#include "btnserialtool.h" BtnSerialTool::BtnSerialTool(QObject *parent) : QObject(parent) { setupSerialPort(); } // 打开串口的函数 void BtnSerialTool::openSerialPort() { const QString portName = "COM8"; const qint32 baudRate = 9600; if (!serialPort.isOpen()) { serialPort.setPortName(portName); serialPort.setBaudRate(baudRate); // 设置数据位,通常为 8 位 serialPort.setDataBits(QSerialPort::Data8); // 设置停止位,这里设置为 1 位停止位 serialPort.setStopBits(QSerialPort::OneStop); // 设置校验位,这里设置为无校验 serialPort.setParity(QSerialPort::NoParity); if (serialPort.open(QIODevice::ReadWrite)) { emit openCloseButtonTextChanged("关闭串口"); } else { emit openError(); } } } // 关闭串口的函数 void BtnSerialTool::closeSerialPort() { if (serialPort.isOpen()) { serialPort.close(); emit openCloseButtonTextChanged("打开串口"); } } bool BtnSerialTool::sendData(const QByteArray& data) { if (serialPort.isOpen()) { qint64 bytesWritten = serialPort.write(data); return bytesWritten == data.size(); } return false; } void BtnSerialTool::handleSendDataReques(const QByteArray &data) { sendData(data); } void BtnSerialTool::readData() { QByteArray newData = serialPort.readAll(); buffer.append(newData); // 查找完整的命令 int startIndex = buffer.indexOf("\\r\\n"); while (startIndex != -1) { int endIndex = buffer.indexOf("\\r\\n", startIndex + 4); if (endIndex != -1) { // 提取完整的命令 QByteArray command = buffer.mid(startIndex + 4, endIndex - startIndex - 4); emit dataReceived(newData); qDebug() << "Complete command:" << command; // 移除已处理的部分 buffer = buffer.mid(endIndex + 4); } else { break; } startIndex = buffer.indexOf("\\r\\n"); } qDebug() << "Received data:" << newData; } void BtnSerialTool::setupSerialPort() { openSerialPort(); connect(&serialPort, &QSerialPort::readyRead, this, &BtnSerialTool::readData); }