qt 串口多线程开发源码
时间: 2023-07-21 21:34:26 浏览: 91
以下是一个简单的Qt串口多线程开发的示例代码:
```
#include <QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QThread>
#include <QDebug>
class SerialPort : public QThread
{
Q_OBJECT
public:
SerialPort(QString portName, QObject *parent = nullptr) :
QThread(parent)
{
m_portName = portName;
m_stop = false;
}
void stop()
{
m_stop = true;
}
signals:
void dataReceived(const QByteArray &data);
protected:
void run() override
{
QSerialPort serialPort;
serialPort.setPortName(m_portName);
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(QSerialPort::NoParity);
serialPort.setStopBits(QSerialPort::OneStop);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
if (!serialPort.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open serial port " << m_portName;
return;
}
while (!m_stop)
{
if (serialPort.waitForReadyRead(100))
{
QByteArray data = serialPort.readAll();
emit dataReceived(data);
}
}
serialPort.close();
}
private:
QString m_portName;
bool m_stop;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
if (ports.isEmpty())
{
qDebug() << "No available serial ports found!";
return 0;
}
SerialPort serialPort(ports.first().portName());
QObject::connect(&serialPort, &SerialPort::dataReceived, [](const QByteArray &data){
qDebug() << "Received data: " << data;
});
serialPort.start();
return a.exec();
}
#include "main.moc"
```
该示例代码实现了一个继承自QThread的SerialPort类,该类在单独的线程中打开串口并等待接收数据,当有数据到达时,将数据通过dataReceived信号发送出去。在主函数中,我们创建了一个SerialPort对象并启动它的线程,同时将dataReceived信号连接到一个lambda函数中,用于接收和处理串口数据。
阅读全文