Combining 3 bytes of data

Hello
I'm using an I2C ADC for one of my projects and it returns the output in 3 bytes as you can see:

I use this code to retrieve the output from the ADC:

Wire.beginTransmission(i2cAddress);
i2cwrite(0x10);
Wire.endTransmission();
Wire.requestFrom(i2cAddress, 3);
byte dataMSB = i2cread();
byte data = i2cread();
byte dataLSB = i2cread();

I'm making a library and I wanted it to be compatible with all of the arduino boards, so created custom functions i2cwrite and i2cread which are basically replaced by correct code for each arduino board, so don't worry about them.

Now I want to return the result as either the binary value of 3 bytes added together (I'm guessing I should do bit shifting?), or a "long" which is again, 3 bytes added together and one empty byte. I'm not sure how I can concatenate the 3 bytes together. Thanks for the help!

There is no need to store each byte in a separate varaible:

  Wire.requestFrom(i2cAddress, 3);
  uint32_t data32 =  i2cread();
  data32 <<= 8;
  data32 |=  i2cread();
  data32 <<= 8;
  data32 |=  i2cread();

Be warned: If you shift a byte more than 7 bits, all of the data will be thrown away. That is why we shift the uint32_t.

johnwasser:

uint32_t data32 = dataMSB;

data32 <<= 8;
data32 |= data;
data32 <<= 8;

data32 |= dataLSB;






Be warned: If you shift a byte more than 7 bits, all of the data will be thrown away. That is why we shift the uint32_t.

how quick is this operation?

I was wondering if I could do something like the code below, without messing up the I2C timing?

uint32_t data32 = i2cread();
data32 <<= 8;
data32 |= i2cread();
data32 <<= 8;
data32 |= i2cread();

It should work fine with the Wire library. The .requestFrom() doesn't return until the messages is received and buffered.

You could also just access the bytes in the long directly with a union and thereby avoid shifting:

union DATA_UNIT {
  uint32_t data_32;
  uint8_t data_8[4];
} data_unit;

data_unit.data_8[2] = i2cread();
data_unit.data_8[1] = i2cread();
data_unit.data_8[0] = i2cread();

Serial.print("Received = ");
Serial.println(data_unit.data_32);

A union allows you to access the same memory in different ways so it's pretty much ideal for the purpose.