Play a Melody on a Piezo Buzzer (Arduino)
Play a simple tune with tone() on a passive piezo buzzer. Learn frequencies, arrays, and loops.
Beginner20 min
What you need
Wiring
Hover a pin or a wire to trace the connection.
Code
buzzer_melody.ino
// Play an 8-note scale on a passive piezo buzzer with tone().
const int buzzer = 8;
int melody[] = { 262, 294, 330, 349, 392, 440, 494, 523 }; // C4 to C5
void setup() {}
void loop() {
for (int i = 0; i < 8; i++) {
tone(buzzer, melody[i], 300); // play note for 300 ms
delay(350); // small gap between notes
}
noTone(buzzer);
delay(1000);
}
Steps
- Wire the buzzer: + (signal) to D8, − to GND.
- Use a passive buzzer (tone() sets the pitch); an active buzzer only beeps.
- Upload to hear the scale repeat.
- Swap the numbers in melody[] for different notes.