Controlling a buzzer with an RPZ
We've done a lot with light, but what about sound? The RPZ can run a simple buzzer with ease.
Getting ready
All you will need here is a piezo buzzer, which is a commonly available electronic component.
How to do it...
The piezo buzzer circuit is about as simple as it gets. There are only two leads: one is assigned to a GPIO port, and the other to ground. We can use PWM to adjust the frequency.
The code is simple too. The following is the code to run a buzzer test from 0 to 1 MHz and back down. Enter the code and run it as
piezo.py
:#!/usr/bin/env python # Raspberry Pi Zero Cookbook # Chapter 6 - Piezo Buzzer Operation import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #Set up GPIO 21 as buzzer output GPIO.setup(21, GPIO.OUT) # No freq to start buzzer1 = GPIO.PWM(21,0.5) # Set Volume buzzer1.start(50) while True: try: print "up!" ...