大家好,我最近在写一个程序,建立了一个子线程,子线程中使用串口进行数据的收发,但是实际测试在串口操作的时候只能发送,无法接收,进一步定位发现readyread信号未被触发,网上的方法基本都试了一遍都不行,想看看大家有没有类似的经历,可以给我提供一些建议,感激不尽!
贴一下代码
子线程
#ifndef APPTHREAD_H
#define APPTHREAD_H
#include <QObject>
#include <QSerialPort>
#include <QElapsedTimer>
#include <QDebug>
#include <qtimer.h>
class AppThread : public QObject
{
Q_OBJECT
public:
explicit AppThread(QObject *parent = nullptr);
void AppTask();
QSerialPort *port;
QTimer *portTimer;
QByteArray *dataArray;
quint8 *portRecvData;
bool portSendMsg( quint8* msg ,int msgLen);
int msgLen;
bool recvFlag;
bool Init();
signals:
private slots:
void recvData();
void timerUpdate();
};
#endif // APPTHREAD_H
子线程cpp
#include "appthread.h"
#include <QDebug>
#include <QThread>
AppThread::AppThread(QObject *parent) : QObject(parent)
{
}
void AppThread::AppTask()
{
qDebug() << "当前线程对象的地址: " << QThread::currentThread();
if(Init())
{
qDebug()<<"init";
}
quint8 data[]={0x01,0x02,0x03,0x05,0x08};
portSendMsg(data,5);
while (1) {
}
}
bool AppThread::Init()
{
//串口初始化
port=new QSerialPort();
portTimer=new QTimer();
connect(port,&QSerialPort::readyRead,this,&AppThread::recvData);
connect(portTimer,&QTimer::timeout,this,&AppThread::timerUpdate);
port->setParity(QSerialPort::NoParity);
port->setDataBits(QSerialPort::Data8);
port->setStopBits(QSerialPort::OneStop);
port->setPortName("ttyUSB0");
port->setBaudRate(QSerialPort::Baud115200);
port->open(QIODevice::ReadWrite);
return port->isOpen();
}
bool AppThread::portSendMsg( quint8* msg ,int msgLen)
{
QByteArray sendDate;
sendDate.resize(msgLen);
for(int i=0;i<msgLen;i++)
{
sendDate[i]=msg[i];
}
port->write(sendDate);
QTimer timer;
timer.start(500);
while (!port->waitForBytesWritten())
{
if(timer.remainingTime())
{
qDebug()<<"no11";
timer.stop();
return false;
}
}
timer.stop();
qDebug()<<"yes";
return true;
}
void AppThread::recvData()
{
portTimer->start(30);//30ms
dataArray->append(port->readAll());
qDebug()<<"111";
}
void AppThread::timerUpdate()
{
portTimer->stop();
msgLen=dataArray->size();
qDebug()<<dataArray;
recvFlag=true;
}