qt项目实战实现串口通信
时间: 2023-12-25 13:05:24 浏览: 36
以下是一个基于Qt串口通信模块QSerialPort实现的简单的串口通信项目实战示例,包括发送和接收16进制数据:
```cpp
// 首先在.pro文件中添加:QT += serialport
#include <QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 查找可用串口
QList<QSerialPortInfo> serialPortInfos = QSerialPortInfo::availablePorts();
qDebug() << "The following serial ports are available:";
for (const QSerialPortInfo &serialPortInfo : serialPortInfos) {
qDebug() << serialPortInfo.portName();
}
// 配置串口
QSerialPort serialPort;
serialPort.setPortName("COM1"); // 根据实际情况修改串口名
serialPort.setBaudRate(QSerialPort::Baud9600); // 波特率
serialPort.setDataBits(QSerialPort::Data8); // 数据位
serialPort.setParity(QSerialPort::NoParity); // 校验位
serialPort.setStopBits(QSerialPort::OneStop); // 停止位
serialPort.setFlowControl(QSerialPort::NoFlowControl); // 流控制
// 打开串口
if (!serialPort.open(QIODevice::ReadWrite)) {
qDebug() << "Failed to open serial port!";
return a.exec();
}
// 发送数据
QByteArray sendData = QByteArray::fromHex("01 02 03 04 05"); // 待发送的16进制数据
qint64 bytesWritten = serialPort.write(sendData);
qDebug() << "Bytes written:" << bytesWritten;
// 接收数据
QByteArray readData = serialPort.readAll();
while (serialPort.waitForReadyRead(100)) {
readData.append(serialPort.readAll());
}
qDebug() << "Read data:" << readData.toHex();
// 关闭串口
serialPort.close();
return a.exec();
}
```