🛠 Mesurer le niveau sonore avec le micro MEMS
Objectives
Use the Knowles MEMS microphone on the V2 (internal pins MIC_IN P0.05 and RUN_MIC P0.20, with activity LED) to read the sound level and trigger reactions based on a threshold. MicroPython scale: 0 to 255.
Hardware
- 1 micro:bit V2 board (the microphone is absent on the V1)
- 1 micro-USB cable for flashing
- Test sound source: clapping, whistle, noise generator app
Complete code
from microbit import *
# Seuil LOUD sur l'échelle 0-255
microphone.set_threshold(SoundEvent.LOUD, 150)
barre = [Image("00000:00000:00000:00000:11111"),
Image("00000:00000:00000:11111:11111"),
Image("00000:00000:11111:11111:11111"),
Image("00000:11111:11111:11111:11111"),
Image("11111:11111:11111:11111:11111")]
while True:
niveau = microphone.current_volume # 0..255
idx = min(4, niveau // 52)
display.show(barre[idx])
if microphone.was_event(SoundEvent.LOUD):
display.show(Image.SURPRISED)
sleep(400)
if button_a.was_pressed: # calibrer le seuil
seuil = microphone.current_volume + 30
microphone.set_threshold(SoundEvent.LOUD, seuil)
display.scroll(str(seuil))
sleep(50)
current_volume provides the instantaneous level; set_threshold + was_event avoid continuous polling for "clap" events. The activity LED near the microphone lights up as soon as the microphone is active.
Expected verification
The LED bar rises progressively with noise, the board displays a "surprised face" on each clap, and pressing A raises the threshold above the ambient level measured at that moment.
Common errors
- Threshold set too low: everything triggers LOUD constantly; too high: nothing triggers anymore.
- Expecting the same behavior on V1:
microphonedoes not exist, AttributeError. - Confusing
current_volume(instantaneous) with the threshold event (one-off, cleared after reading). - Covering the microphone with your fingers during measurement: the case hole is small, causing the level to drop.
Other tutorials for this board
Code examples for this board
coeur.pyMicroPythonboutons.pyMicroPythonpodometre.pyMicroPythonlumiere.pyMicroPythonmusique.pyMicroPythonradio_ping.pyMicroPython