从C#程序向Arduino发送数据

3
我有一个问题,就是从C#程序向Arduino发送数字(每次只发送一个值)。 我注意到,如果我发送的值小于128,那么一切正常,但是当数值变大时就会出现问题。 C#代码:
shinput = Convert.ToInt16(line2); // shinput = short.
byte[] bytes = BitConverter.GetBytes(shinput);
arduino.Write(bytes, 0, 2);

Arduino代码行:

Serial.readBytes(reciver,2);
inByte[counter]= reciver[0]+(reciver[1]*256);

我会非常感激任何帮助。


你的 C# 程序和 Arduino 代码是否使用相同的波特率进行传输? - Cameron MacFarland
1个回答

0

您可以尝试使用已知的值按照已知的顺序进行测试,以确保正确的通信;

arduino.Write(new byte[]{ 145}, 0, 1);
arduino.Write(new byte[]{ 240}, 0, 1);

那么

Serial.readBytes(reciver,1); //check reciver == 145
Serial.readBytes(reciver,1); //check reciver == 240

如果这是正确的,现在测试字节序

arduino.Write(new byte[]{ 145, 240}, 0, 2);

那么

Serial.readBytes(reciver,1); //check reciver == 145
Serial.readBytes(reciver,1); //check reciver == 240

最终,你可能需要一个字节接收器[1] * 256,然后将其强制转换为可以存储更大值的值:
((int) reciver[1] * 256)

那么试试这个:

Serial.readBytes(reciver,2); 
inShort[counter] = (short) reciver[0] | ((short) reciver[1]) << 8;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接