Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
Lesson 32: Passive Buzzer Module
In this lesson, you’ll learn to play a melody on a passive buzzer module using an ESP32 Development Board. We’ll cover programming the ESP32 to control the buzzer and create musical notes with varying durations. This project is ideal for beginners in electronics and programming, providing hands-on experience in sound generation and basic digital sound principles. You’ll develop practical skills in utilizing the ESP32 board and integrating simple components like the passive buzzer.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
|---|---|---|
Universal Maker Sensor Kit |
94 |
You can also buy them separately from the links below.
Component Introduction |
Purchase Link |
|---|---|
ESP32 & Development Board (ESP32 Board) |
|
Wiring
Code
Code Analysis
Including the pitches library:
This library provides the frequency values for various musical notes, allowing you to use musical notation in your code.
#include "pitches.h"
Defining constants and arrays:
buzzerPinis the digital pin on the ESP32 Development Board where the buzzer is connected.melody[]is an array that stores the sequence of notes to be played.noteDurations[]is an array that stores the duration of each note in the melody.
const int buzzerPin = 25; int melody[] = { NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4 }; int noteDurations[] = { 4, 8, 8, 4, 4, 4, 4, 4 };
Playing the melody:
The
forloop iterates over each note in the melody.The
tone()function plays a note on the buzzer for a specific duration.A delay is added between notes to distinguish them.
The
noTone()function stops the sound.
void setup() { for (int thisNote = 0; thisNote < 8; thisNote++) { int noteDuration = 1000 / noteDurations[thisNote]; tone(buzzerPin, melody[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); noTone(buzzerPin); } }
Empty loop function:
Since the melody is played only once in the setup, there’s no code in the loop function.