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";
}
4

1 回答 1

0

问题是您使用 UTF-8 解码,而 Arduino 仅发送 1 字节 ASCII 字符。所以fromLocal8Bit像说的那样使用 albert828

像这样:

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";
}
于 2020-07-25T20:41:29.413 回答