Play a melody
Play "Twinkle, Twinkle, Little Star" on a piezo buzzer with tone().
Output · Beginner
In a real product: Microwave oven (Consumer electronics): The end-of-cooking melody and key beeps come from a piezo driven by a timer.
A piezo buzzer clicks every time its voltage changes. Switching it on and off hundreds of times a second makes a note, and changing the rate changes the pitch. tone() does that for you.
What you'll learn
- How
tone(pin, frequency, duration)makes a square wave - Storing a melody as arrays of frequencies and lengths
- Why you still need a
delay()aftertone()
How it works
The buzzer's + pin (2) is on pin 8 and its − pin (1) is on GND. tone(8, 262) toggles pin 8 at 262 Hz, which is middle C. A hardware timer does the toggling, so the CPU is free meanwhile.
melody[] holds each note's frequency in hertz and beats[] its length. tone() with a duration stops the note by itself, but returns at once, so delay() waits for the note (plus a short gap) before the next one starts.
In the simulator you hear the buzzer through your speakers.
Try this
- Speed the tune up or slow it down by changing the 300 ms beat.
- Add a pushbutton that plays the melody only when pressed.
- Write a siren: sweep the frequency up from 500 Hz to 1500 Hz and back.
sketch.ino
// Play "Twinkle, Twinkle, Little Star" on a buzzer on pin 8.
const int BUZZER = 8;
// Note frequencies in Hz (C4 = 262, G4 = 392, A4 = 440...) and their lengths in beats.
const int melody[] = {262, 262, 392, 392, 440, 440, 392, 349, 349, 330, 330, 294, 294, 262};
const int beats[] = {1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2};
const int NOTES = sizeof(melody) / sizeof(melody[0]);
const int BEAT_MS = 300;
void setup() {}
void loop() {
for (int i = 0; i < NOTES; i++) {
tone(BUZZER, melody[i], BEAT_MS * beats[i]);
delay(BEAT_MS * beats[i] + 50); // the note, then a short gap
}
noTone(BUZZER);
delay(1500);
}