2013-03-02 111 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; 
相關問題