Buzzer Sounds with LEDC
Your ESP32 can already blink an LED and dim it with PWM. In this lesson you make it sing. You will learn the difference between the two kinds of buzzers, why sound is really just vibration at a certain speed, and how the ESP32's built-in LEDC hardware turns numbers into musical notes, sirens and alarm beeps.
The big idea
A passive buzzer is basically a tiny loudspeaker. It does not know how to make a sound on its own — it only vibrates when you push electricity into it back and forth very fast. If you switch the voltage on and off 440 times every second, the little metal disc inside pushes the air 440 times per second, and your ear hears the musical note A4 (the "A" an orchestra tunes to).
The number of on/off swings per second is called the frequency, measured in hertz (Hz). Change the frequency and you change the pitch (how high or low the note sounds). The ESP32 has a hardware timer peripheral called LEDC that can generate a perfectly steady on/off signal at any frequency you ask for — so making music is really just telling LEDC which frequency to play, and for how long.
What you will be able to do
- Tell an active buzzer from a passive one and pick the right one for the job.
- Explain how frequency creates pitch, and read a note-frequency table.
- Play a single tone with
ledcAttachandledcWriteTone. - Control loudness with the duty cycle and cleanly stop a sound.
- Play a whole melody from arrays of notes and durations, including rests and tempo.
- Build alarm patterns: a siren and beep codes.
- Drive a louder buzzer safely using a transistor.
- Troubleshoot silence and distorted sound.