我有一个运行nanopb的微控制器(Arduino Uno),它通过电线发送protobuf消息。我发现在一种特定情况下,我没有收到完整的消息。我想了一会儿是微控制器,但似乎是从它读取的C#端。
仅当uint32值大于16。16或更小时才发生此问题,并且工作正常。
我在微控制器上设置了一个非常简单的程序,以确保不是我的其他代码在那引起了它。本质上,它是通过电线发送一个结构,其中包含一个uint32_t值:
//Protobuf message:
message Test { required uint32 testInt = 1 }
//Resulting struct:
typedef struct Test {
uint32_t testInt;
}
//Serial code:
Serial.begin(115200);
pb_ostream_t ostream;
//Removed ostream setup code as it's not relevant here...
Test message;
Test.testInt = 17;
pb_encode_delimited(&ostream, Test_fields, &message);
如果我插入设备并使用“白蚁”查看其数据输出,则会看到以下数据(正确):
[02] [08] [11] (note Termite displays it in hex)
(也就是说,该消息的长度为2个字节,后跟msg起始字节,后跟Test.testInt值,十六进制为17-0x11)
现在,如果我使用C#编写此消息,则在阅读消息时应该看到3个字节,但是我只看到2个。当testInt中的值等于或小于16时,它遇到的是三个字节,等于或大于17个字节,我只能得到两个:
var port = new SerialPort("COM7", 115200, Parity.None, 8, StopBits.One);
port.Handshake = Handshake.RequestToSendXOnXOff;
port.Open();
while (port.IsOpen)
{
Console.WriteLine(port.ReadByte());
Thread.Sleep(10);
}
port.Close();
Console.ReadLine();
Output with 16: 2 8 16
Output with 17: 2 8 17
非常感谢您的帮助,我对此不知所措=(
您将串行端口设置为使用Xon / Xoff。为什么?
XON的代码是17。
如果要发送二进制数据,请不要使用Xon / Xoff。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句