btnserialtool.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "btnserialtool.h"
  2. BtnSerialTool::BtnSerialTool(QObject *parent) : QObject(parent) { setupSerialPort(); }
  3. // 打开串口的函数
  4. void BtnSerialTool::openSerialPort() {
  5. const QString portName = "COM8";
  6. const qint32 baudRate = 9600;
  7. if (!serialPort.isOpen()) {
  8. serialPort.setPortName(portName);
  9. serialPort.setBaudRate(baudRate);
  10. // 设置数据位,通常为 8 位
  11. serialPort.setDataBits(QSerialPort::Data8);
  12. // 设置停止位,这里设置为 1 位停止位
  13. serialPort.setStopBits(QSerialPort::OneStop);
  14. // 设置校验位,这里设置为无校验
  15. serialPort.setParity(QSerialPort::NoParity);
  16. if (serialPort.open(QIODevice::ReadWrite)) {
  17. emit openCloseButtonTextChanged("关闭串口");
  18. } else {
  19. emit openError();
  20. }
  21. }
  22. }
  23. // 关闭串口的函数
  24. void BtnSerialTool::closeSerialPort() {
  25. if (serialPort.isOpen()) {
  26. serialPort.close();
  27. emit openCloseButtonTextChanged("打开串口");
  28. }
  29. }
  30. bool BtnSerialTool::sendData(const QByteArray &data) {
  31. if (serialPort.isOpen()) {
  32. qint64 bytesWritten = serialPort.write(data);
  33. return bytesWritten == data.size();
  34. }
  35. return false;
  36. }
  37. void BtnSerialTool::handleSendDataReques(const QByteArray &data) { sendData(data); }
  38. void BtnSerialTool::readData() {
  39. QByteArray newData = serialPort.readAll();
  40. buffer.append(newData);
  41. // 查找完整的命令
  42. int startIndex = buffer.indexOf("\\r\\n");
  43. while (startIndex != -1) {
  44. int endIndex = buffer.indexOf("\\r\\n", startIndex + 4);
  45. if (endIndex != -1) {
  46. // 提取完整的命令
  47. QByteArray command = buffer.mid(startIndex + 4, endIndex - startIndex - 4);
  48. emit dataReceived(newData);
  49. qDebug() << "Complete command:" << command;
  50. // 移除已处理的部分
  51. buffer = buffer.mid(endIndex + 4);
  52. } else {
  53. break;
  54. }
  55. startIndex = buffer.indexOf("\\r\\n");
  56. }
  57. qDebug() << "Received data:" << newData;
  58. }
  59. void BtnSerialTool::setupSerialPort() {
  60. openSerialPort();
  61. connect(&serialPort, &QSerialPort::readyRead, this, &BtnSerialTool::readData);
  62. }