Lessons · Lesson A1 · Actuators and motors · 30 min
Sound, buzzers and speakers
Tell an active buzzer from a passive one, play notes and a short melody with tone(), and meet the DFPlayer Mini for MP3 files. About 30 minutes, with a piano you can press.
Air going back and forth
What reaches your ear is not a thing but a push: air squeezed, then released, over and over. That pressure wave is what the ear picks up as sound [3]. A sound is air going back and forth.
A buzzer makes that push on a small scale. A piezo buzzer holds a crystal that changes shape when a voltage is applied. The crystal presses on a thin disc, like a tiny speaker cone, and the disc makes the pressure wave. Change how fast the voltage goes back and forth, and you change the sound you hear [3].
In this lesson you will:
- tell the two kinds of buzzer apart,
- play a note of your choice, then a short melody,
- see what a DFPlayer Mini adds when you want real MP3 files.
Active or passive?
Two parts that look alike can behave very differently.
- An active buzzer has its own driver circuit inside, a piezo plus a circuit that makes it oscillate. You give it power and it beeps. Adafruit’s listing of one says it sings at 2 kHz and that you cannot change that frequency [1]. That makes it fine for “beep!” alarms, like the one in lesson K2.
- A passive buzzer is just the piezo element. It has no driver, so it needs a changing signal, a square wave, from your board [2]. The listing says to connect one pin to ground and the other to a square wave from a microcontroller, and that it is loudest around 4 kHz and works well from 2 to 10 kHz [2].
Which one do you want? If you only need an alarm beep, the active one is simpler. If you want different notes, you need a passive one, because pitch comes from the signal you send.
How to tell them apart. Read the listing or the label of the part first. Then you can test with something you already know. Put it on GPIO 25 through a 150 Ω resistor (in case it is the magnetic kind, see the next screen) and run lesson K2’s idea: digitalWrite(25, HIGH) and nothing else. A steady voltage is not a changing signal, so a passive piezo will not give you a steady tone [2], while an active buzzer will sound, since it brings its own oscillator [1]. If it beeps on a steady voltage, it is active. If it stays silent, that is not proof: through the resistor, an active buzzer made for 5 V can be too weak to sound. Then trust the listing, or try the melody sketch below: only a passive buzzer plays clearly different notes.
Where the picture stops: the two look nearly identical on a table, and a module with three pins can be either. Do not trust the look. Test it, or read the seller’s page.
Play a note
Wire the passive buzzer on GPIO 25, in place of the active one: the other leg goes to GND. The button stays on GPIO 27 (other leg to GND) and the LED on GPIO 26 through 220 Ω, as in lesson K2.
Check which passive buzzer you have. A piezo element (its listing says “piezo”, like the PS1240) can go straight on the pin: its listing says to connect one pin to ground and the other to a microcontroller [2]. Some parts sold as “passive buzzer” are the magnetic kind instead: a tiny coil, with a low resistance on the listing, such as 16 Ω. Wired straight to a pin, a coil like that asks for far more than the about 20 mA an ESP32 pin is designed to give (see K2). If yours is magnetic, or the listing does not say, put a 150 Ω resistor between GPIO 25 and the buzzer. It will be a little quieter, and the pin stays safe.
Upload this sketch and open the Serial Monitor at 115200 baud:
// Tinker Mission, lesson A1: a pitch you choose, with tone() and noTone()
// Wiring (passive buzzer, same pin as the active buzzer of lesson K2):
// Passive buzzer: one leg to GPIO 25 (the + leg if yours is marked), other leg to GND (3-pin module: S to GPIO 25, middle pin to 3V3, - to GND)
// Magnetic buzzer (coil, low resistance) or not sure? Add a 150 ohm resistor between GPIO 25 and the buzzer.
// Button: one leg to GPIO 27, the diagonally opposite leg to GND (no resistor needed)
// LED: GPIO 26 -> 220 ohm -> LED long leg; LED short leg -> GND
// On start: one beep at 440 Hz for half a second.
// Then: hold the button to hear 880 Hz. Release it and the sound stops.
// Try it: change the two numbers and listen to how the pitch changes.
const int BUZZER_PIN = 25;
const int LED_PIN = 26;
const int BUTTON_PIN = 27;
const unsigned int START_FREQ = 440; // hertz: vibrations per second
const unsigned int BUTTON_FREQ = 880; // twice as many vibrations per second
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
Serial.println("Start beep: 440 Hz");
tone(BUZZER_PIN, START_FREQ, 500); // pin, frequency, duration in ms (does not wait)
delay(600); // let it finish before the loop starts
}
bool wasPressed = false; // the button state at the last check
void loop() {
bool pressed = (digitalRead(BUTTON_PIN) == LOW);
if (pressed && !wasPressed) {
// just pressed: start the note once
tone(BUZZER_PIN, BUTTON_FREQ); // no duration: sounds until noTone()
digitalWrite(LED_PIN, HIGH);
} else if (!pressed && wasPressed) {
// just released: stop it
noTone(BUZZER_PIN);
digitalWrite(LED_PIN, LOW);
}
wasPressed = pressed;
delay(10);
}
Download the sketch folder (.zip)
You hear a short beep at start. Then hold the button: a higher tone sounds, and stops when you let go.
What the new lines do:
tone(pin, frequency)generates a square wave of that frequency on the pin, with a 50 % duty cycle, and it keeps going untilnoTone()[4].tone(pin, frequency, duration)does the same but for the given number of milliseconds [4]. It does not make the sketch wait [4], so we adddelay(600).noTone(pin)stops the wave [5].wasPressedremembers the button from the last pass, so the note starts once when you press and stops once when you release. Without it, the loop would calltone()again on every pass, about 100 times a second, for nothing.- The frequency is in hertz, the number of back-and-forths per second. The Arduino reference notes that tones lower than 31 Hz are not possible [4].
Only one tone can play at a time. A second call on another pin has no effect while the first is still playing; to switch pins, call noTone() on the first pin before tone() on the next one [4].
Press the keys in the piano below: each key shows its frequency in hertz and draws the square wave the board would send.
Simulation: the browser plays the note, not your board.
fixed frequency: 2000 Hz, whatever the key
Press a key.
Hold a key: the note plays while you hold it. Arrow keys move between keys, Space plays.
No sound in this browser: the picture still works.
This is the starting state: the controls need JavaScript.
A melody from two lists
A tune is a list of notes and a list of lengths. We store each list in an array, a row of numbers kept under one name: melody[0] is the first, melody[1] the second, and so on. Press the button and the sketch plays them one after the other:
// Tinker Mission, lesson A1: a short melody from two lists (notes and lengths)
// Wiring (passive buzzer):
// Passive buzzer: one leg to GPIO 25 (the + leg if yours is marked), other leg to GND (3-pin module: S to GPIO 25, middle pin to 3V3, - to GND)
// Magnetic buzzer (coil, low resistance) or not sure? Add a 150 ohm resistor between GPIO 25 and the buzzer.
// Button: one leg to GPIO 27, the diagonally opposite leg to GND (no resistor needed)
// LED: GPIO 26 -> 220 ohm -> LED long leg; LED short leg -> GND
// Press the button: the first notes of a well-known nursery tune play, and the LED lights with each note.
// An active buzzer cannot play this: it only makes its own single pitch.
const int BUZZER_PIN = 25;
const int LED_PIN = 26;
const int BUTTON_PIN = 27;
// Note frequencies in hertz (middle octave). REST = silence.
const unsigned int NOTE_C4 = 262;
const unsigned int NOTE_D4 = 294;
const unsigned int NOTE_E4 = 330;
const unsigned int NOTE_F4 = 349;
const unsigned int NOTE_G4 = 392;
const unsigned int NOTE_A4 = 440;
const unsigned int REST = 0;
// The tune, note by note.
const unsigned int melody[] = {
NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4,
NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4
};
// How long each note lasts, as a fraction of a whole note: 4 = a quarter, 2 = a half.
const int lengths[] = {
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2
};
const int NOTE_COUNT = sizeof(melody) / sizeof(melody[0]); // how many notes in the list
const unsigned long WHOLE_NOTE_MS = 2000; // a whole note lasts 2 seconds: lower = faster tune
void playMelody() {
for (int i = 0; i < NOTE_COUNT; i++) {
unsigned long duration = WHOLE_NOTE_MS / lengths[i]; // length of this note in ms
if (melody[i] == REST) {
noTone(BUZZER_PIN);
} else {
tone(BUZZER_PIN, melody[i], duration * 9 / 10); // sound for 90 % of the time ...
digitalWrite(LED_PIN, HIGH);
}
delay(duration * 9 / 10);
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
delay(duration / 10); // ... and a tiny gap before the next note
}
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
Serial.println("Press the button to play the melody.");
}
void loop() {
if (digitalRead(BUTTON_PIN) == LOW) {
Serial.println("Playing...");
playMelody();
Serial.println("Done. Press again.");
delay(300); // short pause so a long press does not restart at once
}
}
Download the sketch folder (.zip)
How to read it:
NOTE_C4 = 262: each note is just a frequency, taken from the note table of Arduino’s own melody example [8]. TheRESTvalue, 0, means silence.lengths[i]: 4 means a quarter of a whole note, 2 a half.WHOLE_NOTE_MS / lengths[i]gives the length in milliseconds.for (int i = 0; i < NOTE_COUNT; i++)repeats the block once per note.tone(..., duration * 9 / 10)starts the note, thendelay(...)waits for it. A short silence of one tenth after each note separates notes that repeat.
The sketch is simple on purpose: while it plays, delay() stops everything else (see K4 for how to avoid that). For a melody that is fine.
Real sound: the DFPlayer Mini
A buzzer makes beeps. For a voice, a drum or a real song you need recorded sound, and a DFPlayer Mini is a small module for that. It is a tiny MP3 player: you store sound files on a microSD card and your board tells it what to play. Its Arduino library is described as a mini MP3 player for Arduino [6]. In the library’s example, a missing SD card is one of the reasons listed when the module cannot start [6].
The idea, in four steps:
- Put MP3 files on a microSD card and slide it into the module.
- Connect the module to the board with a few wires, including a serial link: the board sends commands, the module plays the sound. The library’s example talks to it at 9600 baud [6].
- Install the
DFRobotDFPlayerMinilibrary (Library Manager). - In the sketch, call
begin(), set the volume (the example uses a range of 0 to 30), and ask it to play a file [6].
If you want to try it, here is the wiring, from the datasheet of a compatible module, the FN-M16P, kept in the library’s repository [9]. Power off while you wire.
VCCto the board’s5Vpin. The module accepts 3.3 to 5 V [9].GND(either one) to aGNDpin of the board.- Module
RXto GPIO 23, moduleTXto GPIO 32: the board’s send pin goes to the module’s receive pin, and back. These are the pins you used for Serial2 in lesson K5. The library example names a different port, Serial1, but either works on the ESP32 as long as you give it the pins. - No resistor on those two wires. The module’s serial pins work at 3.3 V [9], like the ESP32. The datasheet asks for a 1 kΩ resistor only with a 5 V board [9].
- A small 4 Ω or 8 Ω speaker of less than 3 W between
SPK1andSPK2[9]. Do not connect either of those two pins toGND.
In the library’s example, the ESP32 line uses the pin names D3 and D2, which do not exist on the DevKitC. Change that line to FPSerial.begin(9600, SERIAL_8N1, 32, 23); (receive pin 32, send pin 23) [6]. Start with a low volume, such as 10 out of 30: if the board resets when the sound starts, the USB supply is too weak (lesson A2 shows the same problem with a servo). Another DFPlayer library’s author also advises reading the maker’s page before connecting the module [7]. The same example notes it was tested on Arduino Uno, Leonardo and Mega boards [6], so on an ESP32 expect to try and adjust.
Wiring an actual DFPlayer is a good first project later. For now you know what it is for: buzzer = beeps from your own code, DFPlayer = recorded sound from a card.
Try your own changes
Change one thing, upload, listen.
- Your own pitch. In
l-a1-tone, changeBUTTON_FREQto 440, then 1000, then 2000. What changes? A passive piezo works well between 2000 and 10,000 Hz [2]. - Faster tune. In
l-a1-melody, setWHOLE_NOTE_MSto 1000, then 4000. - Your own tune. Replace the first few notes and lengths with your own. Remember to add one length for each note.
- Silence in the tune. Put
RESTbetween two notes and give it a length. - Active buzzer test. Put an active buzzer on GPIO 25 and run
l-a1-melody. What do you hear?
When it does not work
- No sound at all. Check the wiring: one leg on GPIO 25 (the one marked + if yours has a mark) and the other on
GND. Check the pin number. - The button changes nothing. Check the other leg to
GNDand theINPUT_PULLUPline, as in K2. - Every note sounds the same, only the rhythm changes. You probably have an active buzzer. It plays one fixed frequency [1].
- Very quiet. Try a frequency nearer 4 kHz, where the passive piezo of that listing is loudest [2].
- The first notes are cut short or run together. Check that
delay()is as long as the note, and that there is a short gap after each one. - Nothing in the Serial Monitor. Set it to 115200 baud, the same as
Serial.begin(115200).
Check yourself
Three short questions. Nothing is saved, take your time.
You want your board to play different notes. Which buzzer do you need?
- An active buzzer, because it makes the sound by itself
- A passive buzzer, because you choose the frequency yourself
- Either one, they behave the same
What does tone(25, 440); do, with no duration?
- It beeps for 440 milliseconds
- It plays a 440 Hz square wave on pin 25 until noTone(25) is called
- It plays 25 notes at 440 Hz
You write tone(25, 440, 500); and the next line of your sketch runs straight away. Why?
- The board is broken
- tone() is non-blocking: it starts the note and does not wait for it to end
- The duration is ignored
Show the answer
tone() is non-blocking: it starts the note and does not wait for it to end. The Arduino reference says tone() does not block the sketch, even with a duration [4]. If you want the note to finish before the next one, add a delay() as long as the note.
In short
- Sound is air moving back and forth. A piezo buzzer moves a disc with a changing voltage [3].
- An active buzzer has its own oscillator and one fixed pitch [1]. A passive buzzer needs a square wave from your board [2].
tone(pin, frequency)starts a note,tone(pin, frequency, duration)plays it for a time without making the sketch wait, andnoTone(pin)stops it [4][5].- A melody is two arrays, notes and lengths, played in a loop.
- A DFPlayer Mini plays recorded MP3 files from a microSD card, under serial commands from your board [6]. The datasheet of a compatible module gives the wiring: 3.3 to 5 V, serial at 3.3 V with no resistor, speaker on SPK1 and SPK2 [9].
Next step: A2, where a different kind of signal moves a servo.
Sources
Show the 9 sources
- Adafruit, “Buzzer 5V - Breadboard friendly” (product ID 1536) (3 V to 5 V applied gives a 2 kHz beep; unlike a plain piezo it does not need an AC signal; it contains a piezo plus driver circuitry that oscillates at 2 kHz; you cannot change the frequency) — https://www.adafruit.com/product/1536
- Adafruit, “Piezo Buzzer - PS1240” (product ID 160) (piezo buzzers are used for beeps, tones and alerts; driven by a 3-30 V peak-to-peak square wave; connect one pin to ground and the other to a square wave from a timer or microcontroller; loudest around 4 kHz, works well from 2 kHz to 10 kHz) — https://www.adafruit.com/product/160
- Adafruit, “Using Piezo Buzzers with CircuitPython & Arduino”, Overview (a piezo crystal changes shape when voltage is applied; pushing against a diaphragm it creates a pressure wave heard as sound; changing the frequency of the voltage changes the sound) — https://learn.adafruit.com/using-piezo-buzzers-with-circuitpython-arduino/overview
- Arduino, Language Reference, “tone()” (generates a square wave of the given frequency, 50 % duty cycle; continues until noTone() unless a duration is given; only one tone at a time; not possible below 31 Hz; non-blocking even with a duration; call noTone() on one pin before tone() on another) — https://docs.arduino.cc/language-reference/en/functions/advanced-io/tone/
- Arduino, Language Reference, “noTone()” (stops the square wave started by tone(); no effect if none is playing) — https://docs.arduino.cc/language-reference/en/functions/advanced-io/noTone/
- DFRobot, DFRobotDFPlayerMini library, README and example “FullFunction” (a mini MP3 player for Arduino; serial at 9600; begin() with a serial port, error message asking to check the connection and insert the SD card; volume 0 to 30; ESP32 branch of begin(9600, SERIAL_8N1, rx, tx); the notice points to the maker’s connection diagram and says it was tested on Arduino Uno, Leonardo, Mega) — https://github.com/DFRobot/DFRobotDFPlayerMini
- Makuna, DFMiniMp3 library wiki, Home (a library supporting the DFRobot DFPlayer Mini MP3 module; read the maker’s product page before connecting the module, it saves a lot of time and effort) — https://github.com/Makuna/DFMiniMp3/wiki
- Arduino, example “toneMelody”, file pitches.h (NOTE_C4 262, NOTE_D4 294, NOTE_E4 330, NOTE_F4 349, NOTE_G4 392, NOTE_A4 440 Hz) — https://github.com/arduino/arduino-examples/blob/main/examples/02.Digital/toneMelody/pitches.h
- Flyron Technology, “FN-M16P Embedded MP3 Audio Module Datasheet” V1.0, kept in DFRobot’s DFRobotDFPlayerMini repository, doc folder (a module with the same 16-pin layout as the DFPlayer Mini, kept by DFRobot with its library; VCC DC3.2 to 5.0 V in the pin table, 3.3 to 5.0 V in the specifications; RX and TX at 3.3 V TTL level; 9600 baud by default; 1 kΩ resistor between TX and RX only with a 5 V microcontroller; built-in 3 W amplifier for a 4 Ω or 8 Ω speaker under 3 W on SPK1 and SPK2; figure 5-1, 3.3 V serial connection) — https://github.com/DFRobot/DFRobotDFPlayerMini/blob/master/doc/FN-M16P%2BEmbedded%2BMP3%2BAudio%2BModule%2BDatasheet.pdf