DAY13-Qt中串口的使用

336 阅读1分钟

Qt中的串口编程

Qt提供了操作串口的类(QSerialPort和QSerialPortInfo),使用他们需要在项目中加入串口模块:

QT += serialport

QSerialPortInfo ---------- 串口信息类

成员函数:
//返回系统中所有的有效串口
[static] QList<QSerialPortInfo> QSerialPortInfo::availablePorts();
​
//串口描述信息
QString QSerialPortInfo::description() const
//串口名
QString QSerialPortInfo::portName() const;

QSerialPort -------- 串口类

构造函数:
//通过QSerialPortInfo构造
QSerialPort::QSerialPort(const QSerialPortInfo &serialPortInfo, QObject *parent = nullptr);
//通过串口名构造
QSerialPort::QSerialPort(const QString &name, QObject *parent = nullptr);
//构造空串口
QSerialPort::QSerialPort(QObject *parent = nullptr);
成员函数:
//通过QSerialPortInfo和串口名绑定串口
void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo);
void QSerialPort::setPortName(const QString &name);

//打开和关闭
[override virtual] bool QSerialPort::open(QIODevice::OpenMode mode);
[override virtual] void QSerialPort::close();
//清空和释放串口
bool QSerialPort::clear(QSerialPort::Directions directions = AllDirections);
[slot] void QObject::deleteLater();//等待事件循环结束再释放

//设置波特率
bool setBaudRate(qint32 baudRate, QSerialPort::Directions directions = AllDirections);
//设置数据位长度
bool setDataBits(QSerialPort::DataBits dataBits);
//设置校验方式
bool setParity(QSerialPort::Parity parity);
//设置停止位长度
bool setStopBits(QSerialPort::StopBits stopBits);
//设置流控制
bool setFlowControl(QSerialPort::FlowControl flowControl);

//发送和接收
信号:
    readyRead -------- 收到了数据
read/readAll --------- 接收数据
write ---------------- 发送数据    

练习:

将Qt的串口程序移植到开发板,如果有两个开发板可以将串口连接(con2)进行通信聊天