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?