🛠 Boussole numérique avec le magnétomètre

micro:bit V2 (BBC micro:bit v2) · intermediaire · Schéma : IMG-microbit-v2-intermediaire-1-microbit-v2-boussole-magnetometre.svg — micro:bit V2 à plat avec rose des vents au-dessus, aiguille pointant vers le N et chiffre de cap affiché sur la matrice LED

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials