我使用串行通信将字符串从Arduino发送到PC。消息的格式包括字符,价值和空间(分开数据(。示例消息:"H123 V2 L63 V2413 I23 CRC2a"
。我在QT中解码此消息的问题有问题,因为当我使用UTF-8将其铸造整数解码为字符时(以简化的方式(,并且我收到了类似的东西:"H&?? ju0002I&u001AICL?H"
。消息长度不是恒定的(Ex。H12
和H123
的大小不同(,因此我无法使用预定的位置进行投射。您是否知道如何正确解码消息?
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 chars。因此,请使用 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";
}