ESP8266 - Piezo Buzzer
This tutorial instructs you how to use ESP8266 to control the piezo buzzer. In detail, we will learn :
- How a piezo buzzer works
- How to the piezo buzzer to an ESP8266 board
- How to program the ESP8266 to make piezo buzzer generate sound.
- How to program the ESP8266 to make piezo buzzer play a melody of a song
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
A Piezo Buzzer is used to produce sound, beeps, or even a melody of a tune.
Available in the market is a 3V-24V active buzzer that functions both as a 3-5V active buzzer and a high-voltage buzzer (12V and beyond). When directly connected to an Arduino pin, this buzzer produces a standard sound, making it suitable for applications such as sound indicators (e.g., keypad sounds). Alternatively, when connected to a high voltage source through a relay, it generates a loud sound, making it ideal for warning signals.
The Piezo Buzzer Pinout
Piezo Buzzer usually has two pins:
- The Negative (-) pin needs to be connected to GND (0V)
- The Positive (+) pin receives the control signal from ESP8266 (directly, or indirectly via relay).
How Piezo Buzzer Works
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
See more in ESP8266's pinout and how to supply power to the ESP8266 and other components.
ESP8266 Code
Detailed Instructions
To get started with ESP8266 on Arduino IDE, follow these steps:
- Check out the how to setup environment for ESP8266 on Arduino IDE tutorial if this is your first time using ESP8266.
- Wire the components as shown in the diagram.
- Connect the ESP8266 board to your computer using a USB cable.
- Open Arduino IDE on your computer.
- Choose the correct ESP8266 board, such as (e.g. NodeMCU 1.0 (ESP-12E Module)), and its respective COM 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.
- Copy the code above and open it with the Arduino IDE.
- Click the Upload button on the Arduino IDE to compile and upload the code to the ESP8266 board.
- Listen to the melody.
Modifying ESP8266 Code
Now, we are going to modify the code in order to play "Jingle Bells" song.
We must alter the values of two arrays: int melody[] and int noteDurations[].
Video Tutorial
Challenge Yourself
- Utilize a Piezo Buzzer to play your favorite song.
- Automatically set off an alarm when someone approaches your valuable items. See: ESP8266 - Motion Sensor for more information.