ESP32 - Piezo Buzzer
This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://esp32io.com/tutorials/esp32-piezo-buzzer
This build shows how to connect a piezo buzzer to an ESP32 and play a short melody with it. A piezo buzzer turns an electrical signal into sound, and depending on the type you use, it can give a simple beep for a keypad indicator or act as a loud warning signal. This guide covers wiring a basic buzzer or a buzzer module to the ESP32 and running code that plays a sequence of notes.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Narrow
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- 30-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- ESP32 Uno-form board
- ESP32 S3 Uno-form board
- USB Cable Type-A to Type-C (for USB-A PC)
- USB Cable Type-C to Type-C (for USB-C PC)
- 3-24V Active Piezo Buzzer
- Active Piezo Buzzer Module
- Passive Piezo Buzzer Module
- Breadboard
- Jumper Wires
- DC Power Jack
- Screw Terminal Expansion Board for ESP32
- Breakout Expansion Board for ESP32
- Power Splitter for ESP32
- DIYables ESP32 Starter Kit (ESP32 included)
- DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
- DIYables Sensor Kit (18 sensors/displays)
Wiring
A basic piezo buzzer has two pins. The positive pin connects to the ESP32 pin that generates the control signal, either directly or through a relay if you are driving a high-voltage buzzer with an external source. The negative pin goes to GND.
A buzzer module instead has three pins: GND goes to the ESP32 GND, VCC goes to 5V or 3.3V, and the I/O pin connects to an ESP32 pin that sends the PWM control signal, same as GPIO18 used in the code below.
How It Works
A 3V-24V active buzzer can work either as a low-voltage active buzzer when connected directly to an ESP32 pin, producing a standard beep suitable for things like keypad feedback, or as a high-voltage buzzer through a relay for a loud warning sound. The ESP32 drives the buzzer pin with a control signal, and varying the frequency and timing of that signal is what produces the different notes you hear.
Code
The sketch uses the tone() and noTone() functions to play a melody on GPIO18. Note pitches are stored in the melody array and their durations in the noteDurations array, with the pitch names coming from a separate pitches.h file you create as a new tab in the Arduino IDE. In setup(), the code loops through each note, calculates its duration, plays it with tone(), waits, then stops it with noTone() before moving to the next note. To play a different song, such as Jingle Bells, you only need to change the values in the melody and noteDurations arrays.
esp32-piezo-buzzer.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://esp32io.com/tutorials/esp32-piezo-buzzer