I'm sending string from Arduino to PC using serial communication. Format of message includes char, value and space (separating data). Example message: "H123 V2 L63 V2413 I23 CRC2a"
.
I have problem with decoding this message in Qt because when I use for example Utf-8 decoding it casting integers to chars (in a simplified way) and I receiving something like that: "H&?? j\u0002I&\u001AICL?H"
. Message length is not constant (different size for ex. H12
and H123
) so I can't use predetermined position to casting. Do you have any idea how to decode message correctly?
Arduino code:
uint8_t H = 0, V = 0, L = 0, I = 0, CRC = 0;
String data;
void loop() {
++H; ++V; ++L; ++I;
data = String("H");
data += String(H, DEC);
data += String(" V");
data += String(V, DEC);
data += String(" L");
data += String(L, DEC);
data += String(" I");
data += String(I, DEC);
CRC = CRC8(data.c_str(), strlen(data.c_str()));
data += String(" CRC");
data += String(CRC, HEX);
Serial.println(data);
delay(1000);
}
Qt code:
while(serial.isOpen())
{
QByteArray data;
if (serial.waitForReadyRead(1000))
{
data = serial.readLine();
while (serial.waitForReadyRead(100))
{
data += serial.readAll();
}
QString response = QString::fromUtf8(data);
qDebug() << "Data " << response << endl;
}
else
qDebug() << "Timeout";
}
The problem is that you use UTF-8 decoding, while Arduino send just 1-byte ASCII chars. So use fromLocal8Bit
as said albert828
Like this:
while(serial.isOpen())
{
QByteArray data;
if (serial.waitForReadyRead(1000))
{
data = serial.readLine();
while (serial.waitForReadyRead(100))
{
data += serial.readAll();
}
QString response = QString::fromLocal8Bit(data);
qDebug() << "Data " << response << endl;
}
else
qDebug() << "Timeout";
}