0

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";
}
albert828
  • 50
  • 6
  • 1
    Why do you think you need utf-8 here? Use for example `QString::fromAscii(data.data())` – Michael May 11 '19 at 16:36
  • There's not method called `QString::fromAscii()`. QString Class documentation: [link](https://doc.qt.io/qt-5/qstring.html) – albert828 May 11 '19 at 17:05
  • Baud rate ? Same on both sides ? Which Arduino? String::operator+ is one of the most difficult operations on an avr Arduino. ( And completey unnecessary here) – datafiddler May 11 '19 at 17:11
  • Ok solved I've set in Qt Even Parity but default for Arduino is No Parity. Second thing encoding should be `QString::fromLocal8Bit(data)`. What is strange for `Serial.println("Test")` it worked correctly. Thank you datafiddler and Michael O. – albert828 May 11 '19 at 17:48

1 Answers1

0

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";
}
Ihor Drachuk
  • 1,265
  • 7
  • 17