Qt 实现多线程的串口通信
2023-09-27 14:20:09 时间
简述
Qt下无论是RS232、RS422、RS485的串口通信都可以使用统一的编码实现。本文把每路串口的通信各放在一个线程中,使用movetoThread的方式实现。
代码之路
用SerialPort类实现串口功能,Widget类调用串口。
serialport.h如下
#include <QObject>
#include <QSerialPort>
#include <QString>
#include <QByteArray>
#include <QObject>
#include <QDebug>
#include <QObject>
#include <QThread>
class SerialPort : public QObject
{
Q_OBJECT
public:
explicit SerialPort(QObject *parent = NULL);
~SerialPort();
void init_port(); //初始化串口
public slots:
void handle_data(); //处理接收到的数据
void write_data(); //发送数据
signals:
//接收数据
void receive_data(QByteArray tmp);
private:
QThread *my_thread;
QSerialPort *port;
};
serailport.cpp如下
#include "serialport.h"
SerialPort::SerialPort(QObject *parent) : QObject(parent)
{
my_thread = new QThread();
port = new QSerialPort();
init_port();
this->moveToThread(my_thread);
port->moveToThread(my_thread);
my_thread->start(); //启动线程
}
SerialPort::~SerialPort()
{
port->close();
port->deleteLater();
my_thread->quit();
my_thread->wait();
my_thread->deleteLater();
}
void SerialPort::init_port()
{
port->setPortName("/dev/ttyS1"); //串口名 windows下写作COM1
port->setBaudRate(38400); //波特率
port->setDataBits(QSerialPort::Data8); //数据位
port->setStopBits(QSerialPort::OneStop); //停止位
port->setParity(QSerialPort::NoParity); //奇偶校验
port->setFlowControl(QSerialPort::NoFlowControl); //流控制
if (port->open(QIODevice::ReadWrite))
{
qDebug() << "Port have been opened";
}
else
{
qDebug() << "open it failed";
}
connect(port, SIGNAL(readyRead()), this, SLOT(handle_data()), Qt::QueuedConnection); //Qt::DirectConnection
}
void SerialPort::handle_data()
{
QByteArray data = port->readAll();
qDebug() << QStringLiteral("data received(收到的数据):") << data;
qDebug() << "handing thread is:" << QThread::currentThreadId();
emit receive_data(data);
}
void SerialPort::write_data()
{
qDebug() << "write_id is:" << QThread::currentThreadId();
port->write("data", 4); //发送“data”字符
}
widget.h的调用代码
1 #include "serialport.h"
2 public slots:
3 void on_receive(QByteArray tmpdata);
4 private:
5 SerialPort *local_serial;
widget.cpp调用代码
//构造函数中
local_serial = new SerialPort();
connect(ui->pushButton, SIGNAL(clicked()), local_serial, SLOT(write_data()),Qt::QueuedConnection);
connect(local_serial, SIGNAL(receive_data(QByteArray)), this, SLOT(on_receive(QByteArray)), Qt::QueuedConnection);
//on_receive槽函数
void Widget::on_receive(QByteArray tmpdata)
{
ui->textEdit->append(tmpdata);
}
相关文章
- Qt之QThread(深入理解)
- 【Linux开发】【Qt开发】tslibs的配置(触摸屏没有,HDMI屏幕):Qt界面响应USB鼠标
- QT学习二:工具栏
- 【QT】QString、QLatin1String、QStringLiteral
- PyQt(Python+Qt)学习随笔:树型部件QTreeWidget中的topLevelItem、indexOfTopLevelItem和takeTopLevelItem方法
- PyQt(Python+Qt)学习随笔:QTreeWidgetItem项列图标的访问方法
- QT多线程简单使用
- 35.QT-多线程
- qt for android蓝牙的连接实现HC-05,控制发送接收数据
- A40i使用笔记:qt在Linux获取系磁盘空间和指定磁盘空间