Arduino Nano - Ultrasonic Sensor - Piezo Buzzer
This tutorial instructs you how to use Arduino Nano and ultrasonic sensor to control piezo buzzer. In detail:
- Arduino Nano produces a sound when the object is near the ultrasonic sensor.
- Arduino Nano ceases the sound when the object is far from the ultrasonic sensor.
- Arduino Nano plays a melody when the object is close to the ultrasonic sensor.
Hardware Preparation
Or you can buy the following kits:
| 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, operation, programming, etc.), the following tutorials can help:
Wiring Diagram

This image is created using Fritzing. Click to enlarge image
The diagram below shows the same connections without a breadboard:

This image is created using Fritzing. Click to enlarge image
See The best way to supply power to the Arduino Nano and other components.
Arduino Nano Code - Simple Sound
Detailed Instructions
- Plug a USB cable into the Arduino Nano and your PC.
- Launch the Arduino IDE, choose the correct board and port.
- Paste the code into the IDE and open it.
- Click the Upload button to transfer the code to the Arduino Nano.
- Wave your hand in front of the sensor.
- Listen for 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 in the Arduino IDE to compile and upload the code to the Arduino Nano.
- Move your hand in front of the sensor.
- Hear the music coming from the piezo buzzer.
- This code is for learning purposes only. Ultrasonic sensors are very sensitive to noise, so if you plan to use one in practice, noise should be filtered for the ultrasonic sensor. See how to filter noise for ultrasonic sensor for more information.


Code Explanation
Check out the line-by-line explanation contained in the comments of the source code!
※ NOTE THAT: