• Using a 3-Axis Magnetometer as a compass.

    An example:

    First Zero the magnetometer

    For each axis X, Y and Z point the axis North and take a reading R1, then turn the magnetometer 180 degrees and take reading R2. Take the average of the two readings as the offset for that axis.
    Your code will then take a reading and subtract the offset for each axis. X= Xraw- Xoffset, Y= Yraw- Yoffset, Z= Zraw- Zoffset.
    Use the resulting Z, Y and Z values in all calculations that follow. If you repeat the North and then rotate proceedure then
    Xn =-Xs, Yn=-Yz, and Zn=-Zs, where the subscripts s and n stanf for North and South.

    Example

    • Assign the Z axis to the Yaw axis.
    • Assign the X axis to the roll (heading) axis.
    • Assign the Y axis to the pitch axis.
    • With the X and Y axis level and the Z axis pointing in the position for use ( Think the model airplane is not inverted):
    • Point the roll (X) axis North and note the sign of the X axis reading. If it is negative, you need to multiply X by -1 in the assignment statement of the code
    • Point the roll (X) axis East and note the sign of the Y axis. The reading should be negative, if not you need to multiply Y by -1 in the assignment statement of the code
    • The yaw axis should be positive in the Northern hemisphere and negative in the Southern menisphere. If not negate it.

      var X=1,Y=-1,Z=1;
      var X1,Y1,Z1;
      var Xoffset=0,Yoffset=0,Zoffset=0;
      //Read the magnetometer X,Y, and Z
      
      //Subtract the offsets
      X1=X-Xoffset; Y1=Y-Yoffset; Z1=Z-Zoffset;
      //Assign the XYZ to roll pitch and yaw axis
      var Sroll=1; var Spitch=-1; var Syaw=1; 
      roll=Sroll*X1; pitch=Spitch*Y1; yaw=Syaw*Z1;
      heading=180/Math.PI * Math.atan2(pitch,roll);
      if(heading <0) heading+=360;
      console.log("Heading= ",heading);
      dip=180/Math.PI*Math.atan(Math.sqrt(roll­*roll+pitch*pitch),yaw);
      console.log("Dip= ",dip);
      //add the declination to get true heading
      

    Note the change in the argument order of the atan2 function from the orignal post.

    • Try it out to see that 90 degree heading is East, 180 is South, 270 is West and 0 is North.
    • Repeat using the Y axis as the roll axis and the X axis as pitch.

    https://en.wikipedia.org/wiki/Magnetic_d­ip

    https://www.ngdc.noaa.gov/geomag-web/#ig­rfwmm

    https://en.wikipedia.org/wiki/Magnetic_d­eclination

About