Labs / Electronic modules

GraftSense - Open Version Tri-Axial Magnetometer Sensor Module Based on LIS2MDL

Author: Li Zisheng · Source: FreakStudio open documentation, v1.1 · License: CC BY 4.0 · Driver code (sensors/lis2mdl_driver): MIT License

Contents
LIS2MDL
LIS2MDL LED1 R3 U1 U2 3-Axis V1.0.0

I. Module Introduction

3-axis magnetometer sensor module based on LIS2MDL, which adopts STMicroelectronics' LIS2MDL ultra-low-power 3-axis digital magnetometer solution, can accurately measure the magnetic field strengths of the X / Y / Z three axes and output 16-bit digital signals, realizing the functions of electronic compass and azimuth calculation;The module is equipped with LDO voltage regulator circuits, power filtering and indicator circuits, is powered by 3.3V and communicates with the main controller via the I²C interface. It has built-in temperature compensation and self-calibration functions, supports programmable interrupt triggering, and is applicable to scenarios such as wearable devices, IoT terminals, navigation and positioning, and AR / VR devices.

II. Introduction to Main Chips

LIS2MDL is an ultra-low-power, high-performance three-axis digital magnetometer launched by STMicroelectronics , with a measurement range of ±50 gauss, 16-bit output, supporting I²C / SPI interfaces, and is suitable for electronic compass and attitude detection.

2.1 Chip Overview

LIS2MDL 50 16 3

LIS2MDL is an ultra-low-power, high-performance 3-axis digital magnetometer launched by STMicroelectronics, with a measurement range of ±50 gauss, 16-bit data output, support for I²C / SPI interfaces, a built-in temperature sensor, programmable interrupt and self-test functions, a supply voltage of 1.71~3.6V, and is packaged in LGA-12, which is suitable for scenarios such as electronic compass and attitude detection.

2.2 Pin Definition

LIS2MDL LGA-12 12
LIS2MDL 2 1-12 1 5 C1 220nF 3

LIS2MDL adopts the LGA-12 package with clearly defined pin functions: Vdd / Vdd_IO are power supply pins, and GND is the ground pin; Pin 1 SCL / SPC and Pin 4 SDA / SDI / SDO form the I²C / SPI interface, Pin 24 CS is used to select the communication mode (high level for I²C, low level for SPI); Pin 7 INT / DRDY / SDO can serve as an interrupt, data ready signal, or SPI 4-wire data output; Pin 5 requires an external 220nF capacitor, and the remaining pins are NC (no connection).

2.3 Functional Block Diagram

LIS2MDL

LIS2MDL senses the external magnetic field via a 3-axis magnetic sensor; after channel switching through a multiplexer, the signal is sent to a charge amplifier for amplification, then converted to a digital value by an A / D converter, processed by the control logic, and output as data through the I²C / SPI interface. Meanwhile, the on-chip integrated temperature sensor, self-test, calibration circuit and clock module ensure measurement accuracy and functional stability, and support the output of INT / DRDY interrupt signals.

2.4 Performance Parameters

LIS2MDL 3 6

LIS2MDL features a magnetic field dynamic range of ±49.152 gauss, a typical sensitivity of 1.5 milligauss per LSB, an RMS noise as low as 3 milligauss, a zero offset within ±60 milligauss, supports self-test function, and operates over a temperature range of -40℃ to + 85℃.

4 2.5V 25 8digit 40 85 5 1.71V 3.6V 200

The LIS2MDL has a typical temperature sensor sensitivity of 8 digit/°C, a supply voltage range of 1.71-3.6V, a current consumption of 200μA in high resolution mode, 50μA in low-power mode, and only 1.5μA in power-down mode; the digital I / O high and low level thresholds are related to the supply voltage, with an operating temperature range of -40°C to + 85°C.

LIS2MDL 0.3 4.8V 10000 40 85 125 2kV

LIS2MDL has an absolute maximum rated supply voltage (Vdd / Vdd_IO) range of -0.3 V to 4.8 V, a control pin input voltage range of -0.3 V to Vdd_IO + 0.3 V, a maximum exposed magnetic field strength of 10000 gauss, an operating temperature range of -40 °C to + 85 °C, a storage temperature range of -40 °C to + 125 °C, and an ESD protection rating of 2 kV; it is also noted that the device is sensitive to mechanical shock and electrostatic discharge.

2.5 Reference Circuit

LIS2MDL 10 100nF 220nF C1

