为了不影响程序其他功能,本人创建了一个线程,用新建线程接收串口数据,串口50Hz的数据。 说明:系统为Win7 64位,Qt为5.6 MingW新建线程已经通过某个按钮启动,同时也通过某个按钮停止,通过调试也能看到线程能够启动;通过串口调试工具也能收到数据。 问题1:上述程序中串口无法接收到数据。 问题2:注释掉的connect()函数用上也不能进入信号的槽函数,即也是无法收到数据。 请各位大神帮忙指导啊!小弟的饭碗就指这个程序了啊。 新建线程如下: 新建线程 .pro文件: QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport QT+=network QT+=serialport .h文件: #ifndef COMTHREAD_H #define COMTHREAD_H #include <QObject> #include <QThread> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> class ComThread : public QThread { Q_OBJECT public: ComThread(); //~ComThread(); void stop(); QByteArray TxData; bool comopen=false; struct ComRxData \\接收数据的结构体 { ushort head; int hyzl; int hyfk; int zyzl; int zyfk; ushort tail; }; struct ComTxData { ushort head; ushort hyfz; ushort hyzq; ushort zyfz; ushort zyzq; ushort tail; }; QSerialPort *Com1Port; QByteArray RxData; private slots: //void ComDataProcess(); protected: void run(); private: volatile bool stopped; volatile bool com_opened; }; #endif // COMTHREAD_H .cpp文件: #include "comthread.h" #include "widget.h" #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> #include <QDebug> extern volatile double HYZL; //hy指令 extern volatile double HYRT; //hy实际值 extern volatile double ZYZL; //zy指令 extern volatile double ZYRT; //zy实际值 ComThread::ComThread() { stopped=false; } void ComThread::run() { Com1Port=new QSerialPort("COM1"); //Com1Port->setPortName("COM1"); if(!com_opened&&(!stopped)) { com_opened=true; comopen=Com1Port->open(QIODevice::ReadWrite); //打开串口并设置串口参数 Com1Port->setBaudRate(QSerialPort::Baud115200); Com1Port->setDataBits(QSerialPort::Data8); Com1Port->setParity(QSerialPort::NoParity); Com1Port->setStopBits(QSerialPort::OneStop); Com1Port->setFlowControl(QSerialPort::NoFlowControl); //connect(Com1Port,SIGNAL(readyRead()),this,SLOT(ComDataProcess())); } while(!stopped) { //for(int n=0;n<10;n++) //{ //qDebug()<<n<<n<<n<<n<<n<<n<<n; //} RxData=Com1Port->readAll(); //读取串口所有的数据 if(RxData!=NULL) { ComRxData theRx; //串口接收数据的结构体 memcpy(&theRx.hyzl,&RxData.data()[2],4); HYZL=(double)theRx.hyzl/1000; memcpy(&theRx.hyfk,&RxData.data()[6],4); HYRT=(double)theRx.hyfk/1000; memcpy(&theRx.zyzl,&RxData.data()[10],4); ZYZL=(double)theRx.zyzl/1000; memcpy(&theRx.zyfk,&RxData.data()[14],4); ZYRT=(double)theRx.zyfk/1000; } if(stopped&&com_opened) { Com1Port->close(); com_opened=false; delete Com1Port; //将串口对象删除 } } stopped=false; } void ComThread::stop() { stopped=true; } //void ComThread::ComDataProcess() //{ // RxData=Com1Port->readAll(); //读取串口所有的数据 // ComRxData theRx; //串口接收数据的结构体 // memcpy(&theRx.hyzl,&RxData.data()[2],4); // HYZL=(double)theRx.hyzl/1000; // memcpy(&theRx.hyfk,&RxData.data()[6],4); // HYRT=(double)theRx.hyfk/1000; // memcpy(&theRx.zyzl,&RxData.data()[10],4); // ZYZL=(double)theRx.zyzl/1000; // memcpy(&theRx.zyfk,&RxData.data()[14],4); // ZYRT=(double)theRx.zyfk/1000; //}
|