Reading continuous data from Serial Port
-
Hi friends,
I am new for QT C++ and am trying to write a program, which could continuous read data from Serial Port. My Program works sometimes smoothly but sometimes it read wrong data. I have run debug and here is what I got:"61\x00\x00" "61\x00\x00" "61\x00\x00" "62\x00\x00" "62\x00\x00" "62\x00\x00" "62\x00\x00" "63\x00\x00" "63\x00\x00" "5" "3\x00\x00" "5" "2\x00\x00" "5" "2\x00\x00"
"54\x00\x00" "54\x00\x00" "54\x00\x00" "55\x00\x00" "54\x00\x00" "54\x00\x00" "55\x00\x00" "55\x00\x00" "5" "1\x00\x00" "51" "\x00\x00" "5" "2\x00\x00" "5" "1\x00\x00" "5" "1\x00\x00"
Someway QTSerialPort didn't read all data. And here is my code, where data should be read and display.
if(serial->isOpen() && serial->isReadable()){ QByteArray receivedData; receivedData = serial->readAll(); qDebug()<<receivedData; ui->lcdDistance->display(receivedData.toInt()); }else{ QMessageBox::critical(this, tr("Error"), tr("Doesn't receive data")); }
I think the problem came from QT, not the microcontroller because I also run debug with my microcontroller and it worked very well.
Please help me to solve this problem. Thanks in advance.
-
QSerialPort is async - connect to the readyRead() signal and read the data data. What you do here can't work since readAll() is non-blocking (and that's fine)
-
Hi,
Serial port data are not guaranteed to arrive as full frames.
You should cumulate the data you get and then check if a full frame can be found in that buffer, process it and then go on.