Calibrating a magnetometer can improve the accuracy of the magnetometer readings.
All ferromagnetic materials will cause skew in the results of the measurements take by a magnetometer. This distortion falls into two categories, hard or soft iron distortion.
We can also further fine tune our readings by including the magnetic declination of our current location.
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_tutorial03_calibration directory.
Hard Iron Distortion
Hard iron distortions are created by objects that produce a magnetic field. A speaker or piece of magnetized iron for example will cause a hard iron distortion. If the piece of magnetic material is physically attached to the same PCB as the magnetometer, then this type of hard iron distortion will cause a permanent bias in the sensor output.
Soft Iron Distortion
Soft iron distortions are considered alterations in the existing magnetic field, this is usually caused by ferromagnetic materials around the sensor as well as the Earth's magnetic field (it is different in different locations).
Unfortunately, there is no easy way to calibrate for soft iron distortion and every time the sensor is moved to a new location, the calibration has to be done again. Most people only apply hard iron calibration as this calibration usually stays constant.
Plotting Your Readings
An easy way to check to see if your sensor needs calibration is to plot the pairwise data from the raw X and Y readings.
The image below was created using Wolfram Mathematica on a Raspberry Pi. The data used was from an uncalibrated compass as. Take note of the ellipsoid shape and how the center is not centered on the X,Y axis.