🛠 Piloter le haut-parleur : sons, mélodies et voix
Objectives
Use the V2 magnetic speaker (Jiangsu Huaneng MLT-8530, driven from P0.00 via the interface chip's DAC): built-in sound effects, melodies, tones, and understanding the audio path shared with the P0 pin.
Hardware
- 1 micro:bit V2 board (the V1 has no speaker)
- 1 micro-USB cable or standalone power supply
- Optional: external speaker on the P0 ring with alligator clips
Complete code
from microbit import *
import music
# Mélodie d'accueil + effets intégrés (audio.play)
music.play(music.NYAN)
audio.play(Sound.HYPERFUN)
notes = ["C:4", "E:4", "G:4", "C5:4", "G:4", "E:4"]
while True:
if button_a.was_pressed:
audio.play(Sound.HELLO) # effet intégré court
elif button_b.was_pressed:
music.play(notes) # mélodie personnalisée
elif accelerometer.was_gesture("shake"):
# Petit synthé : la note dépend de l'inclinaison x
freq = 200 + abs(accelerometer.get_x) // 4
music.pitch(freq, 150)
sleep(50)
music.play accepts predefined melodies (FUNERAL, NYAN, PYTHON…) and lists of "NOTE:duration". music.pitch(freq, ms) generates a continuous tone. Sound comes out of both the speaker AND the P0 ring: speaker.off mutes the internal speaker but not the P0 path.
Expected verification
At startup, the Nyan melody followed by the HYPERFUN effect can be heard. A plays "hello", B replays the six-note melody, shaking the board produces a sound whose pitch follows the tilt.
Common errors
- Using P0 as an analog/touch input in parallel: the audio signal interferes with the measurement (documented conflict).
- Expecting sound on V1: the speaker is exclusive to V2;
musicis silent on V1. - Malformed short melody: the format requires "C:4" (note:quarter-beats), not "C4".
- Maximum volume saturation: the magnetic speaker is limited, no amplifier — do not confuse with an externally PWM-driven buzzer.
Other tutorials for this board
Code examples for this board
coeur.pyMicroPythonboutons.pyMicroPythonpodometre.pyMicroPythonlumiere.pyMicroPythonmusique.pyMicroPythonradio_ping.pyMicroPython