Qt5.2的串口类接收不到串口数据,和事件机制

背景:最近瞎看Qt的东西,然后试了一下Qt自带的串口类。遇到的问题是用串口类始终接收不到数据,但是能发送数据,而且通过其它串口调试助手或者示波器都确认串口硬件没问题。

最后解决问题,并找出问题的原因。详细的过程已经在测试代码注释中标出了经过和原因。对QT的事件机制只有初步概念,不太理解。

/********************************************************************************************************
* 串口接收不到数据的问题,根据邮件列表解决了: https://www.mail-archive.com/[email protected]/msg08724.html
* 1,建议不要在单线程用阻塞读写操作。2,必须用waitForReadyXX(),否则启动不了QT的EventLoop,进而串口也不工作,接收不到数据?
*   总之,感觉QT的串口还不是很稳定,QT5.1才刚加入QSerialPort类
* 2,进阶学习:查看帮助文档中QCoreApplication的exec(),有这么一句,说明通常的QT的GUI程序中,main()程序的最后通过调用QApplication.exec()
*   进入事件循环,非GUI中一般通过QCoreApplication进入事件循环。而进入了Event Loop后,才能和OS交互,接收OS的事件,
*   但是一旦进入此循环相当于阻塞了其它操作。
* It is necessary to call this function to start event handling.
* The main event loop receives events from the window system and dispatches these to the application widgets.
*  To make your application perform idle processing (i.e. executing a special function whenever there are no pending events),
*  use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().
*****************************************************************************************************************/

/**************
 * 功能:串口“COM1"以波特率9600接收数据,并打印出来。
 * 若60秒内,都没有接收到数据,则退出程序。
 * ***********/
#include "mainwindow.h"
#include 
#include 
#include 
#include 
#include 
#include          //qt的输出似乎都要加<
#include 
#include 
#include 
#include 
using namespace std;
int main(int argc, char *argv[])
{
    cout << "hello";
    cout<<"world";
    //QApplication a(argc, argv);
     QCoreApplication a(argc, argv);
    char readbuf[1];
    int res=0;
    QTextStream out(stdout);
    QList  portlist = QSerialPortInfo::availablePorts();

    QSerialPort myport;
    myport.setPortName("COM1");
    myport.open(QIODevice::ReadWrite);
    myport.setDataBits(QSerialPort::Data8);
    myport.setParity(QSerialPort::NoParity);

    myport.setStopBits(QSerialPort::OneStop);
    myport.setFlowControl(QSerialPort::NoFlowControl);
    myport.setBaudRate(QSerialPort::Baud9600);
    myport.setReadBufferSize(1024);

    QByteArray writeData,readData;

 //   writeData.append("abcdefg");
 //   qint64 bytesWritten = myport.write(writeData);
 //   out<<"bytesWriten:"<

实验方法:用串口调试找开另一个串口COM5(USB转串口),COM5输出接到COM1的输入。即同一电脑的COM5向COM1发送数据。COM5随意发送数据

实验分析:就算能接收数据,也只有事件机制方法才合理,当事件通知有数据事件时,再去读数据。总不能一直循环阻塞读吧?方法三就是进程睡眠1S就去读串口。

写法一运行结果:

Qt5.2的串口类接收不到串口数据,和事件机制_第1张图片


写法二:

Qt5.2的串口类接收不到串口数据,和事件机制_第2张图片


写法三:

Qt5.2的串口类接收不到串口数据,和事件机制_第3张图片


你可能感兴趣的:(Qt)