LIS2MDL In the application circuit, the chip core is powered by Vdd, and the I / O ports are powered by Vdd_IO. Both require decoupling capacitors (10μF + 100nF for the Vdd terminal, 100nF for the Vdd_IO terminal); the 220nF low- ESR capacitor C1 connected to pin 5 should be placed close to the pin to avoid the influence of copper foil inductance;In terms of communication, I²C mode requires pulling CS high, SPI mode requires pulling it low, the INT pin function can be configured via I²C / SPI programming, and when only supplying power to Vdd_IO, communication can be maintained while the measurement chain is turned off.

2.6 Chip Configuration

None.

2.7.1 I2C Communication

LIS2MDL I2C 3W 15

LIS2MDL supports I²C and 3 -wire / 4 -wire SPI two digital interfaces, which share the same set of pins;The CS pin serves as the mode selection terminal: a high level enables I²C communication, while a low level enables SPI communication;SCL / SPC, SDA / SDI / SDO correspond to the I²C clock/data and SPI clock/input/output functions respectively.

LIS2MDL 100 400 1 3.4

The LIS2MDL I²C interface operates in slave mode, supports register read and write operations, and uses the clock line and clock line and SDA bidirectional data line, both of which require external pull-up resistors; this interface is compatible with Standard-mode (100kHz), Fast-mode (400kHz), Fast-mode Plus (1MHz) and High-speed mode (3.4MHz).

LIS2MDL

The LIS2MDL I²C interface acts as a slave device and complies with the standard I²C protocol: the master initiates transmission via a START signal, sends the slave address plus a read/write bit, and after the slave responds with an ACK, the register sub-address (supporting automatic address increment) is sent; write operations support single-byte or multi-byte continuous writing, while for read operations, the write address and sub-address must be sent first, then switch to read mode via a repeated START, during multi-byte reading the master sends ACK to sustain the transmission, and finally terminates it with a NACK.

LIS2MDL 6 0 0011110 1 3DH 3CH

LIS2MDL I²C communication follows the most significant bit (MSB) first transmission order, supports clock stretching and NACK termination mechanism; its default slave address is 0011110b, the read operation address is 3Dh, and the write operation address is 3Ch. For read operations, a repeated start signal (SR) must be sent after the subaddress to switch the direction, and the transmission is finally terminated by a STOP condition.

2.7.2 Registers

2.7.2.1 Hard Iron Offset Compensation Register
LIS2MDL 45h 46h 47h 48h 49h 4Ah 16 4Fh

LIS2MDL 's 0x45h to 0x4Ah are X / Y / Z axis 16-bit hard iron offset compensation registers (in two' s complement format), which are used to eliminate ambient magnetic field offset;0x4Fh is the WHO_AM_I device identification register, whose fixed value can be used for chip identity verification.

2.7.2.2 CFG_REG_A Function Configuration Register
LIS2MDL 60h 1 0 ODR1 ODR0 10/20/50/100Hz MD1 MD0

CFG_REG_A (address 60h) is the configuration register of LIS2MDL, which can set temperature compensation, reboot, soft reset, low-power mode, output data rate (ODR, supporting 10/20/50/100Hz) and operation mode (continuous / single / idle), serving as a key register for configuring sensor measurement parameters.

2.7.2.3 CFG_REG_B Function Configuration Register
LIS2MDL 61h 0 ODR/2 1 ODR/4

CFG_REG_B (address 61h) is a function configuration register of the LIS2MDL, which can be used to configure single/general bias cancellation, interrupt trigger timing, set pulse frequency and digital low-pass filter; when the low-pass filter is enabled, the bandwidth is reduced from ODR / 2 to ODR / 4, so as to optimize measurement noise and accuracy.

2.7.2.4 CFG_REG_C Function Configuration Register
LIS2MDL 62h I2C_DIS 4WSPI 4

CFG_REG_C (Address 62h) is a function configuration register of the LIS2MDL, which can be used to configure the interrupt/data-ready signal pin output, I²C interface disable, data update lock (BDU), data byte order (BLE), 4-wire SPI mode, and self-test function, so as to realize flexible configuration of sensor communication and interrupt behavior.

2.7.2.5 INT_CTRL_REG Interrupt Control Register
LIS2MDL 63h 1 0
LIS2MDL 64h 0 1

INT_CTRL_REG (address 63h) is the interrupt control register of the LIS2MDL, which is used to configure the three-axis interrupt detection enable (X / Y / ZIEN, all enabled by default), interrupt polarity (IEA), interrupt signal mode (IEL, pulse / latch) and global interrupt enable (IEN); in latch mode, the interrupt status needs to be cleared by reading INT_SOURCE_REG (64h).

2.7.2.6 INT_SOURCE_REG Interrupt Source Register
LIS2MDL 64h

