How to Convert Magnetometer Data into Compass Heading

Pmod CMPS2, oblique view.
Pmod CMPS2 3-axis digital magnetometer/compass.

In two previous  posts we discussed how to calibrate magnetometer data in order to get accurate measurements, as well as how to acquire data in the first place. In this post we will go through the last major step, how to convert the data from units of Gauss into a true compass heading using the Pmod CMPS2 as an example.

Data Conversion

The Memsic MMC34160PJ magnetometer on the Pmod CMPS2 provides data for each axis in units of Gauss, but the information is generally more legible when presented as a compass heading. The method for converting Gauss units to a compass heading is provided below.

  1. Calculate the real Gauss value for the X and Y axes from the amount of LSBs returned where the LSB value by default is 0.48828125 mG, resulting in 2048 LSBs per Gauss.
    xGaussDatxDataLSB0.48828125 mG

    yGaussDatyDataLSB0.48828125 mG
  2. Calculate the direction D by first checking to see if the X Gauss data is equal to 0 to prevent divide by 0 zero errors in the future calculations. If the X Gauss data is 0, check to see if the Y Gauss data is less than 0. If Y is less than 0 Gauss, the direction D is 90 degrees; if Y is greater than or equal to 0 Gauss, the direction D is 0 degrees.
  3. If the X Gauss data is not zero, calculate the arctangent of the Y Gauss and X Gauss data and convert from polar coordinates to degrees.
  4. If the direction D is greater than 360 degrees, subtract 360 degrees from that value.
  5. If the direction D is less than 0 degrees, add 360 degrees to that value.
  6. The compass heading can then be determined by the direction value D:
    • If D is greater than 337.25 degrees or less than 22.5 degrees – North
    • If D is between 292.5 degrees and 337.25 degrees – North-West
    • If D is between 247.5 degrees and 292.5 degrees – West
    • If D is between 202.5 degrees and 247.5 degrees – South-West
    • If D is between 157.5 degrees and 202.5 degrees – South
    • If D is between 112.5 degrees and 157.5 degrees – South-East
    • If D is between 67.5 degrees and 112.5 degrees – East
    • If D is between 0 degrees and 67.5 degrees – North-East

If you’d like to see how to acquire date initially or how to calibrate your magnetometer, you can visit the previous posts on theses topics, or go to the Pmod CMPS2 reference manual.

If you’d like to see some example code written in the Arduino IDE for how we acquire, calibrate and convert data from the Pmod CMPS2, see the Pmod CMPS2 Resource Center.

For questions or comments, please post in the comment section below or visit the Digilent Forum!

Be the 1st to vote.

Leave a Reply

Your email address will not be published. Required fields are marked *