This part 2 of a multi part series on how to use a digital compass(magnetometer) with your Raspberry Pi.
Part 1 can be found here and is a prerequisite to part 2.
Code for this guide
Git repository here
The code can be pulled down to your Raspberry Pi with;
The code for this guide can be found under the compass_tutorial02_tilt_compensation directory.
Calculating Compass Heading
Part 1 covered how to get the heading from the magnetometer, however this is only reliable when the magnetometer is on a flat surface. If the magnetometer is tilted, the heading will skew and not be correct.
The chart below shows a compass being held at 200 degrees and being tilted in various directions. The blue line is the raw heading, the orange line is the heading after applying tilt compensation. As you can see, without tilt compensation the heading will change if the compass is tilted.