2013-03-02 105 views
3

我从C#prog发送数字到Arduino(当时的一个值)有问题。 我注意到,如果我发送的值低于128,那么问题就从更高的值开始。从C#程序发送数据到Arduino

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); 

我会很感激的任何帮助。

+0

是您的C#程序和Arduino的代码在相同的波特率传输? – 2013-03-02 14:10:41

回答

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 

最终很可能是你有一个字节reciver [1] * 256,你需要把它施放成能够存储较大的值的值:

((int) reciver[1] * 256) 

所以试试这个:

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