[Compass] Easy Magnetometer Calibration

This code is a short example on how to calibrate your cheap magnetic compass. I used a three axis HCM5883 magnetometer from Honeywell. It’s very cheap, but mine was pretty bad. It turned out its measurements were pretty wrong, but somewhat good. It turned out i just had to calibrate a little.

What you just do is you just get the values plotted from your little processor in a CSV format (comma seperated, like, X,Y on every line. e.g. “52,-123”. Then you just use the Matlab import wizard to easily import it. The entire process takes around one minute per calibration.

Initial test. See how the center of the circle does -not- lie on 0,0 as it should

Result after applying a X-20 and Y-80 in the code.

So, just check where the center of the circle is, and then check where it should be: then apply a little + or – here and there by eye; and you’re good to go. If it looks like an egg then you should apply some division or multiplication, but that’s even obvious to a 4-year old.

Code for 2 Axis

Simple Matlab code:

  1. plot(data(:,1),data(:,2),'r.')
  2. axis equal
  3. ylabel('Magnetic signal Y [8-bit gauss]');
  4. xlabel('Magnetic signal X [8-bit gauss]');
  5. grid on

Code for 3 Axis

Simple Matlab code:

  1. plot3(data(:,1),data(:,2),data(:,3),'r.')
  2. axis equal
  3. ylabel('Magnetic signal Y [8-bit gauss]');
  4. xlabel('Magnetic signal X [8-bit gauss]');
  5. grid on

Tim Zaman

MSc Biorobotics. Specialization in computer vision and deep learning. Works at NVIDIA.

You may also like...

2 Responses

  1. Kurt says:

    Hi there, sorry but i’m kind of new with matlab, so i’ve made an “m” file with you code, but when i’ve tried to run it, it says that there is no data.

    So what should i do?, i mean, i have a hmc5883L magnetometre, i’ve made the code for the self test of the sensor and i’ve got the x, y and z values, then in a text file i’ve written with comma as you said, then exported those data, and last tried to run you code but it doesn’t work.

    So please can you explain it more clearly all the steps?

    Thank you.

  2. psychoul says:

    Thanks!!! It really helped a lot! I am getting much better results even from the IMU embedded filter.