Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 14 additions & 16 deletions lib/lis2mdl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,22 +215,20 @@ print("Register dump:", regs)

---

## 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)
```
## Examples

| Example | Description |
|-----------------------------|-------------|
| basic_read.py | Read raw magnetic field (X, Y, Z) in microtesla and temperature in a loop. Simplest entry point to the LIS2MDL driver. |
| calibrate_2d.py | Interactive 2D hard-iron calibration. The user rotates the board flat to compute offsets using `calibrate_minmax_2d()`, then evaluates calibration quality with `calibrate_quality()`. |
| tilt_compensated_heading.py | Tilt-compensated heading using both magnetometer and accelerometer. Combines `heading_with_tilt_compensation()` from LIS2MDL with acceleration data from the ISM330DL driver. **Dependency: `ism330dl` driver required.** |
| metal_detector.py | Detect nearby metal objects by monitoring magnetic field magnitude changes. Displays an intensity bar and triggers a buzzer with stronger beeps for stronger disturbances. **Dependency: board PWM/buzzer support required, no extra driver needed.** |
| door_sensor.py | Detect door open/close using a magnet. Compares live magnetic field magnitude to a closed-door baseline and prints state changes with timestamps. |
| field_logger.py | Log magnetic field (X, Y, Z) and temperature to a CSV file every second for 60 seconds. The file is written to DAPLink flash and can be read later over USB mass storage. **Dependency: `daplink_flash` driver/module required (`set_filename`, `write_line`).** |
| field_map.py | Real-time spatial magnetic field mapping. Displays X, Y, Z, field magnitude, and min/max tracking for each axis while the board is moved around. |
| low_power_one_shot.py | Energy-efficient sampling example. Uses `power_off()` between readings and `read_one_shot()` every 10 seconds, then prints values and free memory. |
| magnet_compass.py | Flat compass example that computes heading and cardinal direction from the LIS2MDL magnetic field. Useful for basic orientation demos. |
| magnet_fieldForce.py | Magnetic field magnitude example that shows total field strength in microtesla. Useful for observing magnetic disturbances and relative field changes. |
Comment thread
Charly-sketch marked this conversation as resolved.

---

Expand Down
28 changes: 28 additions & 0 deletions lib/lis2mdl/examples/basic_read.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
Read raw magnetic field (X, Y, Z) in microtesla and temperature in a loop.
Simplest possible example — good entry point for beginners.
"""

from time import sleep_ms

from lis2mdl import LIS2MDL
from machine import I2C

i2c = I2C(1)
mag = LIS2MDL(i2c)

print("LIS2MDL basic read example")
print("Press Ctrl+C to stop.")
print()

while True:
x_ut, y_ut, z_ut = mag.magnetic_field_ut()
temp_c = mag.temperature()

print(
"Magnetic field: X={:.2f} uT Y={:.2f} uT Z={:.2f} uT Temp={:.2f} C".format(
x_ut, y_ut, z_ut, temp_c
)
)

sleep_ms(500)
60 changes: 60 additions & 0 deletions lib/lis2mdl/examples/calibrate_2d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
Interactive hard-iron calibration.
Ask the user to slowly rotate the board flat on a table.
Uses calibrate_minmax_2d() to compute offsets, then displays before/after heading quality with calibrate_quality().
Demonstrates the full calibration workflow.
"""
from time import sleep_ms

from lis2mdl import LIS2MDL
from machine import I2C


def print_quality(title, quality):
print(title)
print(" mean_xy = ({:.3f}, {:.3f})".format(quality["mean_xy"][0], quality["mean_xy"][1]))
print(" mean_z = {:.3f}".format(quality["mean_z"]))
print(" std_xy = ({:.3f}, {:.3f})".format(quality["std_xy"][0], quality["std_xy"][1]))
print(" std_z = {:.3f}".format(quality["std_z"]))
print(" r_mean_xy = {:.3f}".format(quality["r_mean_xy"]))
print(" r_std_xy = {:.3f}".format(quality["r_std_xy"]))
print(" anisotropy_xy = {:.3f}".format(quality["anisotropy_xy"]))
print()


i2c = I2C(1)
mag = LIS2MDL(i2c)

print("2D hard-iron calibration example")
print("Keep the board flat on a table.")
print("Slowly rotate it through full circles.")
print()

print("Checking heading quality before calibration...")
quality_before = mag.calibrate_quality(samples_check=120, delay_ms=15)
print_quality("Before calibration:", quality_before)

print("Starting 2D calibration now...")
mag.calibrate_minmax_2d(samples=300, delay_ms=20)

print("Calibration values:")
print(
" x_off={:.2f} y_off={:.2f} x_scale={:.2f} y_scale={:.2f}".format(
mag.x_off, mag.y_off, mag.x_scale, mag.y_scale
)
)
print()

print("Checking heading quality after calibration...")
quality_after = mag.calibrate_quality(samples_check=120, delay_ms=15)
print_quality("After calibration:", quality_after)

print("Live heading preview after calibration")
print("Press Ctrl+C to stop.")
print()

while True:
heading = mag.heading_flat_only()
direction = mag.direction_label(heading)
print("Heading: {:7.2f} deg Direction: {}".format(heading, direction))
sleep_ms(200)
59 changes: 59 additions & 0 deletions lib/lis2mdl/examples/door_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
Detect door open/close using a magnet.
Measure baseline field with door closed (magnet near sensor).
Loop and detect large magnitude drop = door opened. Print state changes with timestamp.
Demonstrates a practical IoT use case.
"""

from time import sleep_ms, ticks_diff, ticks_ms

from lis2mdl import LIS2MDL
from machine import I2C

BASELINE_SAMPLES = 60
OPEN_DROP_UT = 10.0
CLOSE_RECOVER_UT = 6.0


def elapsed_seconds(start_ms):
return ticks_diff(ticks_ms(), start_ms) / 1000.0


i2c = I2C(1)
mag = LIS2MDL(i2c)

print("Door sensor example")
print("Place the board with the door closed and the magnet in its normal closed position.")
print("Measuring closed-door baseline...")
print()

baseline = 0.0
for _ in range(BASELINE_SAMPLES):
baseline += mag.magnitude_ut()
sleep_ms(100)

baseline /= BASELINE_SAMPLES
start_ms = ticks_ms()
state = "CLOSED"

print("Closed baseline: {:.2f} uT".format(baseline))
print("Monitoring door state changes...")
print()

while True:
magnitude = mag.magnitude_ut()
drop = baseline - magnitude

if state == "CLOSED" and drop >= OPEN_DROP_UT:
state = "OPEN"
print("[t+{:.1f}s] Door opened |B|={:.2f} uT drop={:.2f} uT".format(
elapsed_seconds(start_ms), magnitude, drop
))

elif state == "OPEN" and drop <= CLOSE_RECOVER_UT:
state = "CLOSED"
print("[t+{:.1f}s] Door closed |B|={:.2f} uT drop={:.2f} uT".format(
elapsed_seconds(start_ms), magnitude, drop
))

sleep_ms(200)
61 changes: 61 additions & 0 deletions lib/lis2mdl/examples/field_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""
Log magnetic field X, Y, Z and temperature to DAPLink flash as CSV every second for 60 seconds.
Uses daplink_flash (set_filename, write_line).
File is then accessible via USB mass storage for analysis in a spreadsheet.
"""

from time import sleep_ms, ticks_diff, ticks_ms

from daplink_flash import DaplinkFlash
from lis2mdl import LIS2MDL
from machine import I2C

# Set to True to erase the DAPLink flash on startup (DESTRUCTIVE).
ERASE_FLASH_ON_START = False

LOG_DURATION_S = 60
SAMPLE_PERIOD_MS = 1000


i2c = I2C(1)
sensor = LIS2MDL(i2c)
flash = DaplinkFlash(i2c)

flash.set_filename("LIS2MDL", "CSV")
if ERASE_FLASH_ON_START:
flash.clear_flash()
sleep_ms(500)
print("Flash erased.")

start_ms = ticks_ms()

header = "timestamp_s,x_ut,y_ut,z_ut,magnitude_ut,temperature_c"
print(header)
flash.write_line(header)

while True:
elapsed_s = ticks_diff(ticks_ms(), start_ms) // 1000
x_ut, y_ut, z_ut = sensor.magnetic_field_ut()
magnitude_ut = sensor.magnitude_ut()
temperature_c = sensor.temperature()

line = "{},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f}".format(
elapsed_s,
x_ut,
y_ut,
z_ut,
magnitude_ut,
temperature_c,
)

print(line)
flash.write_line(line)

if elapsed_s >= LOG_DURATION_S:
break

sleep_ms(SAMPLE_PERIOD_MS)

print()
print("Logging complete.")
print("The CSV file is available from the DAPLink USB mass storage.")
58 changes: 58 additions & 0 deletions lib/lis2mdl/examples/field_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""
Spatial field mapping.
Print X, Y, Z field values and magnitude as a formatted table, updating every 500ms.
Move the board around to see how the field changes.
Includes min/max tracking for each axis to show the range explored.
"""

from math import sqrt
from time import sleep_ms

from lis2mdl import LIS2MDL
from machine import I2C


def update_minmax(value, current_min, current_max):
current_min = min(current_min, value)
current_max = max(current_max, value)
return current_min, current_max


i2c = I2C(1)
mag = LIS2MDL(i2c)

x_min = y_min = z_min = 1e9
x_max = y_max = z_max = -1e9

print("Field map example")
print("Move the board around and watch how the field changes.")
print()

header = "{:>8} {:>8} {:>8} {:>10} {:>17} {:>17} {:>17}".format(
"X(uT)", "Y(uT)", "Z(uT)", "|B|(uT)",
"X range", "Y range", "Z range"
)
print(header)
print("-" * len(header))

while True:
x_ut, y_ut, z_ut = mag.magnetic_field_ut()
magnitude = sqrt(x_ut * x_ut + y_ut * y_ut + z_ut * z_ut)

x_min, x_max = update_minmax(x_ut, x_min, x_max)
y_min, y_max = update_minmax(y_ut, y_min, y_max)
z_min, z_max = update_minmax(z_ut, z_min, z_max)

print(
"{:8.2f} {:8.2f} {:8.2f} {:10.2f} {:>17} {:>17} {:>17}".format(
x_ut,
y_ut,
z_ut,
magnitude,
"[{:.2f}, {:.2f}]".format(x_min, x_max),
"[{:.2f}, {:.2f}]".format(y_min, y_max),
"[{:.2f}, {:.2f}]".format(z_min, z_max),
)
)

sleep_ms(500)
49 changes: 49 additions & 0 deletions lib/lis2mdl/examples/low_power_one_shot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
Energy-efficient sampling.
Use power_off() between readings, trigger read_one_shot() every 10s.
Print values and free memory.
Demonstrates idle mode for battery-powered deployments.
"""

import gc
from math import sqrt
from time import sleep_ms

from lis2mdl import LIS2MDL
from machine import I2C

MAG_LSB_TO_UT = 0.15
SAMPLE_INTERVAL_MS = 10000


i2c = I2C(1)
mag = LIS2MDL(i2c)

print("Low-power one-shot example")
print("The sensor stays in idle mode between readings.")
print("One sample every 10 seconds.")
print()

while True:
mag.power_off()

# Sleep in small steps so Ctrl+C remains responsive.
for _ in range(SAMPLE_INTERVAL_MS // 100):
sleep_ms(100)

raw_x, raw_y, raw_z = mag.read_one_shot()
temp_c = mag.temperature()

x_ut = raw_x * MAG_LSB_TO_UT
y_ut = raw_y * MAG_LSB_TO_UT
z_ut = raw_z * MAG_LSB_TO_UT
magnitude_ut = sqrt(x_ut * x_ut + y_ut * y_ut + z_ut * z_ut)

gc.collect()
free_mem = gc.mem_free()

print(
"One-shot read: X={:.2f} uT Y={:.2f} uT Z={:.2f} uT |B|={:.2f} uT Temp={:.2f} C Free mem={} bytes".format(
x_ut, y_ut, z_ut, magnitude_ut, temp_c, free_mem
)
)
Loading
Loading