The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

140 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


Controlling a buzzer in Python
Controlling an active buzzer through the GPIO Zero library is almost identical to controlling an
LED, in that it has on and off states. You need a different, function, though: buzzer. Start a
new project in Thonny and save it as Buzzer, then type the following:

from gpiozero import Buzzer
from time import sleep

As with LEDs, GPIO Zero needs to know which pin your buzzer is connected to in order to
control it. Type the following:

buzzer = Buzzer( 15 )

From here, your program is almost identical to the one you wrote to control the LED; the only
difference (apart from a different GPIO pin number) is you’re using buzzer in place of led.
Type the following:

while True:
buzzer.on()
sleep( 1 )
buzzer.off()
sleep( 1 )

Click the Run button and your buzzer will begin to buzz: one second on, and one second off.
If you are using a passive buzzer rather than an active buzzer, you’ll only hear a brief click every
second instead of a continuous buzz: this is because a passive buzzer lacks an oscillator to
create the rapidly changing signal which makes the plates inside the buzzer vibrate.
Click the Stop button to exit the program, but make sure the buzzer isn’t making a sound
at the time otherwise it will continue to buzz until you run your program again!

CHALLENGE: A BETTER BUZZ
How could you change the program to make the buzzer
sound for a shorter time? Can you build a circuit so the
buzzer is controlled by a button?
Free download pdf