Zbotic Logo Zbotic Logo
  • Home
  • Shop
  • Sale
  • 3D Print Service
  • PCB Service
  • B2B
  • Blogs
  • Contact Us
0 0

View Wishlist Add all to cart

0 0
0 Shopping Cart
Shopping cart (0)
Subtotal: ₹0.00

View cartCheckout

  • Shop
  • About Us
  • Contact Us
  • Reseller
  • Blogs
020 69134444
1800 209 0998
[email protected]
Help Desk
Facebook Twitter Instagram Linkedin YouTube
Zbotic Logo Zbotic Logo
0 0

View Wishlist Add all to cart

0 0
0 Shopping Cart
Shopping cart (0)
Subtotal: ₹0.00

View cartCheckout

All departments
  • 3D Print Service
  • 3D Printer
  • Batteries & Chargers
  • Development Boards
  • Drone Parts
  • EBike parts
  • Sensor Modules
  • Electronic Components
  • Electronic Modules
  • IoT and Wireless
  • Mechanical Parts and Workbench Tools
  • Motors & Drivers & Pumps & Actuators
  • DIY and Robot Kits
  • Show more
  • Home
  • Shop
  • Sale
  • 3D Print Service
  • PCB Service
  • B2B
  • Blogs
  • Contact Us
Return to previous page
Home Arduino & Microcontrollers

Arduino Compass Module HMC5883L: Heading and Navigation

Arduino Compass Module HMC5883L: Heading and Navigation

March 11, 2026 /Posted byJayesh Jain / 0

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
Recommended: Arduino Uno R3 Beginners Kit — The perfect starting point for compass and sensor projects, with all essential components included.

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.

Recommended: Arduino Nano Every with Headers — Compact form factor ideal for embedding a magnetometer into small navigation builds where board size matters.

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:

  1. Run a sketch that prints raw X, Y, Z values at ~10 Hz.
  2. Slowly rotate the module through a full horizontal 360° turn.
  3. Record X_min, X_max, Y_min, Y_max.
  4. Compute offsets: X_offset = (X_max + X_min) / 2, same for Y.
  5. 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.

Recommended: Arduino Nano 33 IoT with Header — Has an onboard LSM6DS3 IMU for tilt compensation alongside your external HMC5883L, and Wi-Fi for sending compass data to a dashboard.

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.

Recommended: 2.4″ Touch Screen TFT Display Shield for Arduino UNO MEGA — Plug-and-play display shield that stacks directly on your Uno for a compass rose UI without extra wiring.

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.

Recommended: Arduino Mega 2560 R3 Board — Multiple hardware I2C and UART ports make it easy to run a compass, GPS, LCD, and SD card logger simultaneously.

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.

Tags: Arduino, compass module, HMC5883L, magnetometer, navigation, sensor
Share Post
  • Facebook
  • Linkedin
  • Whatsapp
Arduino Motor Shield R3: Drive...
blog arduino motor shield r3 drive dc and stepper motors easily 594831
blog arduino eeprom tutorial read write wear levelling guide 594835
Arduino EEPROM Tutorial: Read,...

Related posts

Svg%3E
Read more

Arduino Batch Programming: Flash Multiple Boards Quickly

April 1, 2026 0
Table of Contents Introduction Components and Hardware Setup Wiring Diagram and Connections Complete Code with Explanation Customization and Improvements Troubleshooting... Continue reading
Svg%3E
Read more

Arduino Based Radar System with Ultrasonic Sensor

April 1, 2026 0
Table of Contents Introduction Components and Hardware Setup Wiring Diagram and Connections Complete Code with Explanation Customization and Improvements Troubleshooting... Continue reading
Svg%3E
Read more

Arduino Automatic Plant Monitor: Sunlight, Moisture, Temperature

April 1, 2026 0
Table of Contents Introduction Components and Hardware Setup Wiring Diagram and Connections Complete Code with Explanation Customization and Improvements Troubleshooting... Continue reading
Svg%3E
Read more

Arduino Lie Detector: GSR Sensor Polygraph Project

April 1, 2026 0
Table of Contents Introduction Components and Hardware Setup Wiring Diagram and Connections Complete Code with Explanation Customization and Improvements Troubleshooting... Continue reading
Svg%3E
Read more

Arduino Metal Detector: Build a Treasure Finder

April 1, 2026 0
Table of Contents Introduction Components and Hardware Setup Wiring Diagram and Connections Complete Code with Explanation Customization and Improvements Troubleshooting... Continue reading

Add comment Cancel reply

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

Facebook Twitter Instagram Pinterest Linkedin Youtube

Get the latest deals and more.

Download on Google Play Download on the App Store

Call us: 020 69134444 / 1800 209 0998

Monday - Saturday 09:30 AM - 06:00 PM
For Technical Supports Email: [email protected]
For Sales / Enquiries Email: [email protected]

  • My Account

    • Cart

    • Wishlist

    • Checkout

    • My Orders

    • Track Order

    • My Account

  • Information

    • FAQs

    • Blogs

    • Career

    • About Us

    • Contact Us

    • Payment Options

  • Policies

    • Privacy Policy

    • Terms & Conditions

    • GST Input Tax Credit

    • Shipping Return Policy

    • E-Waste Collection Points

    • Our Sitemap

© Zbotic.in is registered trademark of Moxie Supply Pvt Ltd – All Rights Reserved
Login
Use Phone Number
Use Email Address
Not a member yet? Register Now
Reset Password
Use Phone Number
Use Email Address
Register
Already a member? Login Now