C++ How can I parse the data sent from the serial port?
-
I am trying to read ID over serial port. When I send my
WT+12300
command via serial port. I am getting ID data. But it comes all the time and it doesn't come as parsed."WT+,ID,2,3,4,5,6,ASDSA,1,\r\nWT+,ID,2,3,4,5,6,ASDSA,1,\r\nWT+,ID,2, I get it as 3,4,5,6,ASDSA,1,\r\n...
and it keeps going. I just want to take theASDSA
part and display it with a qlabel. How can I do that?
here is functionvoid productDetail::on_pushButton_clicked() { if (serial.begin(QString("COM6"), 9600, 8, 0, 1, 0, false) ) { QString sendWC= "WR+11300"; serial.send(sendWC); QString serialID = serial.getString(); serialID = serialID.simplified(); ui->idLabel->setText(serialID); qDebug()<< serialID; }
-
@mangekoyu said in C++ How can I parse the data sent from the serial port?:
I just want to take the ASDSA part
We don't what the ASDA "part" might mean to you....
In any case, use eitherQString.indexOf()
orQString::match()
to find whatever it is you want in the string. -
@mangekoyu
I don't know what "the 'ASDAS' part" actually is, I have asked you twice, given you an example of what you might mean, and still no answer. So I leave that to you, I'm not going to ask again. If all you want isASDA
on a label golabel->setText("ASDA")
. -
@mangekoyu
Someone has now suggested you mean "The 8th comma-separated item., counting from 0, on each line". They are obviously a better mind-reader than I, since I did not get that.....So.... sounds like you want to
- First,
QString::split()
your input string on\r\n
, to get a list of lines. - Then, split again on
,
to get a list of "items", and you want[7]
.
- First,
-
and it is still wrong because you cannot make assumptions about the content of input streams with regard to completeness. you have to read in and accumulate data until you have enough to parse, then parse what is available and discard what has been successfully processed. Maybe your serial IO is line buffered...maybe it is not. Don't make the assumption that any single serial read contains complete parseable data.