QT Serialport GUI and worker thread
-
First things first, I'm a newbie in QT so don't blame me. I know that many similar questions have been in the forum, but I couldn't solve my problem.
Problem description. I want to have a GUI application that receives and parses data and update some qt widget. Formerly I did them all in the Mainwindow thread, but since it hangs, I tried to make it multi-threaded. But it still hangs when I try to update GUI data as fast as 10 ms.Now, this is what I have tried.
int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }class Parser : public QThread , public QRunnable { Q_OBJECT public: explicit Parser(QThread *parent = nullptr); ~Parser(); signals: void data1Available(unsigned char*); void data2Available(unsigned char*); void finished(); // QRunnable interface public: void run(); public slots: void parse(); };MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect( &SerialPort, SIGNAL(readyRead()), this, SLOT(ReadData()) ); QThread* thread = new QThread; thread->setObjectName("Parser Thread"); qInfo()<<"Parser Thread"; Parser* parser= new Parser(); parser->moveToThread(thread); QObject::connect(thread,&QThread::started,parser,&Parser::run); QObject::connect(parser,&Parser::finished,parser,&Parser::deleteLater); QObject::connect(parser,&Parser::finished,thread,&QThread::quit); QObject::connect(thread,&QThread::finished,thread,&QThread::deleteLater); QObject::connect(parser,SIGNAL(data1Available(unsigned char *)),this,SLOT(on_data1Available(unsigned char *))); QObject::connect(parser,SIGNAL(data2Available(unsigned char *)),this,SLOT(on_data2Available(unsigned char *))); thread->start(); }void MainWindow::ReadData() { QByteArray Data = SerialPort.readAll(); for (unsigned char i=0;i<Data.length();i++) circBuff.append(Data[i]); }void MainWindow::on_data1Available(unsigned char* tempData) { ui->label1->setNum(tempData[5]); } void MainWindow::on_data2Available(unsigned char* tempData) { ui->label2->setNum(tempData[7]); }void Parser::run() { qInfo()<<this<<Q_FUNC_INFO<<QThread::currentThread(); QScopedPointer<QEventLoop> loop (new QEventLoop); QScopedPointer<QTimer> timer (new QTimer); timer->setInterval(5); connect(timer.data(),&QTimer::timeout,this,&Parser::parse); connect(this,&Parser::finished,loop.data(),&QEventLoop::quit); timer->start(); loop->exec(); qInfo()<<this<<"Finished... "<<QThread::currentThread(); }void Parser::parse() { unsigned char tempData[16]; while (1) { while (circBuff.size()>=16) { if ( ) { if () emit data1Available(tempData); else emit data2Available(tempData); } } } emit finished(); } -
There is absolutely no need to use a thread for QSerialPort since it's asynchronous.
If your ui hangs then use a debugger and see why it hangs.Your code above doesn't make any sense - neither the threading is correctly done nor is QSerialPort reading done in the secondary thread nor is the buffer (circBuff) shared between the threads (and if it would then a proper locking mechnism is missing). Please stop using threads for such kind of stuff. This was told all newbieas here - first get in touch with Qt, learn proper c++ and then maybe learn how to correctly use a thread but not the other way round.
-
There is absolutely no need to use a thread for QSerialPort since it's asynchronous.
If your ui hangs then use a debugger and see why it hangs.Your code above doesn't make any sense - neither the threading is correctly done nor is QSerialPort reading done in the secondary thread nor is the buffer (circBuff) shared between the threads (and if it would then a proper locking mechnism is missing). Please stop using threads for such kind of stuff. This was told all newbieas here - first get in touch with Qt, learn proper c++ and then maybe learn how to correctly use a thread but not the other way round.
@Christian-Ehrlicher thank you for your reply
For the first step you suggest me to transfer the reading of serial port data to the same thread of parser. Then make blocking access to circular buffer in the same thread.
For the second step should I use the event loops?
For the third step of sharing circBuf how should I deep dive in QT? Which document resources would you suggest me to read or video to watch? -
Hi vahid. use this code to read serial port:
//define your class like this PortSerial::PortSerial(QString port, int dev) { if(!openport(port)) { printErrors("PortSerial","Port:"+port+" can not open."); } moveToThread(&t);// hear put the code to thread to avoid hanging connect(&t,SIGNAL(started()),this,SLOT(readserialport()));//connect the thread start to read serial port t.start(); } int PortSerial::openport(QString port) { printErrors("openport","start fn"); serialport.setPortName(port); serialport.setParity(QSerialPort::NoParity); serialport.setStopBits(QSerialPort::OneStop); serialport.setFlowControl(QSerialPort::NoFlowControl); serialport.setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections); //serial port return bool. if(serialport.open(QIODevice::ReadWrite)) return 1; else return 0; } void PortSerial::writeData(QByteArray ba) { printErrors("writeData","start fn"); serialport.write(ba); } void PortSerial::readserialport() { printErrors("readserialport","start fn"); while (1) { if(serialport.waitForReadyRead(100)) { myque.clear(); printErrors("readserialport","the queue is clean"); printErrors("readserialport","wait for read data from sensor"); QByteArray responseData=serialport.readAll(); while (serialport.waitForReadyRead(100)) { responseData+=serialport.readAll(); } printErrors("readserialport","read:"+responseData.toHex()+"\n devid : "+devid); emit readyread(responseData,devid); } } }after that you can connect any slot to this signal to receive the data from your serial port with out hanging in GUI
-
Hi vahid. use this code to read serial port:
//define your class like this PortSerial::PortSerial(QString port, int dev) { if(!openport(port)) { printErrors("PortSerial","Port:"+port+" can not open."); } moveToThread(&t);// hear put the code to thread to avoid hanging connect(&t,SIGNAL(started()),this,SLOT(readserialport()));//connect the thread start to read serial port t.start(); } int PortSerial::openport(QString port) { printErrors("openport","start fn"); serialport.setPortName(port); serialport.setParity(QSerialPort::NoParity); serialport.setStopBits(QSerialPort::OneStop); serialport.setFlowControl(QSerialPort::NoFlowControl); serialport.setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections); //serial port return bool. if(serialport.open(QIODevice::ReadWrite)) return 1; else return 0; } void PortSerial::writeData(QByteArray ba) { printErrors("writeData","start fn"); serialport.write(ba); } void PortSerial::readserialport() { printErrors("readserialport","start fn"); while (1) { if(serialport.waitForReadyRead(100)) { myque.clear(); printErrors("readserialport","the queue is clean"); printErrors("readserialport","wait for read data from sensor"); QByteArray responseData=serialport.readAll(); while (serialport.waitForReadyRead(100)) { responseData+=serialport.readAll(); } printErrors("readserialport","read:"+responseData.toHex()+"\n devid : "+devid); emit readyread(responseData,devid); } } }after that you can connect any slot to this signal to receive the data from your serial port with out hanging in GUI
@MhM93
As in your other thread on this subject. You should not use or recommend to others the use of a thread to do asynchronous serial port IO. That is just what the other posters are telling the OP here. And you should not have code like yourreadserialport()which useswaitForReadyRead(), multiple times and in loops. -
For those who engaged in this topic, formerly I used an older version of QT, upgrading to the latest version solved the backend problem aka serial port and parsing data. I made use of multithreading and mutex.
-
For those who engaged in this topic, formerly I used an older version of QT, upgrading to the latest version solved the backend problem aka serial port and parsing data. I made use of multithreading and mutex.
@Vahid-Ajallooeian said in QT Serialport GUI and worker thread:
I made use of multithreading and mutex.
That seems a shame, but up to you.