Raspberry Pi - Piezo Buzzer

This tutorial instructs you how to use Raspberry Pi to control the piezo buzzer. In detail, we will learn :

Hardware Preparation

1×Raspberry Pi 4 Model B
1×3-24V Active Piezo Buzzer
1×Active Piezo Buzzer Module
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) Power Adapter for Raspberry Pi 4B
1×(Optional) Plastic Case for Raspberry Pi 4B

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Piezo Buzzer

A Piezo Buzzer is used to produce sound, beeps, or even a melody from a song.

Available in the market is a 3V-24V active buzzer that serves dual purposes: functioning both as a 3-5V active buzzer and a high-voltage buzzer (12V and beyond).

  • Connecting this buzzer directly to an Arduino pin produces a standard sound, making it ideal for applications such as sound indicators, like keypad sounds.
  • On the other hand, when connected to a high voltage through a relay, it emits a loud sound, making it suitable for warning signals.

The Piezo Buzzer Pinout

Piezo Buzzer generally has two pins:

  • The Negative (-) pin should be connected to GND (0V)
  • The Positive (+) pin receives the control signal from Raspberry Pi (directly, or indirectly via relay)
Piezo Buzzer pinout

How Piezo Buzzer Works

See How Piezo Buzzer works

Wiring Diagram

The wiring diagram between Raspberry Pi and Piezo Buzzer

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file buzzer.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-piezo-buzzer """ import RPi.GPIO as GPIO import time # Set the GPIO mode (BCM or BOARD) GPIO.setmode(GPIO.BCM) # Define the GPIO pin number to which the buzzer is connected BUZZER_PIN = 18 # Set up the GPIO pin as an output GPIO.setup(BUZZER_PIN, GPIO.OUT) # Constants for note names and their corresponding frequencies C4 = 261 G3 = 196 A3 = 220 B3 = 247 # Dictionary to map numeric values to note names note_names = { C4: "C4", G3: "G3", A3: "A3", B3: "B3", } # List of notes in the melody melody = [ C4, G3, G3, A3, G3, 0, B3, C4 ] # List of note durations (in milliseconds) note_durations = [ 400, 200, 200, 400, 400, 400, 400, 400 ] # Pause duration between notes (in milliseconds) pause_duration = 300 def play_tone(pin, frequency, duration): # Calculate the period based on the frequency period = 1.0 / frequency # Calculate the time for half of the period half_period = period / 2.0 # Calculate the number of cycles for the given duration cycles = int(duration / period) for _ in range(cycles): # Set the GPIO pin to HIGH GPIO.output(pin, GPIO.HIGH) # Wait for half of the period time.sleep(half_period) # Set the GPIO pin to LOW GPIO.output(pin, GPIO.LOW) # Wait for the other half of the period time.sleep(half_period) try: while True: # Infinite loop # Iterate over the notes of the melody for i in range(len(melody)): # To calculate the note duration, take the value from the list and divide it by 1,000 (convert to seconds) note_duration = note_durations[i] / 1000.0 note_freq = melody[i] note_name = note_names.get(note_freq, "Pause") print(f"Playing {note_name} (Frequency: {note_freq} Hz) for {note_duration} seconds") # Play the tone play_tone(BUZZER_PIN, note_freq, note_duration) # Add a brief pause between notes (optional) time.sleep(pause_duration / 1000.0) # Stop the tone playing (optional) GPIO.output(BUZZER_PIN, GPIO.LOW) # Allow the user to stop the buzzer by pressing Ctrl+C except KeyboardInterrupt: GPIO.output(BUZZER_PIN, GPIO.LOW) GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 buzzer.py
  • Listen to the melody of a song emmited by the piezo buzzer.

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

Modifying Raspberry Pi Code

Now, we will be altering the code to play the "Jingle Bells" song.

  • Create a Python script file buzzer_Jingle_Bells.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-piezo-buzzer """ import RPi.GPIO as GPIO import time # Set the GPIO mode (BCM or BOARD) GPIO.setmode(GPIO.BCM) # Define the GPIO pin number to which the buzzer is connected BUZZER_PIN = 18 # Set up the GPIO pin as an output GPIO.setup(BUZZER_PIN, GPIO.OUT) # Constants for note names and their corresponding frequencies C4 = 261 D4 = 293 E4 = 329 F4 = 349 G4 = 392 A4 = 440 B4 = 493 # Dictionary to map numeric values to note names note_names = { C4: "C4", D4: "D4", E4: "E4", F4: "F4", G4: "G4", A4: "A4", B4: "B4", } # List of notes in the "Jingle Bells" melody melody = [ E4, E4, E4, E4, E4, E4, E4, G4, C4, D4, E4, F4, F4, F4, F4, F4, E4, E4, E4, E4, E4, D4, D4, E4, D4, G4 ] # List of note durations (in milliseconds) note_durations = [ 200, 200, 400, 200, 200, 400, 200, 200, 200, 200, 200, 200, 200, 400, 200, 200, 200, 200, 200, 200, 200, 200, 200, 400, 200, 200 ] # Pause duration between notes (in milliseconds) pause_duration = 300 def play_tone(pin, frequency, duration): # Calculate the period based on the frequency period = 1.0 / frequency # Calculate the time for half of the period half_period = period / 2.0 # Calculate the number of cycles for the given duration cycles = int(duration / period) for _ in range(cycles): # Set the GPIO pin to HIGH GPIO.output(pin, GPIO.HIGH) # Wait for half of the period time.sleep(half_period) # Set the GPIO pin to LOW GPIO.output(pin, GPIO.LOW) # Wait for the other half of the period time.sleep(half_period) try: while True: # Infinite loop # Iterate over the notes of the melody for i in range(len(melody)): # To calculate the note duration, take the value from the list and divide it by 1,000 (convert to seconds) note_duration = note_durations[i] / 1000.0 note_freq = melody[i] note_name = note_names.get(note_freq, "Pause") print(f"Playing {note_name} (Frequency: {note_freq} Hz) for {note_duration} seconds") # Play the tone play_tone(BUZZER_PIN, note_freq, note_duration) # Add a brief pause between notes (optional) time.sleep(pause_duration / 1000.0) # Stop the tone playing (optional) GPIO.output(BUZZER_PIN, GPIO.LOW) # Allow the user to stop the buzzer by pressing Ctrl+C except KeyboardInterrupt: GPIO.output(BUZZER_PIN, GPIO.LOW) GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 buzzer_Jingle_Bells.py
  • You can compare this code with the previous code to see the differences

With this modification, the code will now play the melody of "Jingle Bells" using the piezo buzzer attached to the Raspberry Pi. Enjoy the festive tune!

Video Tutorial

Challenge Yourself

  • Employ a Piezo Buzzer to play your favorite song.
  • Utilize a Raspberry Pi Motion Sensor to automatically sound an alarm when someone is near your valuable items. Refer to Raspberry Pi - Motion Sensor for more information.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!