QSerialPort read string with "readAll()"
-
Hi and welcome ;)
If you look at Terminal Example you see how to connect up
the readyRead signal and use readall()Normally when you do serial reading. you
will read into a buffer (append to it) until u have the expected number of bytes or a
"end of transmission" char is seen. like newline.
Then a copy of buffer is send to processing and the buffer is cleared and it starts over. -
Thanks for your answer!
I tried to adjust my code and got this here:header: QByteArray charBuffer; .... void MainWindow::readData() { QByteArray data = serial->readAll(); console->putData(data,false); charBuffer.append(data); if (data.contains("\n")) //read into a structure until newline received. { QString myString(charBuffer); if(myString.startsWith("SensorUpdate")) emit sensorData(myString); charBuffer = ""; } }
But it still doesn't work :(
-
hi have you checked that input actually do contain "\n" ?
Also which part is not working ?
Does it enter
if (data.contains("\n")) //read into a structure until newline received.
{
...or not?
Code does look fine :)
-
@mrjj The data i receive is correct. I used the debugger and got these results:
data = "\r\nSensorupdate ,var1,var2,var3"
myString ="\r\nSensorupdate ,var1,var2,var3";But the if statement does not work. The string is not emitted. I tried to use several if statements ("contains("\r\nSensorupdate","containts("Sensorupdate"),startsWirth("\r\nSensorupdate"). All of them dont seem to work.
I tried my original code again to make sure nothing changed and yes it still works with the readLine() function... Darnnnn!
-
@Basti46
Ok try with indexof
http://doc.qt.io/qt-5/qstring.html#indexOf
and Qt::CaseInsensitivei do wonder why containts("Sensorupdate") dont see it.
Seems your \n comes first in data ?
-
@mrjj
Sooooo i think i found the problems!data from serialPort Example:
does work
"Sensorupdate ,var1,var2\r\n";
does not work yet
"\r\n"Sensorupdate ,var1,var2";
does not work
"Sensorupdate ,Sensor1,var2\r\n";
"Sensorupdate ,Sensor2,var2\r\n";If i get more than one line at each run my gui is not able to handle the data. The readAll function is too fast and gives too much data too handle at a time. I need to handle each line one by one but the readAll function gives me several lines. Soo a solution would be to store the data into a file and read it from there. But maybe there is something else.
Thanks @mrjj for ur time :D -
hi
in you GUI
you could split the QString into a list
http://doc.qt.io/qt-5/qstring.html#split
split on \n
Then loop the list and handle each as you normally would.
So would not matter if u get more than one in as input.