Unable to tilt compensate Pololu AltIMU-10 v4 heading

Hi all,

I am currently trying on tilt compensate Pololu AltIMU-10 v4 to give me the heading with respect to magnetic north. However, the compensated value is far more unstable compared to the original value.

I have been following this application note: https://www.pololu.com/file/download/LSM303DLH-compass-app-note.pdf?file_id=0J434

My code for tilt compensation is:

// Resultant acceleration
float reAcc = sqrt(ax * ax + ay * ay + az * az);

// Normalize acceleration components
float accXnorm = ax / reAcc;
float accYnorm = ay / reAcc;
float accZnorm = az / reAcc;

// Pitch and roll
float pitch = asin(-accXnorm);
float roll = asin(accYnorm / cos(pitch));

// Magnetic Resultant
float reMag = sqrt(mx * mx + my * my + mz * mz);

// Normalize magnetic components
float magXnorm = mx / reMag;
float magYnorm = my / reMag;
float magZnorm = mz / reMag;

// Get x and y component in earth horizontal plane
float magXcomp = magXnorm * cos(pitch) + magZnorm * sin(pitch);
float magYcomp = magXnorm * sin(roll) * sin(pitch) + magYnorm * cos(roll) - magZnorm * sin(roll) * cos(pitch);

// Get the heading
float heading = 180 * atan2(magYcomp,magXcomp) / PI;

if(heading < 0)
heading += 360;

I think it is almost the same as the datasheet above. Can anyone points out if there is any mistake in the code?

I apologize if I make any silly mistake.

How did you calibrate the accelerometer and magnetometer, and where do you apply the corrections?

Hi, qzai09.

I didn’t see any issues with your code at a quick glance. One debugging strategy might be to print out intermediate values within the calculation to see if they make sense. What is the type of the variables ax, mx, etc? If they are integers, you might need to cast them to wider integer types or floats to avoid overflows when you multiply them or losing precision when you divide them.

You might also want to take a look at the way we compute a tilt-compensated heading in our LSM303 Arduino library and its Heading example. It uses a different approach than the ST app note, though.


Hi @Jim_Remington and @kevin,

Sorry for the late reply. I just solved the issue today. The problem is I did get the offset of the magnetometer at my home last time. However, I did not do so for my workplace. Therefore, when I work at my workplace, it is inaccurate.

The unstable readings might be due to I actually placed the IMU on my phone to check the readings. It might be the magnetic field inside the phone interfering with the IMU, causing the reading to be very incorrect.

By the way, do we need to calibrate every time we switched places using this magnetometer?

Thank you for your replies.

Best Regards,
Quek Wei Hao

For best performance, magnetometers should be recalibrated frequently, especially if the surroundings have changed.