I am using a MMA8452 accelerometer. I did not quite understand the following piece of code

data->x = ((tmp_data[0] << 8) & 0xff00) | tmp_data[1];

data->y = ((tmp_data[2] << 8) & 0xff00) | tmp_data[3];

data->z = ((tmp_data[4] << 8) & 0xff00) | tmp_data[5];

But, MMA8452 has 12 bit samples. Should these again be shifted by 4 bits to the right as tmp_data[1], tmp_data[3], tmp_data[4] have only 4 bits of data?

When the Device is Flat. What should be the values of x, y, z.

Hi Sriram,

I am not sure where you found this piece of code, but you are right that these are 16-bit values which need to be shifted by 4 bits to the right to get 12-bit acceleration data.

Have a look at my example code where I use:

I2C_ReadMultiRegisters(MMA8652FC_I2C_ADDRESS, OUT_X_MSB_REG, 6, AccelData); // Read data output registers 0x01-0x06

// 12-bit accelerometer data

Xout_12_bit = ((

short) (AccelData[0]<<8 | AccelData[1])) >> 4; // Compute 12-bit X-axis acceleration output valueYout_12_bit = ((

short) (AccelData[2]<<8 | AccelData[3])) >> 4; // Compute 12-bit Y-axis acceleration output valueZout_12_bit = ((

short) (AccelData[4]<<8 | AccelData[5])) >> 4; // Compute 12-bit Z-axis acceleration output value// Accelerometer data converted to g's

Xout_g = ((

float) Xout_12_bit) / SENSITIVITY_2G; // Compute X-axis output value in g'sYout_g = ((

float) Yout_12_bit) / SENSITIVITY_2G; // Compute Y-axis output value in g'sZout_g = ((

float) Zout_12_bit) / SENSITIVITY_2G; // Compute Z-axis output value in g'sWith the device placed horizontally on a flat surface (X-axis = 0g, Y-axis = 0g and Z-axis = 1g), the output data for both X and Y axes should vary between 0x0001, 0x0000, 0x0FFF, 0x0FFE etc. as they are expressed as 2’s complement number (see the attached file for more information). There may be some offset so the output values can be a bit different, but still close to 0g.

I hope it helps.

Best regards,

Tomas

PS: If my answer helps to solve your question, please mark it as "Correct". Thank you.