musique.py
The V2 carries a speaker: the music library plays melodies and notes (with octave) on the internal speaker or the amplified pin0. Buttons and tilt gestures become game keys.
Required hardware
A BBC micro:bit V2 (nRF52833, 5×5 LED matrix, A/B buttons, accelerometer + compass, microphone and speaker) powered over USB or a battery pack. Optional: 8 Ω mini speaker or buzzer on pin0 and GND for external sound.
Wiring
Speaker between pin0 (amplified output) and GND. The internal speaker needs nothing.
How it works
music.play takes a list of notes like LA:200 (an A held 200 ms); wait blocks until the end. Tilt up/down gestures fire a note, like a tilt xylophone.
Running it
Open python.microbit.org, paste the MicroPython program and send it to the board (the micro:bit shows up as a MICROBIT drive). Press reset to restart.
Variants
Compose a full tune with music.play(list, loop=True), or play a scale driven by the servo script potentiometer.
musique.py
# Melodies et notes sur le haut-parleur de la micro:bit V2.
from microbit import *
import music
# 'dea' = theme simplifie ; la V2 possede un haut-parleur annexe.
melodie = ['C4:100', 'E4:100', 'G4:100', 'C5:200',
'G4:100', 'E4:100', 'C4:300']
display.show(Image.MUSIC)
sleep(600)
music.play(melodie, pin=pin0, wait=True, loop=False)
# Joue aussi sur le haut-parleur integre (pin par defaut).
while True:
if button_a.was_pressed():
music.play(music.DING)
if button_b.was_pressed():
music.play(music.GHOST)
# Incliner vers le haut : do ; vers le bas : sol.
if accelerometer.is_gesture('tilt up'):
music.play(['C4'], pin=pin0)
if accelerometer.is_gesture('tilt down'):
music.play(['G4'], pin=pin0)
sleep(20)
# Pin0 = sortie amplifiee du bord de carte : buzzer ou mini-HP.
# reset() arrete toute musique en cours.