0
0
Raspberry Piprogramming~5 mins

Buzzer and TonalBuzzer in Raspberry Pi

Choose your learning style9 modes available
Introduction

A buzzer is a small device that makes sound when powered. A TonalBuzzer lets you play different tones or notes, like a simple music player.

To make a beep sound when a button is pressed.
To alert someone with a sound in a project, like a timer or alarm.
To play simple melodies or tones for fun or feedback.
To signal different events with different sounds.
To learn how to control hardware sounds with code.
Syntax
Raspberry Pi
from gpiozero import Buzzer, TonalBuzzer

buzzer = Buzzer(pin_number)
buzzer.on()  # turns buzzer on
buzzer.off() # turns buzzer off

# For TonalBuzzer
from gpiozero import TonalBuzzer

tonal_buzzer = TonalBuzzer(pin_number)
tonal_buzzer.play(frequency)  # plays a tone

# To stop
tonal_buzzer.stop()

Replace pin_number with the GPIO pin connected to the buzzer.

TonalBuzzer can play different frequencies (tones), while Buzzer just turns on/off.

Examples
This turns the buzzer on for 1 second, then off.
Raspberry Pi
from gpiozero import Buzzer
import time

buzzer = Buzzer(17)
buzzer.on()
time.sleep(1)
buzzer.off()
This plays a 440 Hz tone (A4 note) for 2 seconds, then stops.
Raspberry Pi
from gpiozero import TonalBuzzer
import time

buzzer = TonalBuzzer(18)
buzzer.play(440)  # plays A4 note
time.sleep(2)
buzzer.stop()
This plays a simple scale of notes, each for half a second.
Raspberry Pi
from gpiozero import TonalBuzzer
import time

buzzer = TonalBuzzer(18)
notes = [262, 294, 330, 349, 392]  # C4, D4, E4, F4, G4
for note in notes:
    buzzer.play(note)
    time.sleep(0.5)
buzzer.stop()
Sample Program

This program plays five musical notes one after another on the buzzer connected to GPIO pin 18.

Raspberry Pi
from gpiozero import TonalBuzzer
import time

buzzer = TonalBuzzer(18)

# Play a short melody
melody = [440, 494, 523, 587, 659]  # A4, B4, C5, D5, E5
for tone in melody:
    buzzer.play(tone)
    time.sleep(0.4)
buzzer.stop()
OutputSuccess
Important Notes

Make sure your buzzer supports tones if you use TonalBuzzer.

Use a resistor if needed to protect your Raspberry Pi and buzzer.

GPIO pins must be set correctly to avoid damage.

Summary

Buzzer makes simple on/off sounds.

TonalBuzzer plays different tones by frequency.

Use these to add sound feedback or simple music to your Raspberry Pi projects.