🛠 Jouer une mélodie avec un buzzer passif et le PWM

RP2040 (generic board / chip) · debutant · Schéma : IMG-rp2040-generic-debutant-3-rp2040-buzzer-pwm-melodie.svg — buzzer passif relié à GP8 et GND d'une carte RP2040 générique, forme d'onde carrée 440 Hz annotée, portée avec les notes

Objectives

Build a small synthesizer: a passive buzzer is nothing more than a membrane that we vibrate with a square signal. The RP2040 provides the ideal clock: 16 PWM channels (8 slices × 2 channels) driven by the 125 MHz clock (RP2040 datasheet). You will calculate the period and duty cycle to play accurate notes, then a complete melody.

Hardware

Complete code

# melodie.py — GP8, PWM 50 % de rapport cyclique, gamme ~31 Hz..62 kHz
from machine import Pin, PWM
import time

buz = PWM(Pin(8))
buz.duty_u16(32768)          # 50 % = son le plus fort (16 bits)

NOTE = {                       # fréquences tempérées (LA4 = 440 Hz)
    'C4': 262, 'D4': 294, 'E4': 330, 'F4': 349, 'G4': 392,
    'A4': 440, 'B4': 494, 'C5': 523, ' ': 0,
}

def note(nom, duree_ms):
    f = NOTE.get(nom, 0)
    if f:
        buz.freq(f)
        buz.duty_u16(32768)
    else:                      # silence
        buz.duty_u16(0)
    time.sleep_ms(duree_ms)
    buz.duty_u16(0)
    time.sleep_ms(20)          # petite articulation entre notes

# « Au clair de la lune » (début)
partition = [('C4',400),('C4',400),('C4',400),('D4',400),
             ('E4',800),('D4',800),('C4',1200),(' ',400)]
while True:
    for n, d in partition:
        note(n, d)
    time.sleep_ms(800)

Expected verification

The melody sounds in tune (compare A4 to the tuning fork on your phone). By changing buz.freq(440) live in the REPL, the sound pitch goes up/down continuously: you control the pitch. A lower duty_u16 (e.g., 8000) lowers the volume without changing the note — PWM also serves as amplitude.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials