🛠 Boussole numérique avec le magnétomètre
Objectives
Turn the micro:bit V2 into a compass using the magnetometer of the combined sensor (LSM303 or FXOS8700CQ, on the internal I²C bus). You will learn how to read compass.heading, calibrate the sensor, and display a heading in degrees.
Hardware
- 1 micro:bit V2 board
- 1 micro-USB cable
- Keep metals, magnets, and Bluetooth speakers away from the measurement area
Complete code
from microbit import *
# Calibration : incliner la carte dans les 6 directions
# jusqu'à ce que la croix se referme (si pas déjà calibrée)
if not compass.calibration_level:
display.show("C")
while compass.calibration_level < 10:
sleep(100)
display.show(Image.YES)
while True:
cap = compass.heading # 0..359 degrés
if cap < 22.5 or cap >= 337.5:
bss = "N"
elif cap < 67.5:
bss = "NE"
elif cap < 112.5:
bss = "E"
elif cap < 157.5:
bss = "SE"
elif cap < 202.5:
bss = "S"
elif cap < 247.5:
bss = "SO"
elif cap < 292.5:
bss = "O"
else:
bss = "NO"
display.scroll(str(cap), delay=40)
display.show(bss)
sleep(500)
compass.heading returns the angle between the board's y-axis and magnetic north. The magnetometer shares the internal I²C (P19/P20) with the motion sensor: it is strongly advised not to reuse these pins.
Expected verification
After calibration (figure-eight movements or along the 6 axes), the displayed heading follows your rotation: approximately 0° towards magnetic north, 90° towards east. The cardinal points N/NE/E… scroll correctly.
Common errors
- Do not calibrate near a metal desk or a speaker: the heading remains incorrect even after recalibration.
- Confusing magnetic north and geographic north (local declination of several degrees).
- The heading jumps from 350 to 10: this is normal near north, handle the wrap-around at 360 in your comparisons.
- Using P19/P20 for another I²C device: you will disconnect the onboard sensor.
Other tutorials for this board
Code examples for this board
coeur.pyMicroPythonboutons.pyMicroPythonpodometre.pyMicroPythonlumiere.pyMicroPythonmusique.pyMicroPythonradio_ping.pyMicroPython