Featured image of post [IoT] Raspberry Pi Pico Plays Music via Buzzer

[IoT] Raspberry Pi Pico Plays Music via Buzzer

Relax with a song played by Raspberry Pi Pico

Connecting a buzzer is relatively simple. You’ll need a buzzer module (I’m using an active/passive buzzer module).

The buzzer has only three pins. Here’s the wiring reference:

Raspberry Pi Buzzer Note
VUSB VCC 5V power (Pin 40)
GP22 I/O GPIO pin
GND GND Ground

Found an arrangement of “Iron Blood Loyal Heart” online:

package main

import (
	"machine"
	"time"

	"tinygo.org/x/drivers/buzzer"
)

type note struct {
	tone     float64
	duration float64
}

func main() {
	// Note that 22 here is the I/O pin
	bzrPin := machine.Pin(22)
	bzrPin.Configure(machine.PinConfig{Mode: machine.PinOutput})

	bzr := buzzer.New(bzrPin)

	song := []note{
		{buzzer.A4, 1.5},      // 6
		{buzzer.G4, 0.5},      // 5
		// ... (Full musical notes arrangement)
		{buzzer.A3, 3.0},      // .6
	}

	for _, val := range song {
		bzr.Tone(val.tone, val.duration)
		time.Sleep(10 * time.Millisecond)
	}
}

Compile and flash:

go mod tidy
tinygo flash -target=pico

Now enjoy the music!