# esp32-qmc5883p-compass-heading

> 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.

- Author: Mikrobot.pl
- Platform: ESP32
- Board: ESP32 Dev Module (`esp32:esp32:esp32`)
- SDK version: 3.3.6
- Tags: #imu, #esp32, #i2c, #compass, #magnetometer, #qmc5883p
- Created: 2026-02-11
- Updated: 2026-02-11
- Favorites: 1, forks: 0
- Project page (view, flash from the browser, fork): https://flashesp.com/explore/UYUmF7ygOj8LwH4BxZO1N
- Download all sources (zip): https://flashesp.com/api/public-projects/UYUmF7ygOj8LwH4BxZO1N/download-sources/

## Source files

- [main.ino (3.0 KB)](https://flashesp.com/explore/UYUmF7ygOj8LwH4BxZO1N/files/cP6wDgnK2CcBrVVMuQOcc.md)
- readme.md (1.4 KB)

## README

# ESP32 + QMC5883P Compass (I2C)

![Project photo](https://i.imgur.com/WtLTu7O.png)

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.
