qt串口以线程方式结合linux进行串口 loopback测试完整程序
时间: 2023-07-23 14:39:02 浏览: 56
下面是一个完整的 Qt 串口 loopback 测试程序,可以在 Linux 上运行,并且使用线程来进行串口数据的发送和接收:
```cpp
#include <QCoreApplication>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QThread>
#include <QDebug>
class SerialThread : public QThread
{
public:
SerialThread(QSerialPort *serialPort, QByteArray sendData) :
m_serialPort(serialPort),
m_sendData(sendData)
{
}
void run() override
{
if (m_serialPort->open(QIODevice::ReadWrite))
{
qDebug() << "Serial port opened successfully";
}
else
{
qDebug() << "Failed to open serial port";
return;
}
qDebug() << "Sending data:" << m_sendData;
m_serialPort->write(m_sendData);
QThread::msleep(100);
QByteArray receivedData = m_serialPort->readAll();
qDebug() << "Received data:" << receivedData;
if (receivedData == m_sendData)
{
qDebug() << "Loopback test passed";
}
else
{
qDebug() << "Loopback test failed";
}
m_serialPort->close();
qDebug() << "Serial port closed";
}
private:
QSerialPort *m_serialPort;
QByteArray m_sendData;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "Available serial ports:";
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts())
{
qDebug() << serialPortInfo.portName();
}
QSerialPort serialPort;
serialPort.setPortName("/dev/ttyS0");
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.setParity(QSerialPort::NoParity);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setStopBits(QSerialPort::OneStop);
QByteArray sendData = "Hello world";
SerialThread serialThread(&serialPort, sendData);
serialThread.start();
return a.exec();
}
```
这个程序和上一个程序的区别在于,在主线程中创建了一个 SerialThread 类的实例,然后将串口设备指针和发送的数据作为参数传递给 SerialThread 类的构造函数。SerialThread 类继承自 QThread,并且重写了 run() 方法,run() 方法中进行了串口数据的发送和接收,并输出测试结果。最后,主线程调用了 serialThread.start() 方法来启动新线程。
相关推荐
![](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)