🛠 Détecter l'inclinaison et les gestes avec l'accéléromètre

micro:bit V2 (BBC micro:bit v2) · debutant · Schéma : IMG-microbit-v2-debutant-3-microbit-v2-inclinaison-accelerometre.svg — micro:bit V2 inclinée avec flèches de mouvement, icône secouer et flèches haut/bas/gauche/droite autour de la carte

Objectives

Use the onboard combined accelerometer + magnetometer sensor (ST LSM303, or NXP FXOS8700CQ depending on the manufacturing batch) to read tilt (x, y, z in milli-g) and recognize official gestures: shake, tilt up/down/left/right, face up/down, freefall.

Hardware

Complete code

from microbit import *

while True:
    # Inclinaison continue : flèches directionnelles
    if accelerometer.get_y < -300:      # penché vers le haut
        display.show(Image.ARROW_N)
    elif accelerometer.get_y > 300:     # penché vers le bas
        display.show(Image.ARROW_S)
    elif accelerometer.get_x < -300:    # penché à gauche
        display.show(Image.ARROW_W)
    elif accelerometer.get_x > 300:     # penché à droite
        display.show(Image.ARROW_E)
    # Gestes ponctuels
    elif accelerometer.was_gesture('shake'):
        display.show(Image.YES)
        sleep(400)
    elif accelerometer.is_ready:
        display.show(Image.HAPPY)
    sleep(50)

get_x/get_y/get_z return acceleration in milli-g (at rest, the downward-facing axis indicates approximately 1000). The ±300 thresholds prevent false triggers.

Expected verification

Tilt the board: an arrow points in the direction of movement. Shake it: the "yes" checkmark appears. Laid flat: a smiley face. Everything works when unplugged.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials