i2cdevlib icon indicating copy to clipboard operation
i2cdevlib copied to clipboard

Conflict data type

Open swords001 opened this issue 11 years ago • 5 comments

Hi guys, I'm new in programming so it's really hard for me to understand why the data variable in the below function is uint8_t type :
int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout)

But the raw data read by this function is of int16_t type : void MPU6050::getMotion6(int16_t* ax, int16_t* ay, int16_t* az, int16_t* gx, int16_t* gy, int16_t* gz) { I2Cdev::readBytes(devAddr, MPU6050_RA_ACCEL_XOUT_H, 14, buffer);

Sorry for my bad English .

swords001 avatar Jul 11 '15 03:07 swords001

In the first instance, you are reading a single register. All the registers are 8 bits wide. However, the data is actually 16 bits wide, so each is stored in two different registers (high and low). In the second function, getMotion6 takes care of combining the two registers/bytes for you, which is why its data is 16 bits wide.

Ernest314 avatar Jul 11 '15 05:07 Ernest314

Thank you for help Ernest I know that the data is 16 bit wide but what i mean is the unsigned versus signed. Data from register is unsigned . However, ax ay az ... are signed.

swords001 avatar Jul 11 '15 06:07 swords001

The entire 16-bit value is actually signed, however it is specially encoded and then split into two bytes. The result is left as unsigned because we are storing raw bits, and signed variables use a bit to indicate signage and that makes things gnarly. The decoding is done for you in the second function you mention.

If you want to read up on the subject, the specific representation used is called "two's complement".

Ernest314 avatar Jul 11 '15 06:07 Ernest314

Hi, it's me again . Could you please explain that why in the function I got the wrong temperature: int16_t MPU6050::getTemperature() { I2Cdev::readBytes(devAddr, MPU6050_RA_TEMP_OUT_H, 2, buffer); return (((int16_t)buffer[0]) << 8) | buffer[1];

However when I change to : return (((int16_t)buffer[1]) << 8) | buffer[0]; then I got the exact temperature.

( I'm using the formula provided in register map to calculate the celcius degree then print out to UART Terminal )

swords001 avatar Jul 13 '15 15:07 swords001

I'm not actually using the I2Cdev library... Ran into some issues, decided to roll my own solution, afterwards realized I was just really dumb :P

On topic though, I'm not sure what's going on behind the scenes, but it's possible that the buffers are being read in a reversed order. The MPU-6050 datasheet does indicate that 0x41 is TEMP_OUT_H ([15:8]) and 0x42 is TEMP_OUT_L ([7:0]). Have you tried reading from the registers one at a time?

Ernest314 avatar Jul 13 '15 17:07 Ernest314