Qt 串口通信:接收并解析 16 进制数据
在 Qt 中进行串口通信,可以使用 Qt 的 QSerialPort 类。下面是一个示例代码,用于收取 16 进制数据:
#include <QCoreApplication>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 获取可用的串口列表
QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
if (portList.isEmpty()) {
qDebug() << 'No serial ports found.';
return a.exec();
}
// 选择第一个可用的串口
QSerialPortInfo portInfo = portList.first();
qDebug() << 'Using serial port:' << portInfo.portName();
// 打开串口
QSerialPort serial;
serial.setPort(portInfo);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
if (!serial.open(QIODevice::ReadOnly)) {
qDebug() << 'Failed to open serial port.';
return a.exec();
}
// 读取串口数据
while (true) {
if (serial.waitForReadyRead(1000)) {
QByteArray data = serial.readAll();
// 将接收到的数据转换为 16 进制字符串
QString hexData = data.toHex().toUpper();
qDebug() << 'Received data:' << hexData;
}
}
return a.exec();
}
上述代码会打开第一个可用的串口,并以 9600 波特率、8 数据位、无校验位、1 停止位、无流控制进行配置。然后,它会持续地读取串口数据,并将收到的数据转换为 16 进制字符串进行输出。
注意:这个示例代码演示了如何接收串口数据,并将其转换为 16 进制字符串进行输出。如果要进一步处理接收到的数据,可以根据具体需求进行修改。
原文地址: https://www.cveoy.top/t/topic/oZRv 著作权归作者所有。请勿转载和采集!