简述
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,把串口模块加入程序。