Search code examples
c#serial-portarduinosend

How to send 4 bytes data ( byte[] ) from C# to Arduino and read it from Arduino?


In another post of mine I was trying to send 4 bytes data (a long integer) from arduino and read it in C# application. It is done. But this time I need to do the opposite. Here is my related part of C# code;

 private void trackBar1_Scroll(object sender, EventArgs e)
        {

            int TrackSend = Convert.ToInt32(trackBar1.Value); //Int to Int32 conversion
            byte[] buffer_2_send = new byte[4];

            byte[] data_2_send = BitConverter.GetBytes(TrackSend);
            buffer_2_send[0] = data_2_send[0];
            buffer_2_send[1] = data_2_send[1];
            buffer_2_send[2] = data_2_send[2];
            buffer_2_send[3] = data_2_send[3];
            if (mySerial.IsOpen)
            {
                mySerial.Write(buffer_2_send, 0, 4);
            }

        }        

And here is the correspondind Arduino code;

void setup()
{
  Serial.begin(9600);
}
unsigned long n = 100;
byte b[4];
char R[4];

void loop()
{
  //Receiving part

  while(Serial.available() == 0){}

    Serial.readBytes(R, 4);       // Read 4 bytes and write it to R[4]

    n = R[0] | (R[1] << 8) | (R[2] << 16) | (R[3] << 24);     // assembly the char array

           //Sending part
  IntegerToBytes(n, b);       // Convert the long integer to byte array
  for (int i=0; i<4; ++i)
  {    
  Serial.write((int)b[i]);
  }
  delay(20);

}

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

When I run the application it sends correctly until 127. When I begin to send values greater than 127 arduino sends me -127, -126, .. and so on. I don't know if problem is in part of sending from C# or reading from Arduino.


Solution

  • I found the solution. After I received the byte array as char array I casted char array to byte array again in the code.

    byte D[4];
    
    D[0] = R[0];
    D[1] = R[1];
    D[2] = R[2];
    D[3] = R[3];