Try Embedded

Digital compass (QMC5883L)

Read the Earth's magnetic field on three axes, turn it into a heading and a compass point, and point a servo needle north.

Sensors · Intermediate

In a real product: Hiking GPS watch (Wearables): A magnetometer gives the heading.

A magnetometer measures the magnetic field along its X, Y and Z axes. Held flat, the horizontal part of the Earth's field points to magnetic north, so the angle of (X, Y) is your heading. A servo turns a needle to keep pointing north.

What you'll learn

  • What a magnetometer measures, and how atan2 turns two axes into an angle
  • Naming a heading: dividing the circle into eight 45° sectors
  • Why a compass needs calibrating and keeping away from steel and motors

How it works

compass.init() starts the QMC5883L measuring continuously at 200 Hz, ±8 gauss. compass.read() fetches X, Y and Z, and getAzimuth() is atan2(Y, X) in degrees, from −180 to 180. The sketch makes it 0–359, names the nearest of eight compass points, and turns the servo so the needle points north whichever way the board faces.

The Earth's field is about 0.5 gauss (50 µT), and most of it points down into the ground (60° at mid latitudes): that is the large Z reading.

Try this

  • Click the compass and drag its heading: the direction and the needle follow.
  • Put the servo next to a motor in your head: a real motor's magnets would pull the reading. compass.calibrate() and setCalibration() correct for fixed nearby iron.
  • Add your location's magnetic declination with compass.setMagneticDeclination() to point to true north.

sketch.ino

// A compass: a QMC5883L gives the heading, printed with the nearest of eight compass points, and a servo on pin 9
// turns its needle so it keeps pointing north.
#include <QMC5883LCompass.h>
#include <Servo.h>

QMC5883LCompass compass;
Servo needle;
const char *POINTS[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"};

void setup() {
  Serial.begin(9600);
  compass.init();
  needle.attach(9);
}

void loop() {
  compass.read();
  int heading = (compass.getAzimuth() + 360) % 360;
  const char *point = POINTS[((heading + 22) / 45) % 8];
  // The needle sits at 90 facing north and turns against the heading. The servo turns only half a circle, so with
  // north more than 90 degrees to either side the needle stops at its end.
  int angle = 90 + (heading <= 180 ? -heading : 360 - heading);
  needle.write(constrain(angle, 0, 180));
  Serial.print("Heading ");
  Serial.print(heading);
  Serial.print(" (");
  Serial.print(point);
  Serial.print("), field X ");
  Serial.print(compass.getX());
  Serial.print(" Y ");
  Serial.print(compass.getY());
  Serial.print(" Z ");
  Serial.println(compass.getZ());
  delay(500);
}

Lessons behind it