簡體   English   中英

從串口解碼數據(帶整數的字符串)

[英]Decoding data from serial port (string with integers)

我正在使用串行通信將字符串從 Arduino 發送到 PC。 消息格式包括字符、值和空格(分隔數據)。 示例消息: "H123 V2 L63 V2413 I23 CRC2a" 我在 Qt 中解碼此消息時遇到問題,因為當我使用例如 Utf-8 解碼時,它會將整數轉換為字符(以簡化的方式)並且我收到類似這樣的信息: "H&?? j\I&\ICL?H" 消息長度不是恆定的(例如H12H123大小不同),因此我無法使用預定位置進行投射。 您知道如何正確解碼消息嗎?

Arduino代碼:

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代碼:


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

問題是您使用 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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM