Arduino Nano - Piezo Buzzer
This tutorial instructs you how to use Arduino Nano to control the piezo buzzer. In detail, we will learn :
- How a piezo buzzer works
- How to the piezo buzzer to an Arduino Nano board
- How to program the Arduino Nano to make piezo buzzer generate sound.
- How to program the Arduino Nano to make piezo buzzer play a melody of a song
|USB A to Mini-B USB cable
|(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
A Piezo Buzzer is used to produce sound, beeps, or even a tune.
Available in the market is a versatile 3V-24V active buzzer that functions as both a 3-5V active buzzer and a high-voltage buzzer (12V and beyond).
- When directly connected to an Arduino pin, the buzzer produces a standard sound, making it ideal for applications such as sound indicators, such as keypad sounds.
- Alternatively, when connected to a high voltage source through a relay, the buzzer emits a loud sound, making it suitable for warning signals.
The Piezo Buzzer Pinout
Piezo Buzzer typically has two pins:
- The Negative (-) pin should be connected to GND (0V)
- The Positive (+) pin receives the control signal from Arduino Nano (directly, or indirectly via relay)
How Piezo Buzzer Works
This image is created using Fritzing. Click to enlarge image
How To Program For Piezo Buzzer
Thanks to the Arduino library, it is simple to play a melody. We are not required to understand how to generate a square wave. All we have to do is use two functions: tone() and noTone() from the library.
Arduino Nano Code
- Connect an Arduino Nano to a PC using a USB cable.
- Open the Arduino IDE, select the appropriate board and port.
- 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 Arduino IDE to compile and upload the code to Arduino Nano.
- Listen to the song of the birds.
Modifying Arduino Nano Code
At present, we will be altering the code to perform the song "Jingle Bells".
We only require altering the values of two arrays: int melody and int noteDurations.
※ NOTE THAT:
The code above utilizes the delay() function. This causes other code to be blocked during playing melody. To prevent this, the ezBuzzer library can be used instead. This library is specifically designed for buzzer use and allows for beeping or playing melodies without blocking other code.
- Employ a Piezo Buzzer to play your favorite song.
- Utilize a motion sensor to create an alarm when someone approaches your valuable items. Refer to Arduino Nano - Motion Sensor for more information.