Back to Explorer

esp32-qmc5883p-compass-heading

Project Information

Author

Mikrobot.pl

Board

ESP32 Dev Module

SDK Version

3.3.6

Platform

ESP32

Created

Updated

Description

Read magnetometer data from a QMC5883P over I2C on an ESP32, convert raw readings to µT, and print a tilt-uncompensated heading (0–360°) to the Serial Monitor. Includes optional magnetic declination correction.

Flash to Device

Login required: You need to login or create an account to flash this project.

Sorry, your browser doesn't support Web Serial.Web Serial requires HTTPS.

README

ESP32 + QMC5883P Compass (I2C)

Project photo

This project reads a QMC5883P magnetometer via I2C on an ESP32, converts the raw sensor values into microtesla (µT), calculates a compass heading (0–360°), and prints everything to the Serial Monitor.

Hardware

  • ESP32 development board
  • QMC5883P magnetometer module (I2C)

Wiring (ESP32 ↔ QMC5883P)

Use the I2C pins defined in the sketch:

  • SDA → GPIO21
  • SCL → GPIO22
  • VCC → 3V3
  • GND → GND

If your module supports both 3.3V and 5V, 3.3V is recommended for ESP32 logic.

Software

Arduino IDE setup

  • Board: select your ESP32 board (e.g., “ESP32 Dev Module”)
  • Serial speed: 115200
  • Libraries: uses built-in Wire.h only (no extra library required)

Configuration

I2C address

The sketch uses the QMC5883P default address:

  • 0x2C

Magnetic declination

Set DECLINATION_DEG to your local magnetic declination (in degrees) to correct the heading:

  • Example: constexpr float DECLINATION_DEG = 4.2f;

Output

The Serial Monitor prints:

  • X/Y/Z magnetic field in µT
  • Heading in degrees

Example: X:12.34 Y:-5.67 Z:44.12 µT | Heading: 123°

Notes / Limitations

  • Heading is calculated from X/Y only (no tilt compensation).
    If the sensor is not kept level, heading will be inaccurate.
  • For best results, perform calibration and keep the module away from magnets/steel.