Sending Long integer values from Arduino and recei

2019-09-17 11:01发布

问题:

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.