I am using arduino as a I2C master to read a 'long' type data from the I2C bus. I found every byte I receive is right. But I encounter some difficulties when I want to 'recover' the original 'long' type data. The data is transmitted MSB first.
I read the data on the I2C bus into a four bytes unsigned char array and then convert it. This is my code.
void ReadData4(unsigned char cmdSend, long* data)
{
unsigned char d[4];
// command
cmd[0] = cmdSend;
// send command
Wire.beginTransmission(0x50); // transmit to device, 0x50 is the address of neurons motor module
Wire.write(cmd,1); // sends command
Wire.endTransmission(); // stop transmitting
//read
Wire.requestFrom(0x50, 4); // request 4 bytes from slave
if (Wire.available())
{
d[0] = Wire.read(); // receive a byte as character
}
if (Wire.available())
{
d[1] = Wire.read(); // receive a byte as character
}
if (Wire.available())
{
d[2] = Wire.read(); // receive a byte as character
}
if (Wire.available())
{
d[3] = Wire.read(); // receive a byte as character
}
Serial.print(d[0], HEX); // print the character
Serial.print('\n');
Serial.print(d[1], HEX); // print the character
Serial.print('\n');
Serial.print(d[2], HEX); // print the character
Serial.print('\n');
Serial.print(d[3], HEX); // print the character
Serial.print('\n');
*data = 0;
*data |= (d[3]);
*data |= (d[2] << 8);
*data |= (d[1] << 16);
*data |= (d[0] << 24);
Serial.print(*data, HEX); // print the character
Serial.print('\n');
return;
}
and this is my output from uart:
FF
D1
AA
DC
FFFFAADC
It looks the single bytes are read correctly. But the second 'FF' in the 'FFFFAADC' should be D1.
then I tried a really simple code:
unsigned char d[4];
d[0] = 0xFF;
d[1] = 0xD1;
d[2] = 0xAA;
d[3] = 0xCD;
Serial.print(d[0], HEX); // print the character
Serial.print('\n');
Serial.print(d[1], HEX); // print the character
Serial.print('\n');
Serial.print(d[2], HEX); // print the character
Serial.print('\n');
Serial.print(d[3], HEX); // print the character
Serial.print('\n');
*data = 0;
*data |= (d[3]);
*data |= (d[2] << 8);
*data |= (d[1] << 16);
*data |= (d[0] << 24);
Serial.print(*data, HEX); // print the character
Serial.print('\n');
And the output is just the same.
I am wondering why the 2nd MSB always wrong. Looking forward for any help.