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.
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 Motion Sensor
If you are unfamiliar with piezo buzzer and motion sensor (including pinout, operation, and programming), the following tutorials can help:
Wiring Diagram

This image is created using Fritzing. Click to enlarge image
See The best way to supply power to the Arduino Nano and other components.
Initial Setting
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
Detailed Instructions
- 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.
Code Explanation
Check out the line-by-line explanation contained in the comments of the source code!
Arduino Nano Code - Melody
Detailed Instructions
- 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.


Code Explanation
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.