Arduino HMC5883L Compass: Wiring, Code and Simulator

To build this Arduino HMC5883L Compass project you need an Arduino Uno and a compass HMC5883L. The Adafruit HMC5883 Unified library turns the magnetometer into a heading. Make the 4 connections in the wiring table, upload the Arduino C++ code, and move the Heading slider and check the printed angle follows it.

Open this circuit in the free Arduino Uno simulator

Parts list

QtyPartWhat it does
1Arduino Unothe microcontroller board
1Compass HMC5883LA 3-axis magnetometer on I²C (0x1E): heading = atan2(Y, X). Turn the heading slider and watch the angle follow.

Wiring

#FromTo
1Arduino Uno 5VCompass HMC5883L VCC
2Arduino Uno GNDCompass HMC5883L GND
3Arduino Uno A4Compass HMC5883L SDA
4Arduino Uno A5Compass HMC5883L SCL

Step by step

  1. Open the simulator. Open the BitForBytes Embedded Lab in your browser and start from the Arduino Uno. No install or account is needed.
  2. Add the parts. Add a compass HMC5883L from the parts palette.
  3. Wire 1. Connect Arduino Uno 5V to Compass HMC5883L VCC.
  4. Wire 2. Connect Arduino Uno GND to Compass HMC5883L GND.
  5. Wire 3. Connect Arduino Uno A4 to Compass HMC5883L SDA.
  6. Wire 4. Connect Arduino Uno A5 to Compass HMC5883L SCL.
  7. Paste the Arduino C++ code. Paste the Arduino C++ code below into the code editor.
  8. Run it. Press Run. Move the Heading slider and check the printed angle follows it.

Arduino C++ code

// Adafruit HMC5883 Unified: a compass heading from the magnetometer.
#include <Adafruit_Sensor.h>
#include <Adafruit_HMC5883_U.h>

Adafruit_HMC5883_Unified mag(12345);

void setup() {
  Serial.begin(9600);
  if (!mag.begin()) {
    Serial.println("HMC5883L not found.");
    while (true) {}
  }
}

void loop() {
  sensors_event_t e;
  mag.getEvent(&e);
  float heading = atan2(e.magnetic.y, e.magnetic.x) * 180.0 / PI;
  if (heading < 0) heading += 360;
  Serial.print("Heading: ");
  Serial.print(heading, 0);
  Serial.println(" deg");
  delay(500);
}

What to try

Move the Heading slider and check the printed angle follows it.

Frequently asked questions

How do I wire the HMC5883L Compass project on an Arduino Uno?

Make 4 connections: Arduino Uno 5V to Compass HMC5883L VCC; Arduino Uno GND to Compass HMC5883L GND; Arduino Uno A4 to Compass HMC5883L SDA; Arduino Uno A5 to Compass HMC5883L SCL.

What parts do I need for this Arduino project?

An Arduino Uno and a compass HMC5883L.

Can I simulate this Arduino project online for free?

Yes. The BitForBytes Embedded Lab runs this exact circuit and Arduino C++ code in your browser for free, with no install and no hardware. The sketch is compiled with the real Arduino toolchain and runs on an emulated ATmega328P.

What does the code do?

The Adafruit HMC5883 Unified library turns the magnetometer into a heading.

More Arduino Uno projects