给我一个qt串口通信的代码
时间: 2023-12-25 10:04:15 浏览: 31
以下是一个基于Qt的串口通信代码示例:
```c++
#include <QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSerialPort serialPort;
serialPort.setPortName("COM3"); // 设置串口号
serialPort.setBaudRate(QSerialPort::Baud115200); // 设置波特率
serialPort.setDataBits(QSerialPort::Data8); // 设置数据位
serialPort.setParity(QSerialPort::NoParity); // 设置校验位
serialPort.setStopBits(QSerialPort::OneStop); // 设置停止位
serialPort.setFlowControl(QSerialPort::NoFlowControl); // 设置流控制
if (!serialPort.open(QIODevice::ReadWrite)) {
qDebug() << "串口打开失败!";
return a.exec();
}
qDebug() << "串口已打开!";
// 连接信号与槽函数
QObject::connect(&serialPort, &QSerialPort::readyRead, [&serialPort](){
QByteArray data = serialPort.readAll(); // 读取串口数据
qDebug() << "收到数据:" << data;
});
// 发送数据
QByteArray sendData = "Hello, World!";
serialPort.write(sendData);
qDebug() << "发送数据:" << sendData;
return a.exec();
}
```
上述代码首先设置了串口的参数,然后打开串口并连接`QSerialPort`的`readyRead`信号和一个槽函数以读取串口数据。最后发送了一段数据到串口中。