Arduino Nano - Motion Sensor - Piezo Buzzer
This tutorial instructs you how to use Arduino Nano and motion sensor to control piezo buzzer to generate sound when detecting the movement of human or animal. In detail:
- Arduino Nano triggers piezo buzzer to generate sound when motion is detected
- Arduino Nano turns off piezo buzzer to stop the sound when motion is not detected
- Arduino Nano triggers piezo buzzer to play a melody when motion is detected
This can be applied in an automation process that triggers actions upon detecting human presence.
|USB A to Mini-B USB cable
|HC-SR501 Motion Sensor
|(Optional) 9V Power Adapter for Arduino Nano
|(Recommended) Screw Terminal Adapter for Arduino Nano
Or you can buy the following sensor kit:
|DIYables Sensor Kit 30 types, 69 units
Overview of Piezo Buzzer and Motion Sensor
If you are unfamiliar with piezo buzzer and motion sensor (including pinout, operation, and programming), the following tutorials can help:
This image is created using Fritzing. Click to enlarge image
|Time Delay Adjuster
|Screw it in anti-clockwise direction fully.
|Detection Range Adjuster
|Screw it in clockwise direction fully.
|Repeat Trigger Selector
|Put jumper as shown on the image.
Arduino Nano Code - Simple Sound
- Plug the USB cable into both the Arduino Nano and the PC.
- Launch the Arduino IDE, select the correct board and port.
- Paste the code into the IDE and open it.
- Click the Upload button in the IDE to transfer the code to the Arduino Nano.
- Wave your hand in front of the sensor.
- Listen to the sound of the piezo buzzer.
Check out the line-by-line explanation contained in the comments of the source code!
Arduino Nano Code - Melody
- Copy the code and open it with the Arduino IDE.
- Create the pitches.h file On Arduino IDE by:
- Either click on the button just below the serial monitor icon and choose New Tab, or use Ctrl+Shift+N keys.
- Give file's name pitches.h and click OK button
- Copy the below code and paste it to the created pitches.h file.
- Click the Upload button on the Arduino IDE to compile and upload the code to the Arduino Nano.
- Move your hand in front of the sensor.
- Listen to the tune played by the piezo buzzer.
**Read the line-by-line explanation in comment lines of the source code!**. Check out the line-by-line description in the comments of the source code!
※ NOTE THAT:
The code above utilizes the delay() function. This has the effect of blocking other code during the playing of the melody. To prevent this from happening, the ezBuzzer library can be used instead. This library is designed to allow the buzzer to beep or play a melody without blocking other code.