btnserialtool.cpp 2.2 KB

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