Paul Stoffregen of PJRC wrote a really awesome cross-platform calibration helper that is great for doing both soft and hard iron magnetometer calibration. What's nice about it is you get a 3D visualization of the magnetometer output and it also tosses outliers and tells you how much spherical coverage you got!

This example runs on chips with at least 64 KB of flash, and will not fit on an UNO (Atmega328) or Leonardo (Atmega32u4) - try the simple calibration instead!

Step 1 - Download MotionCal Software

MotionCal is available for Mac, Windows and Linux, you can download it from clicking here.

Look for this section in the website:

And click the one that matches your computer the best.

Step 2 - Upload the SensorLab imucal Example

Next we have to tell the microcontroller board to send the magnetometer (and, if there is one, accelerometer and gyroscope) data out over serial in the right format.

Open up the Adafruit_SensorLab->calibration->imucal

Select your desired board & port from the Tools menu then click Upload

Open up the serial console, you'll see SensorLab initialization and detection of whatever magnetometer is available. In this case is a LIS3MDL, but any magnetometer can be calibrated!

You'll then see a stream of data that looks like:
Raw:-58,-815,8362,76,-121,-95,-375,-159,-24
Uni:-0.07,-0.98,10.00,0.0832,-0.1327,-0.1046,-37.50,-15.93,-2.50

The first three numbers are accelerometer data - if you don't have an accelerometer, they will be 0

The middle three numbers are gyroscope data - if you don't have an gyroscope, they will be 0

The last three numbers are magnetometer, they should definitely not be zeros!

Close the serial port, and launch MotionCal

Select the same COM / Serial port you used in Arduino

Twist the board/sensor around. Make sure its not near any strong magnets (unless that's part of the installation)

Keep twisting until you get a complete 'sphere' of red dots. At this point you are calibrated!

In the top right you'll see the hard magnetic offsets at the top, the soft offsets in the middle and the field strength at the bottom.

In this case, the hard iron offsets are [-6.16, -7.95, 20.77]

Take a screenshot of this display, so you can refer to these numbers later!

This guide was first published on Jan 26, 2020. It was last updated on Jan 26, 2020.
This page (Magnetic Calibration with MotionCal) was last updated on Oct 25, 2020.