2.4. Buzzer Beep

Short example demonstration video
In this example we will use a passive buzzer to play a melody. The buzzer functions like a small speaker, it requires AC audio signal to produce sound. To make it play different melodies and tones we simply change the frequency of the signal sent to it.
✅
At the end of this example you will learn:
- How to play sound/melody from a passive buzzer
- How to use PWM for different frequencies
ℹ️
Parts required:
- Soldered NULA Mini Board
- Breadboard
- 1 x Buzzer
- Some jumper wires

Required components
Putting the components together
- Place the buzzer in the breadboard, connect the positive pin to GPIO 5, and negative to GND.
- Positive pin should be labeled on top of the buzzer.

Components connected together
Code Example
Import necessary modules, PWM is used to control the tone output from the buzzer.
from machine import Pin, PWM
import time
Create a PWM object on pin 5.
buzzer = PWM(Pin(5))
Here we define some common notes along with their frequencies in Hz.
C4 = 262
D4 = 294
E4 = 330
F4 = 349
G4 = 392
A4 = 440
Out of those notes we defined, we can create a melody by putting them in a list. We also set duration to play each note.
melody = [C4, D4, E4, F4, G4, A4, G4, F4, E4, D4, C4]
duration = 200
Loop through the melody and play each note with a small pause in between. In the end disable the PWM output for the buzzer.
for note in melody:
buzzer.freq(note) # Set buzzer frequency based on the note
buzzer.duty(512) # 50% duty (sound on)
time.sleep_ms(duration) # Play note for defined duration
buzzer.duty(0) # 0% duty (sound off)
time.sleep_ms(150) # Short pause between notes
buzzer.deinit()