🛠 Détecter l'inclinaison et les gestes avec l'accéléromètre
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
- 1 micro:bit V2 board
- 1 micro-USB cable for flashing, then autonomous operation on battery
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
- Comparing against thresholds that are too small (< 100): the display flickers constantly due to sensor noise.
- Confusing
was_gesture(instantaneous, clears history) withcurrent_gesture(continuous state). - Swapping the x/y axes depending on how you hold the board: test before writing the thresholds.
- Expecting the magnetometer here: the compass is handled at the intermediate level.
Other tutorials for this board
Code examples for this board
coeur.pyMicroPythonboutons.pyMicroPythonpodometre.pyMicroPythonlumiere.pyMicroPythonmusique.pyMicroPythonradio_ping.pyMicroPython