Go Down

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

#### paramesium

##### Apr 12, 2013, 07:03 pm
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(){  Serial.begin(38400);}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;          Serial.println(num);  delay(500);}`

Best,
Jack

#### Hillridge

#1
##### Apr 12, 2013, 07:37 pmLast 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];`

Edit:

To be more clear, here is what's happening line by line:
Code: [Select]
`buffer[0]: 0x00buffer[1]: 0x13buffer[2]: 0xC6buffer[3]: 0x00`
Here's what happens:
Code: [Select]
`num = buffer[start];//num = 0x00000000num = (buffer[start + 1] <<8) | num;//num = (0x13<<8) | 0x00000000//num = 0x1300 | 0x00000000//num = 0x00001300num = (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`

#### paramesium

#2
##### Apr 12, 2013, 07:45 pm
thanks hillridge, it works perfectly!

#### robtillaart

#3
##### Apr 13, 2013, 10:16 am
@Hillridge,
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