boussole.py
The V2 magnetometer gives the heading to north (0-359°); the script shows an arrow per 45° band and the heading on console. The figure-eight calibration triggers automatically on first run.
Required hardware
A BBC micro:bit V2 (nRF52833, 5×5 LED matrix, A/B buttons, accelerometer + compass, microphone and speaker) powered over USB or a battery pack. No part: integrated LSM303 compass.
Wiring
No wiring. Move magnets, speakers and metal desks away — they skew the reading.
How it works
compass.heading() returns the angle between the USB edge and magnetic north; set_heading(0) re-zeroes it; the FLECHES table maps angle to a cardinal image.
Running it
Open python.microbit.org, paste the MicroPython program and send it to the board (the micro:bit shows up as a MICROBIT drive). Press reset to restart.
Variants
Turn it into a metal detector (heading standard deviation explodes), or combine with radio to remotely report a heading.
boussole.py
# Boussole : cap en degres + fleche, avec calibration au 1er lancer.
from microbit import *
FLECHES = [Image.ARROW_N, Image.ARROW_NE, Image.ARROW_E,
Image.ARROW_SE, Image.ARROW_S, Image.ARROW_SW,
Image.ARROW_W, Image.ARROW_NW]
# Calibration : incliner la carte en huit jusqu'au coche.
if not compass.is_calibrated():
display.show(Image.TARGET)
compass.calibrate()
compass.set_heading(0) # reference actuelle = nord
dernier = -1
while True:
cap = int(compass.heading()) # 0..359 degres
if abs(cap - dernier) >= 15: # rafraichir si mouvement
dernier = cap
index = ((cap + 22) % 360) // 45
display.show(FLECHES[index])
print('cap = %d deg' % cap)
if button_a.was_pressed():
compass.clear_cache()
display.show(Image.ALL_CLOCKS)
sleep(100)
# Le magnetometre est sensible aux aimants et au metal du bureau.