🛠 Piloter le haut-parleur : sons, mélodies et voix

micro:bit V2 (BBC micro:bit v2) · avance · Schéma : IMG-microbit-v2-avance-2-microbit-v2-haut-parleur-musique.svg — micro:bit V2 avec haut-parleur magnétique en gros plan, notes de musique sortant de la carte et route audio vers la broche P0 indiquée

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials