用QT写一个串口通讯软件,采用485 RTU通讯格式,显示发送和接受的内容
以下是一个简单的串口通讯软件的示例代码,采用QT框架,使用485 RTU通讯格式,并显示发送和接收的内容:
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QByteArray>
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
class SerialPort : public QObject
{
Q_OBJECT
public:
SerialPort(QObject *parent = nullptr) : QObject(parent)
{
// 打开串口
serialPort = new QSerialPort(this);
serialPort->setPortName("COM1");
serialPort->setBaudRate(QSerialPort::Baud115200);
serialPort->setDataBits(QSerialPort::Data8);
serialPort->setParity(QSerialPort::NoParity);
serialPort->setStopBits(QSerialPort::OneStop);
serialPort->setFlowControl(QSerialPort::NoFlowControl);
if (serialPort->open(QIODevice::ReadWrite))
{
qDebug() << "Serial port opened!";
connect(serialPort, SIGNAL(readyRead()), this, SLOT(readData()));
}
else
{
qDebug() << "Serial port open failed!";
}
// 定时发送数据
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(sendData()));
timer->start(1000); // 每隔1秒发送一次数据
}
private slots:
void readData()
{
QByteArray data = serialPort->readAll();
qDebug() << "Received data: " << data.toHex();
}
void sendData()
{
QByteArray data = QByteArray::fromHex("010300000001840A");
serialPort->write(data);
qDebug() << "Sent data: " << data.toHex();
}
private:
QSerialPort *serialPort;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
SerialPort serialPort;
return a.exec();
}
#include "main.moc"
在这个示例代码中,我们创建了一个SerialPort类,它继承自QObject,并且实现了readData()和sendData()两个槽函数,分别用于读取串口接收到的数据和发送数据。在SerialPort类的构造函数中,我们打开了串口,并且连接了readyRead()信号和readData()槽函数。我们还创建了一个定时器,每隔1秒钟发送一次数据。在sendData()函数中,我们使用了QByteArray::fromHex()函数将16进制字符串转换为字节数组,然后使用serialPort->write()函数发送数据。在readData()函数中,我们使用serialPort->readAll()函数读取串口接收到的数据,并使用toHex()函数将字节数组转换为16进制字符串,然后输出到控制台。
注意,这个示例代码中,我们仅仅实现了最简单的串口通讯功能,仅供参考。在实际应用中,我们需要根据具体的需求,添加更多的功能,例如:校验接收到的数据、解析协议、显示数据等。
原文地址: https://www.cveoy.top/t/topic/zDc 著作权归作者所有。请勿转载和采集!