Interfacing HMC5883L Magnetometer with Raspberry Pi
In this tutorial, we will explore how to connect the HMC5883L Triple Axis Digital Magnetometer to a Raspberry Pi and harness its capabilities using Python. The HMC5883L stands out as an optimal choice for digital compass applications, thanks to its three-dimensional magnetometer features that allow for precise measurements of magnetic field strength and orientation. This makes it an invaluable tool for pinpointing the Earth’s magnetic north.
Upon integrating the HMC5883L magnetometer with the Raspberry Pi, we will be able to fetch compass readings and ascertain the magnetic field across the X, Y, and Z axes in terms of microteslas (µT). From this data, determining the heading in degrees becomes a straightforward computation. We’ll be guiding you through every step of the process, ensuring you can seamlessly execute these tasks with Python on your Raspberry Pi.
Bill of MaterialsWe need following components to work on this project.
S.N.ComponentsQuantityPurchase Link 1Raspberry Pi 41Amazon | AliExpress | SunFounder 2HMC5883L Magnetometer1Amazon | AliExpress | SunFounder 3Jumper Wires10Amazon | AliExpress | SunFounder 4Breadboard1Amazon | AliExpress | SunFounder HMC5883L 3-Axis Compass/MagnetometerThe HMC5883L is a digital compass conceived by Honeywell. It is a surface-mount, multi-chip module engineered specifically for the detection of low magnetic fields. It is particularly adept at supplying directional data, making it a common choice for navigation and positioning systems.
The design of the HMC5883L revolves around anisotropic magnetoresistive (AMR) technology, which facilitates the precise measurement of magnetic fields. It includes three-axis sensors, with field capacities spanning from ±1.3 to ±8.1 Gauss. This denotes its capability to measure magnetic fields across three distinct axes (X, Y, and Z), allowing it to sense the direction of the Earth’s magnetic field in a three-dimensional context.
The HMC5883L is equipped with numerous inherent features that simplify its incorporation into a variety of systems. Among these are an integrated ADC (Analog-to-Digital Converter) offering 12-bit data output, and an I2C serial bus interface. This interface is utilized for device communication, enabling it to transfer data to a microcontroller or another processing unit.
The HMC5883L Magnetometer Module is comprised of an HMC5883L Magnetometer IC, a Voltage Regulator IC, resistors, and capacitors, all consolidated within an integrated circuit. It uses a voltage regulator IC XC6206P332MR (662K).
Specifications of HMC5883L- Operating Voltage: 3V to 6V DC
- Operating Current: 100-130 μA
- I2C interface
- 1-2 degree heading accuracy
- Integrated 12-bit ADC
- 160Hz max data rate
- Range of -8 to +8 Gauss
- Data Output Rate: 0.75, 1.5, 3, 7.5, 15 Hz
The HMC5883L module has five pins as shown in this image below:
Here is a basic description of the typical pinout for an HMC5883L module.
- VCC: This is the power supply pin. It requires a DC voltage, typically 3V -6V.
- GND: This is the ground pin.
- SCL: This is the clock line for the I2C interface.
- SDA: This is the data line for the I2C interface.
- DRDY: This is Data Ready pin which goes low when new data is available. It’s optional and isn’t always used in basic applications.
The HMC5883L magnetometer uses various internal registers to configure and receive data:
- Configuration Register A (0x00): Configures device operation, including output data rate and measurement configuration.
- Configuration Register B (0x01): Sets the device gain and sensitivity.
- Mode Register (0x02): Selects the operating mode, such as continuous measurement, single measurement, or idle mode.
- Data Output X Registers (0x03 and 0x04): Hold X-axis sensor readings.
- Data Output Y Registers (0x05 and 0x06): Hold Y-axis sensor readings.
- Data Output Z Registers (0x07 and 0x08): Hold Z-axis sensor readings.
- Status Register (0x09): Contains status flags about data output.
- Identification Registers (0x0A, 0x0B, 0x0C): Used to identify the device.
The HMC5883L employs the I2C communication protocol, functioning as a slave device. Its designated I2C device address is 0x1E. The corresponding addresses for its read and write operations are as follows:
- For write operations (SLA+W), the address is 0x3C.
- For read operations (SLA+R), the address is 0x3D.
Let us interface the HMC5883L Magnetometer with Raspberry Pi 4 using Python code and extract magnetometer readings for the X, Y, and Z axes, as well as the heading information.
The connection diagram is straightforward.
Connect the VCC & GND pin of the HMC5883L magnetometer to the 3.3V & GND pin of the Raspberry Pi. Likewise, join the SDA & SCL pins of the Magnetometer to the SDA (GPIO2) & SCL (GPIO3) pins of the Raspberry Pi respectively.
Setting Up the Raspberry PiBefore moving directly to the Python programming part, we need to setup the Raspberry Pi.
1. Enable I2C on the Raspberry Pi:
- Open a terminal and type sudo raspi-config .
- Navigate to Interfacing Options >I2C and enable it.
- Reboot the Raspberry Pi.
2. Install the necessary Python packages:
sudo apt - get update sudo apt - get install i2c - tools python3 - smbus3. Detect the device: After connecting the HMC5883L, you can detect it using the following command:
i2cdetect - y 1If everything is connected properly, you should see an address 1E appear in the list, which is the default address for the HMC5883L.
Python Code for Interfacing HMC5883L with Raspberry PiHere is a Python Code to interface HC5883L Magnetometer with Raspberry Pi 4. Copy the following code and paste it on your Thonny IDE. Then Save it with any name.
This simple Python script will read data from the HMC5883L.
import smbus import time import math # HMC5883L register addresses ADDRESS = 0x1E CONFIG_A = 0x00 CONFIG_B = 0x01 MODE = 0x02 X_MSB = 0x03 Z_MSB = 0x05 Y_MSB = 0x07 bus = smbus . SMBus ( 1 ) bus . write_byte_data ( ADDRESS , CONFIG_A , 0x70 ) # Set to 8 samples @ 15Hz bus . write_byte_data ( ADDRESS , CONFIG_B , 0x20 ) # 1.3 gain LSb / Gauss 1090 (default) bus . write_byte_data ( ADDRESS , MODE , 0x00 ) # Continuous measurement mode def read_raw_data ( addr ) : # Read raw 16-bit value high = bus . read_byte_data ( ADDRESS , addr ) low = bus . read_byte_data ( ADDRESS , addr + 1 ) # Combine them to get a 16-bit value value = ( high 32768 : # Adjust for 2's complement value = value - 65536 return value def compute_heading ( x , y ) : # Calculate heading in radians heading_rad = math . atan2 ( y , x ) # Adjust for declination angle (e.g. 0.22 for ~13 degrees) declination_angle = 0.22 heading_rad += declination _ angle # Correct for when signs are reversed. if heading_rad < 0 : heading_rad += 2 * math . pi # Check for wrap due to addition of declination. if heading_rad > 2 * math . pi : heading_rad -= 2 * math . pi # Convert radians to degrees for readability. heading_deg = heading_rad * ( 180.0 / math . pi ) return heading_deg while True : x = read_raw_data ( X_MSB ) y = read_raw_data ( Y_MSB ) z = read_raw_data ( Z_MSB ) heading = compute_heading ( x , y ) print ( f "X: uT, Y: uT, Z: uT, Heading: °" ) time . sleep ( 0.5 ) if __name__ == "__main__" :This script initializes the HMC5883L in continuous measurement mode and then continuously reads and prints the X, Y, and Z magnetometer values. The data might need to be calibrated or adjusted depending on your application and surrounding magnetic fields.
To calculate the heading (or the orientation in degrees) using the magnetometer values, one usually makes use of the arctangent function. The heading can be determined from the X and Y magnetometer readings.
Testing & ResultsYou may run the above Python Script and the Thonny Shell will start showing the Magnetometer readings in micro-Tesla and Heading angles in degrees.
To observe the change in magnetic field values, bring any magnetic material or magnet near the sensor. You will observe drastic change in the magnetic field readings. The heading angle can be varied simly by rotating the sensor.
Remember, the computed heading will be relative to the Earth’s magnetic North and not the true North. This distinction is important if you are navigating based on the heading.
The difference between the magnetic North and the true North is known as the magnetic declination, and it varies depending on your geographic location. You might need to adjust the heading for magnetic declination based on where you’re located.
Previous Article Measuring Acceleration with ADXL345 Accelerometer & Raspberry Pi Next Article Solar Radiation Measurement using Pyranometer Sensor & Arduino Related Posts ADXL375 Accelerometer with Raspberry Pi Pico & MicroPython Updated: July 24, 2025 Interface BMI160 with Raspberry Pi Pico & MicroPython Updated: February 2, 2025 2K Shift Register 74HC595 with Raspberry Pi Pico & MicroPython Updated: February 2, 2025 1 3K Interfacing XBee Module with Raspberry Pi Pico & MicroPython Updated: February 2, 2025 3K Modbus RTU with Raspberry Pi Pico & MicroPython Updated: February 2, 2025 7K Thermal Fever Detector with MLX90640 & OpenCV Raspberry Pi Updated: February 2, 2025 6K CommentsCancel reply Latest Posts ESP32 IoT Vehicle Motion Analyzer with MPU6050 & LIS3MDL March 10, 2026 Building a Smart Sensor Node with a BLE Microcontroller February 26, 2026 High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU February 16, 2026 DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32 February 1, 2026 Flight Black-Box Motion Recorder System using ESP32 & BMI160 December 7, 2025 ESP8266 & DHT11 Humidity Temperature Monitor on ThingSpeak October 19, 2025 IoT based Battery SoC (%) Monitoring System with ESP32 September 28, 2025 Speed-Run Translations: Making Fast-Moving Meme Videos Accessible Worldwide September 22, 2025 Top Posts & Pages Categories- Arduino Projects (197)
- Articles (59)
- Learn Electronics (19)
- Product Review (15)
- Tech Articles (27)
- 555 Timer Projects (21)
- Op-Amp Circuits (7)
- Power Electronics (13)
- ESP32 MicroPython (7)
- ESP32 Projects (78)
- ESP32-CAM Projects (15)
- ESP8266 Projects (76)
- LoRa/LoRaWAN Projects (22)
- AMB82-Mini IoT AI Camera (4)
- BLE Projects (18)
- STM32 Projects (19)
- Raspberry Pi Pico Projects (57)
- Raspberry Pi Pico W Projects (12)
- Raspberry Pi Projects (24)
“‘How to Electronics’ is a vibrant community for electronics enthusiasts and professionals. We deliver latest insights in areas such as Embedded Systems, Power Electronics, AI, IoT, and Robotics. Our goal is to stimulate innovation and provide practical solutions for students, organizations, and industries. Join us to transform learning into a joyful journey of discovery and innovation.
Copyright © How To Electronics. All rights reserved. Ad Blocker Enabled! Ad Blocker Enabled!Looks like you're using an ad blocker. Please allow ads on our site. We rely on advertising to help fund our site.