-
Notifications
You must be signed in to change notification settings - Fork 1
examples(lis2mdl): Replace test scripts with practical examples. #251
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
14 commits
Select commit
Hold shift + click to select a range
990efd9
fix(lis2mdl): Remove test from example
Charly-sketch ff59fa9
feat(lis2mdl): add basic read example
Charly-sketch 0eae2cc
feat(lis2mdl): add calibrate 2D example
Charly-sketch 2c4eeca
feat(lis2mdl): add door sensor example
Charly-sketch df5c10e
feat(lis2mdl): add field_map example
Charly-sketch 327ffa3
feat(lis2mdl): add low power one shot example
Charly-sketch 50be1c4
feat(lis2mdl): add metal detector example
Charly-sketch 62b227b
feat(lis2mdl): add fiel logger example
Charly-sketch 226e08d
feat(lis2mdl): add tilt compensation example
Charly-sketch db97a59
docs(lis2mdl): add example to readme
Charly-sketch cc499aa
fix(lis2mdl): Remove useless accel read in tilt compensated example
Charly-sketch f9509f8
fix(lis2mdl): correct tone timing in metal detector example
Charly-sketch b71150b
fix(lis2mdl): Use hardware PWM for metal detector buzzer tone.
nedseb 359ab9c
fix(lis2mdl): Use pyb to import timer in metal detector
Charly-sketch 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
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,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) |
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,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) |
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,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) |
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,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.") |
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,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) |
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,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 | ||
| ) | ||
| ) |
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.