Raspberry Pi - Ultrasonic Sensor - Piezo Buzzer
This tutorial instructs you how to use Raspberry Pi and ultrasonic sensor to control piezo buzzer. In detail:
- Raspberry Pi produces sound when the object is near the ultrasonic sensor.
- Raspberry Pi halts the sound when the object is away from the ultrasonic sensor.
- Raspberry Pi plays a melody when the object is close to the ultrasonic sensor.
Hardware Preparation
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Additionally, some of these links are for products from our own brand, DIYables.
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
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:
- Create a Python script file ultrasonic_sensor_buzzer.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
- 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:
- Save the file and run the Python script by executing the following command in the terminal:
- 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!