Sending Long integer values from Arduino and receiving them from C# app?

狂风中的少年 提交于 2019-12-11 19:45:16

问题


As title gives it away I am trying to just send Long integer values from arduino and receiving it from my C# application.

My Arduino code is

void setup()
{
  Serial.begin(9600);
}

long n;
byte b[4];

void loop()
{
  n=500;
   for (int i=0; i<10; i++)
   {
     n = n+20;
  IntegerToBytes(n, b);
  for (int i=0; i<4; ++i)
  {
  Serial.write((int)b[i]);
  }
  delay(1000);
   }  
}

void IntegerToBytes(long val, byte b[4])
{
  b[3] = (byte )((val >> 24) & 0xff);
  b[2] = (byte )((val >> 16) & 0xff);
  b[1] = (byte )((val >> 8) & 0xff);
  b[0] = (byte )((val) & 0xff);
}

And related C# code is

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            if (mySerial.IsOpen)
            {
                int bytes = mySerial.BytesToRead;

                byte[] byte_buffer = new byte[4];
                mySerial.Read(byte_buffer, 0, 4);
                if (bytes == 4)
                {
                    SerialConverted_LONGValue = BitConverter.ToInt32(byte_buffer, 0);
                }
            }
        }

After I debug the code it just writes the received value to a textbox. I can see just one value, and if any chance, it changes couple of times, as well.

What is wrong with my long to byte[] and byte[] to long conversion?


回答1:


BitConverter does a straight map. It does not know about endianess. Change the order of assignment from 3, 2, 1, 0 to 0, 1, 2, 3.



来源:https://stackoverflow.com/questions/22731322/sending-long-integer-values-from-arduino-and-receiving-them-from-c-sharp-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!