Play a Tone on a Buzzer
Part of the Outputs section of Coddy's Arduino journey. Lesson 10 of 24.
A buzzer clicks every time the voltage on its pin changes. Click it hundreds of times a second and you hear a note.
The number of times per second is the frequency, counted in hertz (Hz). A higher frequency is a higher note: 440 Hz is the note A, and 880 Hz is the A one octave above it.
tone(pin, frequency) switches the pin on and off at that frequency for you:
tone(8, 440); // play 440 Hz on pin 8Like a PWM pin, the tone keeps playing on its own, through delay(), until you call tone() again with another frequency. It works on any pin, not only the ~ ones.
Challenge
EasyThe buzzer is on pin 8. Make a two-note siren:
- play 440 Hz for one second
- then 880 Hz for one second
- again and again
Press Run and listen, then Check.
Try it yourself
const int buzzerPin = 8;
void setup() {
}
void loop() {
// 440 Hz for a second, then 880 Hz for a second
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
3Sound
Play a Tone on a BuzzerBeeps and SilencePitch From a KnobNotes in an ArrayA Melody From Two ArraysPractice on your own: Arduino playground