Raspberry PI Buzzer Control Code

What is buzzer?

A buzzer is an audio signaling device which is mostly used as an alarming device or a user input feedback in devices. Buzzers can make beeping sounds in different frequencies and durations. Typical applications including siren, alarm devices, fire alarm. It is widely used in household appliances, electronic toys game machine and many more industries. The big advantage of a buzzer is the wide spectrum of volume. For example it is used in high volume as an alarm system and on low volume as a children’s toy. By appending sounds you can generate music with it. Sounds are generated in different frequencies by sending PWM signals from the microcontroller. PWM is a square shaped signal. The frequency of the PWM is determined by the number of squares generated in a second. You can learn more about PWM on the internet. The duration of the PWM signal determines the duration of the beep.

raspberry pi buzzer
Figure 1 - Raspberry PI Buzzer

Required hardware

  • Raspberry PI
  • Buzzer
  • Resistor 100Ω

Source code to install on controller


#!/usr/bin/python
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)

p = GPIO.PWM(17, 100)
p.start(0)
try:
    while 1:
       	for dc in range(0, 101, 5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)
        for dc in range(100, -1, -5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)

except KeyboardInterrupt:
    pass
p.stop()
GPIO.cleanup()

More information