Razor-AHRS / razor-9dof-ahrs

AHRS Firmware for the SparkFun 9DOF Razor IMU and SparkFun 9DOF Sensor Stick
Other
450 stars 264 forks source link

32 bit issue #40

Open PaulStoffregen opened 8 years ago

PaulStoffregen commented 8 years ago

This type of code will fail on 32 bit boards, like Teensy3, Arduino Zero, Arduino Due, ESP8266, ChipKit, etc...

    accel[0] = (((int) buff[3]) << 8) | buff[2];  // X axis (internal sensor y axis)
    accel[1] = (((int) buff[1]) << 8) | buff[0];  // Y axis (internal sensor x axis)
    accel[2] = (((int) buff[5]) << 8) | buff[4];  // Z axis (internal sensor z axis)

On 32 bit boards, "int" is a 32 bit number. Because buff[] is unsigned bytes, these will will produce results from 0 to 65535, because you'd shifting numbers from 0 to 255. On AVR where "int" is 16 bits, this code works, but only because the result which should have been 0 to 65535 is stored into a 16 bit signed number which can only represent -32768 to +32767.

The proper way to make this work involves a cast to int16_t, like this:

    accel[0] = (int16_t)((((int) buff[3]) << 8) | buff[2]);  // X axis (internal sensor y axis)
    accel[1] = (int16_t)((((int) buff[1]) << 8) | buff[0]);  // Y axis (internal sensor x axis)
    accel[2] = (int16_t)((((int) buff[5]) << 8) | buff[4]);  // Z axis (internal sensor z axis)

This fix is fully compatible with AVR and all 32 bit platforms. It explicitly instructs the compiler to consider the result a 16 bit signed integer.