The Arduino HMC5883L compass module is one of the most popular magnetometer ICs for hobbyist navigation projects. Whether you are building a robot that needs to track its heading, a drone that must hold a course, or a handheld GPS logger, the HMC5883L gives you three-axis magnetic field data that you can convert into a reliable compass bearing. In this guide, you will learn everything from hardware wiring and library setup to hard-iron calibration, tilt compensation, and practical project ideas — all using Arduino.
Table of Contents
- What Is the HMC5883L?
- Hardware Wiring
- Library Setup and First Sketch
- Hard-Iron and Soft-Iron Calibration
- Tilt Compensation with an Accelerometer
- Navigation Project Ideas
- Troubleshooting Tips
- Frequently Asked Questions
What Is the HMC5883L?
The HMC5883L is a three-axis magnetometer manufactured by Honeywell (now part of the QST family with the QMC5883L clone). It measures magnetic field strength along X, Y, and Z axes with a resolution down to 2 milligauss and communicates over the I2C bus at a fixed address of 0x1E. The GY-273 breakout board, which is the most common module form, operates at 3.3 V logic but includes an onboard regulator accepting 3.3 V to 5 V supply, making it directly compatible with Arduino Uno, Nano, and Mega boards.
Key specifications:
- Supply voltage: 3.3 V (GY-273 module: 3.3–5 V via onboard LDO)
- I2C address: 0x1E (HMC5883L) / 0x0D (QMC5883L clone)
- Measurement range: ±0.88 to ±8.1 Gauss (configurable)
- Output data rate: 0.75–75 Hz
- Heading accuracy: ±1–2° after calibration
Hardware Wiring
The HMC5883L GY-273 module exposes five pins: VCC, GND, SCL, SDA, and DRDY (data-ready interrupt, optional). Connect it to an Arduino Uno as follows:
| GY-273 Pin | Arduino Uno Pin |
|---|---|
| VCC | 5 V |
| GND | GND |
| SCL | A5 |
| SDA | A4 |
| DRDY | Optional – D2 |
Keep I2C wires short (under 30 cm) and avoid routing them near motor drivers or high-current traces, as magnetic interference will corrupt readings. If your module lacks onboard pull-up resistors, add 4.7 kΩ resistors from SDA and SCL to 3.3 V.
Library Setup and First Sketch
Open the Arduino IDE Library Manager and install the Adafruit HMC5883 Unified library (also requires Adafruit Unified Sensor). For the popular QMC5883L clone, install DFRobot QMC5883 instead — the register maps differ and mixing them will produce zeroes.
Here is a minimal sketch to read heading:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_HMC5883_U.h>
Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345);
void setup() {
Serial.begin(115200);
if (!mag.begin()) {
Serial.println("HMC5883L not found. Check wiring!");
while (1);
}
}
void loop() {
sensors_event_t event;
mag.getEvent(&event);
float heading = atan2(event.magnetic.y, event.magnetic.x);
// Declination for Mumbai: +0.93° (0.0162 radians)
heading += 0.0162;
if (heading < 0) heading += 2 * PI;
if (heading > 2 * PI) heading -= 2 * PI;
float headingDegrees = heading * 180 / M_PI;
Serial.print("Heading: ");
Serial.print(headingDegrees);
Serial.println("°");
delay(500);
}
The magnetic declination correction is location-specific. Visit magnetic-declination.com and enter your city to find the exact value. For most Indian cities the declination is between +0.5° and +1.5° East.
Hard-Iron and Soft-Iron Calibration
An uncalibrated compass can show errors of 20–40°, making it useless for navigation. Calibration corrects two error classes:
- Hard-iron distortion: Caused by permanent magnets near the sensor (e.g., motor magnets, speaker coils). Shows up as a constant offset in raw X/Y readings. Corrected by subtracting the midpoint of the min/max values collected during a full 360° rotation.
- Soft-iron distortion: Caused by ferromagnetic materials that warp the Earth’s field. Converts the circular locus into an ellipse. Corrected by scaling axes so the ellipse becomes a circle.
Step-by-step hard-iron calibration:
- Run a sketch that prints raw X, Y, Z values at ~10 Hz.
- Slowly rotate the module through a full horizontal 360° turn.
- Record X_min, X_max, Y_min, Y_max.
- Compute offsets:
X_offset = (X_max + X_min) / 2, same for Y. - Subtract these offsets from every reading before computing
atan2.
After hard-iron calibration, heading errors typically drop to ±3–5°. For the remaining soft-iron error, collect the ellipse data and compute scale factors using the ratio of axis ranges: X_scale = avg_range / X_range and Y_scale = avg_range / Y_range.
Tilt Compensation with an Accelerometer
The 2D atan2(Y, X) formula only works when the sensor is held perfectly flat. Any tilt of more than ±5° introduces significant heading error. Tilt compensation requires a 3-axis accelerometer (e.g., MPU-6050, ADXL345) mounted rigidly on the same plane as the magnetometer.
The compensated heading formula:
// Normalize accelerometer
float roll = atan2(ay, az);
float pitch = atan2(-ax, sqrt(ay*ay + az*az));
// Tilt-compensated magnetic readings
float Xh = mx * cos(pitch) + mz * sin(pitch);
float Yh = mx * sin(roll) * sin(pitch)
+ my * cos(roll)
- mz * sin(roll) * cos(pitch);
float heading = atan2(Yh, Xh) * 180.0 / PI;
if (heading < 0) heading += 360.0;
With tilt compensation, heading accuracy remains within ±5° even at roll/pitch angles of ±30°, which is acceptable for most mobile robot and drone applications.
Navigation Project Ideas
Once your compass is calibrated and tilt-compensated, here are practical projects you can build:
1. Digital Compass with TFT Display
Display a graphical compass rose on a TFT screen. Draw a rotating needle that always points North. Refresh at 5 Hz for smooth animation.
2. GPS Waypoint Navigator
Combine the HMC5883L with a GPS module (Neo-6M). Calculate the bearing to a target waypoint from current GPS coordinates, then compare with compass heading to produce a turn direction command for a robot or drone autopilot.
3. Heading-Hold Gimbal Controller
Use the compass heading as the process variable in a PID loop. Drive a servo to rotate a platform and maintain it at a user-defined bearing regardless of the carrier vehicle’s rotation.
4. Buried Pipe / Cable Detector
Underground cables carrying AC current generate detectable magnetic fields. Slowly sweep the sensor over the ground and plot field magnitude vs position to locate the cable path.
Troubleshooting Tips
- All readings return zero or NaN: Wrong IC variant. Check if your module has QMC5883L (address 0x0D) instead of HMC5883L (0x1E). Use an I2C scanner sketch to confirm.
- Heading jumps wildly: Interference from nearby motors or power supply wires. Move the sensor at least 10 cm away from any motor driver. Use a shielded I2C cable.
- Consistent offset in heading: Not calibrated. Perform hard-iron calibration as described above.
- Reading always same value: Sensor is in self-test mode or gain is overranged. Set field range to ±1.3 Gauss (default) and reset the chip via its single-measurement command.
- Drift over time: Temperature changes affect hard-iron offsets. Run a quick calibration at the start of each session if temperature swings more than 15°C.
Frequently Asked Questions
Is the HMC5883L and QMC5883L the same?
No. The QMC5883L is a Chinese clone with different I2C address (0x0D vs 0x1E) and slightly different register layout. They look physically identical on GY-273 modules, so check the IC marking. Use the DFRobot QMC5883 library for the clone and Adafruit HMC5883 for the genuine Honeywell part.
How accurate is the HMC5883L after calibration?
After proper hard-iron and soft-iron calibration, expect ±1–3° heading accuracy in a low-interference environment. In practice, most maker projects achieve ±5° which is sufficient for robot navigation and drone heading hold.
Can I use the HMC5883L outdoors in sunlight?
Yes. The IC is not light-sensitive. However, keep the module away from steel structures, reinforced concrete, and high-tension power lines, all of which distort the local magnetic field and require fresh calibration in each new location.
Does the HMC5883L work with 5 V Arduino?
The GY-273 module has an onboard voltage regulator and level shifter, so yes, you can power it from 5 V. Do not connect a bare HMC5883L IC directly to 5 V GPIO lines — the IC is 3.3 V only and will be damaged.
What is the difference between heading and bearing?
Heading is the direction the sensor (or vehicle) is currently pointing relative to North. Bearing is the direction from your current position to a target point. Navigation software computes the bearing to the target, then steers the vehicle until its heading matches that bearing.
The Arduino HMC5883L compass module is a powerful and affordable sensor that opens up a wide range of navigation and orientation projects. With proper calibration and tilt compensation it delivers accuracy that rivals dedicated GPS compass modules at a fraction of the cost. Explore our full range of Arduino modules and sensors at Zbotic to build your next navigation project.
Add comment