03 / Templates · beginner
BUZZER
Open in PlaygroundPlay tones and short melodies on a piezo buzzer using Arduino's tone() function — no resistor required.
beginnerbuzzertoneaudioPWM
sketch.inoArduino C++
35 lines
// Buzzer — Tone / Melody Player
// Plays the opening notes of "Twinkle Twinkle Little Star" on the piezo buzzer.
const int BUZZER_PIN = 8;
// Note frequencies (Hz)
const int NOTE_C4 = 262;
const int NOTE_D4 = 294;
const int NOTE_E4 = 330;
const int NOTE_F4 = 349;
const int NOTE_G4 = 392;
const int NOTE_A4 = 440;
int melody[] = {
NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4,
NOTE_A4, NOTE_A4, NOTE_G4,
};
int durations[] = {
400, 400, 400, 400,
400, 400, 800,
};
void setup() {
Serial.begin(9600);
Serial.println("Playing melody...");
}
void loop() {
for (int i = 0; i < 7; i++) {
tone(BUZZER_PIN, melody[i], durations[i]);
delay(durations[i] * 1.3); // pause between notes
}
noTone(BUZZER_PIN);
delay(2000); // wait, then repeat
}- Arduino Uno01
- Buzzer02
| Component Pin | Arduino Pin |
|---|---|
| Buzzer Positive (+) | Pin 8 |
| Buzzer Negative (−) | GND |