简体   繁体   中英

Sending data from C# program to Arduino

I have a problem with sending numbers from the C# prog to the Arduino (one value at the time). I noticed that if I send value lower than 128 its ok, the problems started with higher values.

C# lines:

shinput = Convert.ToInt16(line2); // shinput = short.
byte[] bytes = BitConverter.GetBytes(shinput);
arduino.Write(bytes, 0, 2);

Arduino lines:

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

I will really appreciate any help.

You can try to test with known values to ensure proper communication, in a known order;

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

then

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

Assuming this is correct, now test the Endianness

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

then

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

in the end it may well be that you have a byte reciver[1] * 256 and you need to cast it up to a value that can store the larger value:

((int) reciver[1] * 256)

so try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM