-
Notifications
You must be signed in to change notification settings - Fork 1
lis2mdl: add magnetometer driver. #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
b5782f1
lis2mdl: initialise LIS2MDL driver.
Charly-sketch c4ed730
lis2mdl: add first measurement values.
Charly-sketch e147cfc
lis2mdl: fix device configuration and first number.
Charly-sketch 63072e9
lis2mdl: fix exemple point to north.
Charly-sketch 1bbab38
lis2mdl: add driver function and example.
Charly-sketch d853c4b
lis2mdl: add LIS2MDL driver.
Charly-sketch 5bc3789
lis2mdl: add LIS2MDL exemple.
Charly-sketch c80aebe
lis2mdl: correct simple linter errors.
nedseb 61d93d3
lis2mdl : fix magic number errors.
Charly-sketch 2f1559f
lis2mdl : fix remove duplicate.
Charly-sketch b0cecf6
lis2mdl: Fix inverted axes and document calibration requirement.
Charly-sketch f9d08aa
lis2mdl: Fix with ruff.
Charly-sketch bfa303b
lis2mdl: Fix copilots errors.
Charly-sketch c76068c
lis2mdl: Resolve reviewer correction.
Charly-sketch 4c4ac80
lis2mdl: Add test scenario for magnetometer driver.
nedseb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,242 @@ | ||
| # LIS2MDL Magnetometer Driver for MicroPython | ||
|
|
||
| A complete and feature-rich driver for the **LIS2MDL 3-axis magnetometer** by STMicroelectronics. | ||
| This library allows easy integration of the LIS2MDL sensor with MicroPython or CircuitPython boards using I²C. | ||
| It provides low-level register access, automatic calibration, heading computation, and tilt compensation — ideal for **digital compasses**, **robot navigation**, and **orientation tracking**. | ||
|
|
||
| --- | ||
|
|
||
| ## 🧭 Features | ||
|
|
||
| * ✅ Full **I²C driver** for LIS2MDL | ||
| * ✅ Supports **10 / 20 / 50 / 100 Hz** output data rates | ||
| * ✅ **Temperature-compensated** and **low-power** modes | ||
| * ✅ Read **raw**, **scaled**, or **calibrated** magnetic field data | ||
| * ✅ **2D and 3D calibration** routines (auto min/max method) | ||
| * ✅ **Heading computation** (flat or tilt-compensated) | ||
| * ✅ **Compass direction labels** (N, NE, E, …) | ||
| * ✅ Built-in **digital low-pass filter** and **offset cancellation** control | ||
| * ✅ Diagnostic utilities: | ||
|
|
||
| * Register dump | ||
| * Calibration quality metrics | ||
| * Self-test and temperature readout | ||
|
Charly-sketch marked this conversation as resolved.
|
||
|
|
||
| --- | ||
|
|
||
| ## ⚙️ Hardware Requirements | ||
|
|
||
| * **LIS2MDL** 3-axis magnetometer (STMicroelectronics) | ||
| * **MicroPython/CircuitPython board**, e.g.: | ||
|
|
||
| * ESP32 / ESP8266 | ||
| * Raspberry Pi Pico / RP2040 | ||
| * STM32 Nucleo or Pyboard | ||
| * 3.3V power supply | ||
| * I²C interface (SCL, SDA) | ||
|
|
||
| --- | ||
|
|
||
| ## 🔌 Wiring Example (ESP32) | ||
|
|
||
| | LIS2MDL Pin | ESP32 Pin | Description | | ||
| | ----------- | --------- | ------------ | | ||
| | VIN | 3.3V | Power supply | | ||
| | GND | GND | Ground | | ||
| | SDA | GPIO21 | I²C Data | | ||
| | SCL | GPIO22 | I²C Clock | | ||
|
|
||
| Example setup: | ||
|
|
||
| ```python | ||
| from machine import I2C, Pin | ||
| from lis2mdl import LIS2MDL | ||
|
|
||
| i2c = I2C(1) | ||
| mag = LIS2MDL(i2c) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 🚀 Quick Start | ||
|
|
||
| ### Read magnetic field | ||
|
|
||
| ```python | ||
| x, y, z = mag.read_magnet_uT() | ||
| print("Magnetic field (µT):", x, y, z) | ||
| ``` | ||
|
|
||
| ### Get heading (flat orientation) | ||
|
|
||
| ```python | ||
| heading = mag.heading_flat_only() | ||
| print("Heading: {:.1f}° {}".format(heading, mag.direction_label(heading))) | ||
| ``` | ||
|
|
||
| ### With tilt compensation | ||
|
|
||
| Requires a function returning accelerometer data `(ax, ay, az)` in g: | ||
|
|
||
| ```python | ||
| def read_accel(): | ||
| return (0.0, 0.0, 1.0) # Example static vector | ||
|
|
||
| heading = mag.heading_with_tilt_compensation(read_accel) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## ⚖️ Calibration | ||
|
|
||
| Calibration is essential to obtain accurate compass readings. | ||
| The driver provides **automated routines** for both 2D (flat) and 3D calibration. | ||
|
|
||
| ### 2D Calibration (Flat) | ||
|
|
||
| Rotate the board **horizontally** in all directions: | ||
|
|
||
| ```python | ||
| mag.calibrate_minmax_2d(samples=300) | ||
| ``` | ||
|
|
||
| ### 3D Calibration (Full) | ||
|
|
||
| Rotate the board **in all orientations**: | ||
|
|
||
| ```python | ||
| mag.calibrate_minmax_3d(samples=600) | ||
| ``` | ||
|
|
||
| ### Apply and test calibration | ||
|
|
||
| ```python | ||
| print("Calibration:", mag.read_calibration()) | ||
| quality = mag.calibrate_quality() | ||
| print("Quality metrics:", quality) | ||
| ``` | ||
|
|
||
| ### Reset calibration | ||
|
|
||
| ```python | ||
| mag.calibrate_reset() | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 🧰 Configuration Examples | ||
|
|
||
| ### Output rate and power | ||
|
|
||
| ```python | ||
| mag.set_odr(50) # 50 Hz | ||
| mag.set_low_power(True) # Enable low-power mode | ||
| ``` | ||
|
|
||
| ### Enable digital low-pass filter | ||
|
|
||
| ```python | ||
| mag.set_low_pass(True) | ||
| ``` | ||
|
|
||
| ### Configure declination and heading offset | ||
|
|
||
| ```python | ||
| mag.set_declination(1.5) # Magnetic declination (°) | ||
| mag.set_heading_offset(-5.0) # Align physical 0° | ||
| ``` | ||
|
|
||
| ### Block data update (BDU) | ||
|
|
||
| ```python | ||
| mag.set_bdu(True) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 🧮 Heading Filtering | ||
|
|
||
| You can apply a **smoothing filter** on the heading angle to stabilize the readings: | ||
|
|
||
| ```python | ||
| mag.set_heading_filter(alpha=0.2) # Light smoothing | ||
| ``` | ||
|
|
||
| * `alpha = 0.0` → no filter | ||
| * `alpha = 0.1–0.3` → medium smoothing | ||
| * `alpha = 1.0` → very heavy smoothing | ||
|
|
||
| --- | ||
|
|
||
| ## 🔍 Diagnostics & Debug | ||
|
|
||
| ### Read sensor ID | ||
|
|
||
| ```python | ||
| print("WHO_AM_I:", hex(mag.read_who_am_i())) | ||
| ``` | ||
|
|
||
| Expected value: `0x40` | ||
|
|
||
| ### Read temperature (approximate) | ||
|
|
||
| ```python | ||
| print("Temperature (°C):", mag.read_temperature_c()) | ||
| ``` | ||
|
|
||
| ### Check data readiness | ||
|
|
||
| ```python | ||
| if mag.data_ready(): | ||
| print("New magnetic data available!") | ||
| ``` | ||
|
|
||
| ### Dump consecutive registers | ||
|
|
||
| ```python | ||
| regs = mag.read_registers(0x60, 12) | ||
| print("Register dump:", regs) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 🧠 Internal Methods Overview | ||
|
|
||
| | Method | Description | | ||
| | ---------------------------------- | ------------------------------ | | ||
| | `read_magnet_raw()` | Raw sensor values (int16) | | ||
| | `read_magnet_uT()` | Magnetic field in µT | | ||
| | `read_magnet_calibrated_norm()` | Calibrated and normalized data | | ||
| | `heading_flat_only()` | Flat compass heading | | ||
| | `heading_with_tilt_compensation()` | Tilt-corrected heading | | ||
| | `read_temperature_c()` | Read relative temperature | | ||
| | `power_down()` / `wake()` | Power management | | ||
| | `soft_reset()` / `reboot()` | Sensor reset functions | | ||
|
|
||
| --- | ||
|
|
||
| ## 🧪 Example: Continuous Compass Loop | ||
|
|
||
| ```python | ||
| from machine import I2C, Pin | ||
| from lis2mdl import LIS2MDL | ||
| import time | ||
|
|
||
| i2c = I2C(1, scl=Pin(22), sda=Pin(21)) | ||
| mag = LIS2MDL(i2c) | ||
| mag.set_declination(2.3) | ||
|
|
||
| while True: | ||
| heading = mag.heading_flat_only() | ||
| print("Heading: {:.1f}° {}".format(heading, mag.direction_label(heading))) | ||
| time.sleep(0.5) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 📚 References | ||
|
|
||
| * [STMicroelectronics LIS2MDL Datasheet](https://www.st.com/resource/en/datasheet/lis2mdl.pdf) | ||
| * [MicroPython Documentation](https://docs.micropython.org/en/latest/library/machine.I2C.html) | ||
|
|
||
| --- | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # Example of heading reading with direction label | ||
| from time import sleep_ms | ||
| from machine import I2C | ||
| from lis2mdl.device import LIS2MDL | ||
| from lis2mdl.const import * | ||
|
|
||
| i2c = I2C(1) | ||
| mag = LIS2MDL(i2c) | ||
|
|
||
| print("Calibrate the magnetometer by moving it in a figure-eight pattern.") | ||
| mag.calibrate_minmax_3d() | ||
| print("Calibration complete.") | ||
|
|
||
| while True: | ||
| angle = mag.heading_flat_only() | ||
|
|
||
| direction = mag.direction_label(angle) | ||
| print("Cap:", angle, "°", "-", direction) | ||
| sleep_ms(100) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| # Example of heading reading with direction label | ||
| from time import sleep_ms | ||
| from machine import I2C | ||
| from lis2mdl.device import LIS2MDL | ||
| from lis2mdl.const import * | ||
|
|
||
| i2c = I2C(1) | ||
| mag = LIS2MDL(i2c) | ||
|
|
||
| print("Calibrate the magnetometer by moving it in a figure-eight pattern.") | ||
| mag.calibrate_minmax_3d() | ||
| print("Calibration complete.") | ||
|
|
||
| while True: | ||
| field_strength = mag.magnitude_uT() | ||
| print("Champ magnétique :", field_strength, "µT") | ||
| sleep_ms(100) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.