0

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.

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't understand if it is sarcasm (because that's also my post) but that post is Arduino to C# and this one is about C# to Arduino.
1

why don't you use a union? that would make your code simpler and more readable:

union {
    byte asBytes[4];
    long asLong;
} foo;

[...]

if (Serial.available() >= 4){
    for (int i=0;i<4;i++){
        foo.asBytes[i] = (byte)Serial.read();
    }
}

Serial.print("letto: ");
Serial.println(foo.asLong);

1 Comment

Yes that's a convinient way. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.