Raspberry Pi - Ultrasonic Sensor - Piezo Buzzer

This tutorial instructs you how to use Raspberry Pi and ultrasonic sensor to control piezo buzzer. In detail:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Ultrasonic Sensor
1×Piezo Buzzer
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
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. We appreciate your support.

Overview of Piezo Buzzer and Ultrasonic Sensor

If you are unfamiliar with piezo buzzer and ultrasonic sensor (including pinout, how it works, and how to program), the following tutorials can provide you with more information:

Wiring Diagram

The wiring diagram between Raspberry Pi and Ultrasonic Sensor Piezo Buzzer

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code - Simple Sound

In this section, we'll program Raspberry Pi to make a piezo buzzer to generate a simple sound whenever the distance measured by ultrasonic sensor is below a threshold.

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 ultrasonic_sensor_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-ultrasonic-sensor-piezo-buzzer import RPi.GPIO as GPIO import time # GPIO pin numbers for the ultrasonic sensor TRIG_PIN = 14 ECHO_PIN = 15 # GPIO pin number for the piezo buzzer BUZZER_PIN = 16 # Threshold distance in centimeters THRESHOLD_DISTANCE_CM = 20 def get_distance(): GPIO.output(TRIG_PIN, GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW) while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time() while GPIO.input(ECHO_PIN) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start speed_of_sound = 34300 # Speed of sound in cm/s distance = (pulse_duration * speed_of_sound) / 2 return distance GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) GPIO.setup(BUZZER_PIN, GPIO.OUT) GPIO.output(TRIG_PIN, GPIO.LOW) GPIO.output(BUZZER_PIN, GPIO.LOW) try: while True: distance = get_distance() print(f"Distance: {distance:.2f} cm") if distance < THRESHOLD_DISTANCE_CM: GPIO.output(BUZZER_PIN, GPIO.HIGH) # Turn the buzzer on else: GPIO.output(BUZZER_PIN, GPIO.LOW) # Turn the buzzer off except KeyboardInterrupt: GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 ultrasonic_sensor_buzzer.py
  • Wave your hand in front of the sensor.
  • Listen to the sound of the piezo buzzer.

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

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Raspberry Pi plays the melody of the song

In this section, we'll program Raspberry Pi to trigger a piezo buzzer to play the song "Jingle Bells" when the distance is below a threshold.

Detailed Instructions

  • Create a Python script file ultrasonic_sensor_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-ultrasonic-sensor-piezo-buzzer import RPi.GPIO as GPIO import time # GPIO pin numbers for the ultrasonic sensor TRIG_PIN = 14 ECHO_PIN = 15 # GPIO pin number for the piezo buzzer BUZZER_PIN = 16 # Threshold distance in centimeters THRESHOLD_DISTANCE_CM = 20 # 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) def play_jingle_bells(): for i in range(len(melody)): 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_tone(BUZZER_PIN, note_freq, note_duration) time.sleep(pause_duration / 1000.0) GPIO.output(BUZZER_PIN, GPIO.LOW) def get_distance(): GPIO.output(TRIG_PIN, GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW) while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time() while GPIO.input(ECHO_PIN) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start speed_of_sound = 34300 # Speed of sound in cm/s distance = (pulse_duration * speed_of_sound) / 2 return distance GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) GPIO.setup(BUZZER_PIN, GPIO.OUT) GPIO.output(TRIG_PIN, GPIO.LOW) GPIO.output(BUZZER_PIN, GPIO.LOW) try: while True: distance = get_distance() print(f"Distance: {distance:.2f} cm") if distance < THRESHOLD_DISTANCE_CM: play_jingle_bells() except KeyboardInterrupt: GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 ultrasonic_sensor_buzzer_Jingle_Bells.py
  • Move your hand in front of the sensor.
  • Hear the tune played by the piezo buzzer.

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Video Tutorial