Raspberry Pi - Door Sensor - Piezo Buzzer
This tutorial instructs you how to use Raspberry Pi and door sensor to trigger piezo buzzer. In detail::
- Raspberry Pi turns on piezo buzzer to produce a sound when detecting the door open via door sensor.
- Raspberry Pi turns off piezo buzzer to cease the sound when detecting the door closed via door sensor.
- Raspberry Pi plays the song "Jingle Bells" when detecting the door open via door 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 Door Sensor
If you are unfamiliar with piezo buzzer and door sensor, including their pinout, functionality, and programming, the following tutorials can help:
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
Raspberry Pi Code - Simple Sound
In this section, we will learn how to use a piezo buzzer to produce a simple sound when the door is open using Raspberry Pi.
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 door_sensor_buzzer.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
- Bring the magnet close to the reed switch, then move it away.
- 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 will make the Raspberry Pi trigger the piezo buzzer to play the song "Jingle Bells" when the door is open.
Detailed Instructions
- Create a Python script file door_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 the magnet far from the reed switch of door sensor to simulate the door open.
- Hear the tune of the piezo buzzer.
Code Explanation
Take a look at the line-by-line explanation in the comments section of the source code!