INT_SOURCE_REG (address 64h) is the interrupt source register of the LIS2MDL. Reading this register in latched mode will automatically clear all flag bits. It records whether the three-axis magnetic field values exceed the positive and negative thresholds, the MROI flag, and whether an interrupt event has occurred, making it a key register for determining the source of an interrupt.

2.7.2.7 INT_THS_L_REG Interrupt Threshold Low Byte Register
LIS2MDL TH7 TH0 7 0 8 16

INT_THS_L_REG (address 65h) is the low-byte register of the interrupt threshold for LIS2MDL, which stores the lower 8 bits of the interrupt threshold (TH[7:0]). It needs to cooperate with the corresponding high-byte register to form a complete 16-bit interrupt trigger threshold, which is used to set the value for triggering an interrupt upon magnetic field abnormality.

2.7.2.8 INT_THS_H_REG Interrupt Threshold High Byte Register
LIS2MDL 66h 8 15 TH15 TH8 16
39 8 15

INT_THS_H_REG (address 66h) is the interrupt threshold high-byte register of the LIS2MDL, which stores the upper 8 bits of the interrupt threshold (TH[15:8]). It needs to be used together with the low-byte register to form a 16-bit unsigned absolute value threshold. This threshold is shared by the three axes, and an interrupt will be triggered when the magnetic field value in either the positive or negative direction exceeds the threshold.

2.7.2.9 STATUS_REG Read-only Status Register
LIS2MDL 8

STATUS_REG (address 67h) is a read-only status register of the LIS2MDL, used to indicate the device's data status. It contains three-axis data ready flags (Zyxda / zda / yda / xda) and data overflow flags (Zyxor / zor / yor / xor), which can be used to quickly determine whether new data is available for reading or data overwriting has occurred.

2.7.2.10 OUTX_L_REG / OUTX_H_REG X-axis Magnetic Field Data Register
LIS2MDL 68h 69h 8
69h 8 0 68h LIS2MDL

OUTX_L_REG / OUTX_H_REG (address 68h - 69h ) is LIS2MDL 's X -axis magnetic field data register, consisting of low bytes ( 68h ) and high bytes ( 69h ) consisting of 16-bit data; when the OFFSET_X_REG is zero, the original magnetic field data is output, otherwise it is compensated data after hard iron bias calibration.

2.7.2.11 OUTY_L_REG / OUTY_H_REG Y-axis Magnetic Field Data Register
LIS2MDL 8 0 6Ah 6Bh

OUTY_L_REG / OUTY_H_REG (address 6Ah - 6Bh ) is LIS2MDL 's Y -axis magnetic field data register, consisting of low bytes ( 6Ah ) and high bytes ( 6Bh ) to form 16-bit complement format data; when the OFFSET_Y_REG is zero, the original magnetic field data is output, otherwise it is the compensation data after hard iron bias calibration, reflecting the Y -axis component of the magnetic field.

2.7.2.12 OUTZ_L_REG / OUTZ_H_REG Z-axis Magnetic Field Data Register
LIS2MDL 6Ch 6Dh 8

OUTZ_L_REG / OUTZ_H_REG (address 6Ch - 6Dh ) is LIS2MDL 's Z -axis magnetic field data register, consisting of low bytes ( 6Ch ) and high bytes ( 6Dh ) composed of 16-bit complement format data; when the OFFSET_Z_REG is zero, the original magnetic field data is output, otherwise it is the compensation data after hard iron bias calibration, reflecting the Z -axis component of the magnetic field.

2.7.2.13 TEMP_OUT_L_REG / TEMP_OUT_H_REG Temperature Data Registers
LIS2MDL 6Eh 6Fh 16 4 8

TEMP_OUT_L_REG / TEMP_OUT_H_REG (addresses 6Eh / 6Fh) are the temperature data registers of the LIS2MDL, which store the 16-bit two's complement data from the internal temperature sensor. The upper 4 bits are sign extension bits, with a nominal sensitivity of 8 LSB/°C, and are used to obtain the operating temperature information of the chip.

2.8 PCB Routing Precautions

None.

III. Circuit Engineering

3.1 Circuit Source Engineering

To obtain the source code of the circuit, please follow the official account [Freak Embedded]

3.2 Module Usage Instructions

The schematic diagram of this module is shown below:

SCH_Schematic1_LIS2MDL-Based 3-Axis Magnetometer Sensor Module_v1.0.0_2026-05-11.pdf 2.2 MB

LIS2MDL C1 C8 R1 R2 U1 U2 LED1 R3 3-Axis

This module provides an IIC communication interface: it supports standard I2C communication rates, is compatible with 3.3V logic level, and can stably transmit the 16-bit digital signals of triaxial magnetic field intensity on the LIS2MDL collected X / Y / Z axes. It is applicable to scenarios such as wearable devices, IoT terminals, navigation and positioning, and AR / VR devices, providing the system with reliable data interaction capabilities for electronic compass and orientation perception.

