QT 实现串口/dev/ttyS3数据短接收发验证的程序
时间: 2023-12-08 15:05:48 浏览: 54
下面是一个简单的QT程序,用于接收和发送串口(/dev/ttyS3)数据,并进行验证:
```cpp
#include <QCoreApplication>
#include <QDebug>
#include <QSerialPort>
#include <QSerialPortInfo>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 查找可用的串口
QList<QSerialPortInfo> portInfos = QSerialPortInfo::availablePorts();
qDebug() << "Available ports:";
for (const QSerialPortInfo &portInfo : portInfos) {
qDebug() << " " << portInfo.portName();
}
// 打开串口
QSerialPort serial;
serial.setPortName("/dev/ttyS3");
serial.setBaudRate(QSerialPort::Baud9600);
if (!serial.open(QIODevice::ReadWrite)) {
qCritical() << "Failed to open port" << serial.portName() << ":" << serial.errorString();
return 1;
}
// 发送数据
QByteArray sendData("Hello world!");
qDebug() << "Sending data:" << sendData;
qint64 bytesWritten = serial.write(sendData);
if (bytesWritten == -1) {
qCritical() << "Failed to write to port" << serial.portName() << ":" << serial.errorString();
return 1;
} else if (bytesWritten != sendData.size()) {
qWarning() << "Failed to write all data to port" << serial.portName() << ". Only wrote" << bytesWritten << "of" << sendData.size() << "bytes.";
}
// 读取数据
qDebug() << "Reading data from" << serial.portName() << "...";
while (serial.waitForReadyRead(1000)) {
QByteArray data = serial.readAll();
qDebug() << "Read" << data.size() << "bytes:" << data;
if (data == sendData) {
qDebug() << "Verification successful!";
break;
}
}
// 关闭串口
serial.close();
return 0;
}
```
这个程序首先查找可用的串口,并打印出它们的名称。然后它打开串口/dev/ttyS3,并将波特率设置为9600。接下来,它发送一个包含字符串"Hello world!"的数据包,并将其打印到控制台上。然后它进入一个循环,等待串口有数据可读,然后读取所有可用的数据,并将其打印到控制台上。如果读取到的数据与发送的数据相同,则验证成功,并退出循环。最后,它关闭串口并退出程序。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)