Buzzer and Music with Pico 2 W

Passive buzzers allow you to create musical tones and melodies by generating PWM signals at different frequencies. By controlling the PWM frequency, you can play musical notes and even entire songs!

Active vs Passive Buzzers

There are two types of buzzers:

Musical Notes and Frequencies

Each musical note corresponds to a specific frequency. For example:

C4 (Middle C) = 262 Hz

D4 = 294 Hz

E4 = 330 Hz

F4 = 349 Hz

G4 = 392 Hz

A4 = 440 Hz

B4 = 494 Hz

Hardware Setup

Connect a passive buzzer to a PWM-capable GPIO pin:

Buzzer + → GPIO 15 (or any PWM pin)

Buzzer - → GND

Tip

Pico 2 W Note

Use any free PWM-capable GPIO except 23-25, 29 (reserved for wireless). GPIO 15 is a good choice for buzzer projects.

Playing a Single Note

rust
use embassy_rp::pwm::{Config as PwmConfig, Pwm};

// Setup PWM for buzzer
let mut pwm_config = PwmConfig::default();
pwm_config.top = 1000; // Will be adjusted per note
pwm_config.compare_a = 500; // 50% duty cycle

let mut pwm = Pwm::new_output_a(
    p.PWM_SLICE7, // GPIO 15 is on slice 7
    p.PIN_15,
    pwm_config
);

// Play middle C (262 Hz)
fn play_note(pwm: &mut Pwm, frequency: u32) {
    let top = (125_000_000 / frequency) as u16;
    pwm.set_top(top);
    pwm.set_compare_a(top / 2); // 50% duty
}

play_note(&mut pwm, 262); // C4
Timer::after_millis(500).await;
pwm.set_compare_a(0); // Stop sound

Playing a Melody

rust
// Define notes as (frequency, duration_ms)
const MELODY: &[(u32, u32)] = &[
    (262, 400), // C4
    (294, 400), // D4
    (330, 400), // E4
    (349, 400), // F4
    (392, 400), // G4
    (440, 400), // A4
    (494, 400), // B4
    (523, 800), // C5
];

// Play the melody
for &(freq, duration) in MELODY {
    play_note(&mut pwm, freq);
    Timer::after_millis(duration).await;
    pwm.set_compare_a(0); // Small gap between notes
    Timer::after_millis(50).await;
}

Popular Melodies

You can program famous melodies like "Twinkle Twinkle Little Star", "Happy Birthday", or "Super Mario Theme" by defining the note frequencies and durations.

Advanced Features

Practical Applications