3.3 Application Experiment

Here, we use the GraftPort-RP2040 development board for testing, and the LIS2MDL-based 3-axis magnetometer sensor module communicates with the main controller via the I2C interface.

Here, we first use the HY2.0-4P connection cable to connect the module to the GraftPort-RP2040 development board's I2C0 interface:

Development Board Pins

Module Pins

Description

Pin 4

SDA

I2C data transmission line, corresponding to I2C0 's SDA

Pin 5

SCL

I2C clock signal line, corresponding to the I2C0 SCL

Here, we need to search for the relevant driver packages on uPyPI: https://upypi.net/zh/

106 lis2mdl_driver

Enter lis2mdl_driver to search, and the following will be displayed:

lis2mdl_driver 1.0.0 2026 05 29

Click to copy the local installation command:

lis2mdl_driver LIS2MDL 1.0.0 2026 05 29 upypi.net/upypi/net/lis2mdl_driver/lis2mdl_driver/1.0.0

Import the module driver library code via the mip tool. Below are the usage commands for the mpremote tool:

mpremote mip install https://upypi.net/pkgs/lis2mdl_driver/1.0.0

Import the 3-axis magnetometer sensor module based on LIS2MDL - MicroPython driver code, then copy the following main.py code into our project:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time    : 2025/9/8 4:52 PM
# @Author  : Jose D. Montoya
# @File    : main.py
# @Description : LIS2MDL magnetometer data reading program, supports automatic I2C device scanning and initialization
# @License : MIT
__version__ = "0.1.0"
__author__ = "Jose D. Montoya"
__license__ = "MIT"
__platform__ = "MicroPython v1.23.0"


# ======================================== Import Modules =========================================

import time
from machine import Pin, SoftI2C
from micropython_lis2mdl import lis2mdl


# ======================================== Global Variables ============================================

# Target sensor address list
TARGET_SENSOR_ADDRS = [0x1E]


# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================


# ======================================== Initialization configuration ===========================================

# I2C bus initialization, using software I2C
i2c_bus = SoftI2C(sda=Pin(4), scl=Pin(5), freq=400000)

# Start scanning for devices on the I2C bus
devices_list: list[int] = i2c_bus.scan()
print("START I2C SCANNER")

# Check the I2C device scan result
if len(devices_list) == 0:
    print("No i2c device !")
    raise SystemExit("I2C scan found no devices, program exited")
else:
    print("i2c devices found:", len(devices_list))

# Iterate over the address list to initialize the target sensor

sensor = None  # Placeholder for the sensor object initialization
for device in devices_list:
    if device in TARGET_SENSOR_ADDRS:
        print("I2c hexadecimal address:", hex(device))
        try:
            # Automatically identify and initialize the corresponding sensor
            sensor = lis2mdl.LIS2MDL(i2c=i2c_bus)
            print("Sensor initialization successful")
            break
        except Exception as e:
            print(f"Sensor Initialization failed: {e}")
            continue
else:
    # Target device not found, raise an exception
    raise Exception("No target sensor device found in I2C bus")

# Set sensor data output rate to 100Hz
sensor.data_rate = lis2mdl.RATE_100_HZ


# ========================================  Main Program  ============================================

# Main loop: iterate through all data rate modes and continuously read magnetic field data
while True:
    for data_rate in lis2mdl.data_rate_values:
        print("Current Data rate setting: ", sensor.data_rate)
        for _ in range(10):
            mag_x, mag_y, mag_z = sensor.magnetic
            print(f"X:{mag_x:.2f}, Y:{mag_y:.2f}, Z:{mag_z:.2f} uT")
            print()
            time.sleep(0.5)
        sensor.data_rate = data_rate

Burn the code, open the terminal, and the output is as follows:

LIS2MDL I2C 100Hz 10Hz

The geomagnetic sensor (I2C address 0x1e) is initialized properly with normal I2C communication, supports data rate switching between 100Hz and 10Hz, its three-axis geomagnetic readings update in real time as the attitude changes, and it works with normal response.

IV. Drivers

lis2mdl_driver-1.0.0.zip 14 KB

None.

VI. Revision History

Document Version

Date Modified

Modifier

Modify Content

v1.0

2026-05-12

Ling Gaoxing

Initialize the document

v1.1

2026-06-06

Xin Ruili

Create an open version of the document based on the internal document version v1.0.

7. Relevant Materials

7.1 Chip Datasheet

LIS2MDLTR.pdf 1.0 MB

7.2 Unique Icons for PCB Silk Screen

LIS2MDL 7.2