Go Down

Topic: left shift problem (Read 541 times) previous topic - next topic


Hello, I am working on a binary communication between arduino.
and I have faced some problem, I can't retrieve the correct data by using left shift function.

The following code is what I do for sending and receiving binary data, to make troubleshoot easy, i made it in one program.

First, I break the data to 4 byte from first arduino
Second, I will collect back the data using second arduino and combine the 4bytes back into one value.

I am totally have no idea why is it not giving me back my value, please let me know if you can solve it, thanks!

Code: [Select]
long val = 12980992;
byte buffer[4];
long retrieve;

void setup(){

void loop(){
  /*to send out from first arduino*/
  buffer[0] = val&0xff;
  buffer[1] = (val >> 8)&0xff;
  buffer[2] = (val >> 16)&0xff;
  buffer[3] = (val >> 24)&0xff;

  long num;
  int start = 0;

/*to retrieve by second arduino*/     
  num = buffer[start];
  num = (buffer[start + 1] <<8) | num;
  num = (buffer[start + 2] <<16) | num;
  num = (buffer[start + 3] <<24) | num;



Apr 12, 2013, 07:37 pm Last Edit: Apr 12, 2013, 07:45 pm by Hillridge Reason: 1
I'm not positive, but I think it's because you're shifting 8bit values (which are likely handled by 16bit registers) more than 16 bits left.  So after buffer[1] you are just ORing in 0x0000;

Try This:
Code: [Select]
num = buffer[start+3];
 num = (num<<8)|buffer[start + 2];
 num = (num<<8)|buffer[start + 1];
 num = (num<<8)|buffer[start];


To be more clear, here is what's happening line by line:
your initial value is 0x00C61300, so your buffers are:
Code: [Select]

buffer[0]: 0x00
buffer[1]: 0x13
buffer[2]: 0xC6
buffer[3]: 0x00

Here's what happens:
Code: [Select]

num = buffer[start];
//num = 0x00000000
num = (buffer[start + 1] <<8) | num;
//num = (0x13<<8) | 0x00000000
//num = 0x1300 | 0x00000000
//num = 0x00001300
num = (buffer[start + 2] <<16) | num;
//num = (0xC6<<16) | 0x00001300
//num = 0x0000 | 0x00001300  <-this is because the 0xC6 was shifted off the top of the 16bit working register
                                          // You expected 0xC60000 but you get 0x0000
//num = 0x00001300


thanks hillridge, it works perfectly!


Very well explained ! +1
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131