How to recalibrate/reset Magnetometer?

Posted on
  • I noticed that if the Puck is started next to a magnet, the magnetometer values are "off". If I push my program back down to the Puck (after moving it away from the magnetic source, the magnetometer goes back to "normal". How, in code, do I force a reset/recalibration of the magnetometer - basically simulated the restarting of the unit?


  • Hi - it depends on the code you're using. For example in­ht we have:

    var zero = Puck.mag();
    var doorOpen = false;
    function onMag(p) {
      p.x -= zero.x;
      p.y -= zero.y;
      p.z -= zero.z;
      var s = Math.sqrt(p.x*p.x + p.y*p.y + p.z*p.z);
      var open = s<1000;
      if (open!=doorOpen) {
        doorOpen = open;
        digitalPulse(open ? LED1 : LED2, 1,1000);
    Puck.on('mag', onMag);

    The magic bit there is zero = Puck.mag();. Just call var zero = Puck.mag(); again and it'll reset the zero value to the current magnetometer reading.

  • I noticed when testing similar code that the first reading after offsetting with zero = Puck.mag(); gives x, y and z values close to zero, as you'd expect, but second and subsequent jump to values that vary (+/-) quite a bit from zero, and actually found it better to do use a later reading as a zero/offset, making a couple of calibration passes as below

    var offset = {x:0, y:0, z:0};
    var calPass = 2;
    function readMag(mag){
      if (calPass > 0) {
        // calibration pass
        offset.x = mag.x;
        offset.y = mag.y;
        offset.z = mag.z;
      } else { 
        // provide reading
        mag.x -= offset.x;
        mag.y -= offset.y;
        mag.z -= offset.z;
    Puck.on('mag', readMag);

    I doubt it matters much, as slight changes in orientation of Puck still move values considerably, regardless, but it seems the Puck.mag() reading doesn't quite do the zeroing/reset I expected.

  • Odd - thanks for letting me know. I guess this is potentially something that might make sense to add to the firmware, where it could take multiple readings.

    Just FYI there's a vector maths class that can make these calculations a bit tidier - especially if you maybe wanted to average a few readings :

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

How to recalibrate/reset Magnetometer?

Posted by Avatar for user87600 @user87600