<QT障碍之路>qt中使用串口类接收数据不完整

问题:当用QT中的serial->readAll()的时候,不会把全部的数据一次性都读取出来,而是阶段性的。原因是因为当串口有信号时候,readyRead()信号就会被抛出,那么一帧完整的数据帧就可能被分多次接收进来,会影响一些后续的操作。

解决方法:

  1.通讯双方提前定义好帧头和帧尾,方便进行校验。当检测到到帧头和帧尾,才认定一帧数据时完整的。

  2.在readyRead()信号抛出后,再readAll()函数前使用延时函数,等待一帧数据完全发送完成。

 1 /* 以下只是部分代码 */
 2 #include <QTimer>
 3 
 4 int main()
 5 {
 6     QTimer *timer = new QTimer();
 8     connect(timer, SIGNAL(timeout()), this, SLOT(timerStop()));
 9 }
10 
11 void Dialog::timerStop(void)
12 {
13     g_RecBuf.prepend(0xBB);
14     timer->stop();
15     {
16         qDebug()<<g_RecBuf;
17         Dialog::saveDataToFile(g_RecBuf);
18     }
19     g_RecBuf.clear();
20 }
21 
22 void Dialog::readParam()
23 {
24     timer->start(100);
25     g_RecBuf.append(serial->readAll());
26 }
原文地址:https://www.cnblogs.com/zhuangquan/p/10114020.html