Wire communications not working correctly [solved, easy fix]

Hi all,

I'm using the Wire.h protocol between two Arduinos. The slave board reads analog sensors and then transmits that info to the master Arduino when requested. There are two values to transmit, S and LPM, in that order. These are both integers 0-1023, per the ADC resolution.

When I send the information from one board to the other, S always comes out exactly as it should, but LPM only comes out as 0, 256, 512, or 768. This is as displayed by the main board's Serial.print function. The slave board also has a Serial.print section for diagnostics, and when I monitor the readings, they're exactly as they should be in relation to the sensors. So something is happening between boards.

Here's the code I use to package the data for transmission. In the loop() function:

S = analogRead(Spin);
LPM = analogRead(LPMpin);
Spack(S);
LPMpack(LPM);
outgoing();

And the functions used to pack and send the data:

void Spack(int n)
{
   GiftBox[0] = (byte)(n >> 8);
   GiftBox[1] = (byte)(n);
}

void LPMpack(int n)
{
   GiftBox[2] = (byte)(n >> 8);
   GiftBox[3] = (byte)(n);
}

void outgoing()
{
   Wire.send(GiftBox,4);
}

And on the receiving end, in the loop() function:

Wire.beginTransmission(2);
Wire.requestFrom(2,4);
for(int i=0; i<3; i++)
{
   GiftBox[i]=Wire.receive();
}
unpack(GiftBox);
Wire.endTransmission;

And the code to "unpack" the data in to two separate, usable variables:

void unpack(byte b[4])
{
   Sgift = (b[0] << 8)+(b[1]);
   LPMgift = (b[2] << 8)+(b[3]);
}

And then it's off to Serial.print() and data.print(), etc.

This works flawlessly for S, but LPM never works right. Like I said, the Serial.print() for diagnostics on the slave board shows that the sensor and ADC are working fine, the problem is in the transmission.

I've worked out that it's maybe a problem with the bit-shifting. Here are the relevant bitwise representations of the values I'm getting:

0   = 0000 0000 0000 0000
256 = 0000 0001 0000 0000
512 = 0000 0010 0000 0000
768 = 0000 0011 0000 0000

So what could be causing the error in shifting the proper values in to LPM?

for(int i=0; i<3; i++)
{
   GiftBox[i]=Wire.receive();
}

So, this loop executes when i is 0, 1, and 2. Hard to receive 4 bytes in 3 iterations,

PaulS:

for(int i=0; i<3; i++)

{
   GiftBox[i]=Wire.receive();
}



So, this loop executes when i is 0, 1, and 2. Hard to receive 4 bytes in 3 iterations,

Sigh...it's the little things in life, ya know?

Thanks for spotting my error. I think I need to stop writing code at 3am and debugging at noon.

I almost didn't spot it. I was about to hit the back key and move on.

In the future, you could add Serial.print() statements for debugging. Print the bytes sent, and the bytes received. If you are sending 4 bytes and printing three, that is a pretty good indication that there is a problem with the loop.