簡述
Qt下無論是RS232、RS422、RS485的串口通信都可以使用統一的編碼實現。本文把每路串口的通信各放在一個線程中,使用movetoThread的方式實現。
代碼之路
用SerialPort類實現串口功能,Widget類調用串口。
serialport.h如下
1 #include <QObject>
2 #include <QSerialPort>
3 #include <QString>
4 #include <QByteArray>
5 #include <QObject>
6 #include <QDebug>
7 #include <QObject>
8 #include <QThread>
9
10 class SerialPort : public QObject 11 { 12 Q_OBJECT 13 public: 14 explicit SerialPort(QObject *parent = NULL); 15 ~SerialPort(); 16
17 void init_port(); //初始化串口
18
19 public slots: 20 void handle_data(); //處理接收到的數據
21 void write_data(); //發送數據
22
23 signals: 24 //接收數據
25 void receive_data(QByteArray tmp); 26
27 private: 28 QThread *my_thread; 29 QSerialPort *port; 30 };
serailport.cpp如下
1 #include "serialport.h"
2
3 SerialPort::SerialPort(QObject *parent) : QObject(parent) 4 { 5 my_thread = new QThread(); 6
7 port = new QSerialPort(); 8 init_port(); 9 this->moveToThread(my_thread); 10 port->moveToThread(my_thread); 11 my_thread->start(); //啟動線程
12
13 } 14
15 SerialPort::~SerialPort() 16 { 17 port->close(); 18 port->deleteLater(); 19 my_thread->quit(); 20 my_thread->wait(); 21 my_thread->deleteLater(); 22 } 23
24 void SerialPort::init_port() 25 { 26 port->setPortName("/dev/ttyS1"); //串口名 windows下寫作COM1
27 port->setBaudRate(38400); //波特率
28 port->setDataBits(QSerialPort::Data8); //數據位
29 port->setStopBits(QSerialPort::OneStop); //停止位
30 port->setParity(QSerialPort::NoParity); //奇偶校驗
31 port->setFlowControl(QSerialPort::NoFlowControl); //流控制
32 if (port->open(QIODevice::ReadWrite)) 33 { 34 qDebug() << "Port have been opened"; 35 } 36 else
37 { 38 qDebug() << "open it failed"; 39 } 40 connect(port, SIGNAL(readyRead()), this, SLOT(handle_data()), Qt::QueuedConnection); //Qt::DirectConnection
41 } 42
43 void SerialPort::handle_data() 44 { 45 QByteArray data = port->readAll(); 46 qDebug() << QStringLiteral("data received(收到的數據):") << data; 47 qDebug() << "handing thread is:" << QThread::currentThreadId(); 48 emit receive_data(data); 49 } 50
51 void SerialPort::write_data() 52 { 53 qDebug() << "write_id is:" << QThread::currentThreadId(); 54 port->write("data", 4); //發送“data”字符
55 }
widget.h的調用代碼
1 #include "serialport.h"
2 public slots: 3 void on_receive(QByteArray tmpdata); 4 private: 5 SerialPort *local_serial;
widget.cpp調用代碼
1 //構造函數中
2 local_serial = new SerialPort(); 3 connect(ui->pushButton, SIGNAL(clicked()), local_serial, SLOT(write_data()),Qt::QueuedConnection); 4 connect(local_serial, SIGNAL(receive_data(QByteArray)), this, SLOT(on_receive(QByteArray)), Qt::QueuedConnection); 5 //on_receive槽函數
6 void Widget::on_receive(QByteArray tmpdata) 7 { 8 ui->textEdit->append(tmpdata); 9 }
寫在最后
本文例子實現的串口號是 /dev/ttyS1(對應windows系統是COM1口),波特率38400,數據位8,停止位1,無校驗位的串口通信。當然,使用串口程序前,需要在.pro文件中添加 QT += serialport,把串口模塊加入程序。