Play a melody with a buzzerTinkerPieCircuit tutorial 13 of 24 · Intermediate · 15 minutes
Press a button to play the notes of a scale on a buzzer using tone().
Open this circuit in TinkerPieCircuit (free, runs in your browser)
What you will learn
- tone(pin, frequency) and noTone(pin)
- Arrays of notes
- Combining a button and a buzzer
Parts
Steps
Wire the buzzer
Click Buzzer. Wire its + leg to
P12and its − leg toGND.Wire the button
Wire the button between
P10andGND, like the Button tutorial.List the notes
A note is a frequency in hertz.
262is middle C. The array holds eight notes of a scale.Play when pressed
When the button is pressed, a loop plays each note for 200 ms with
tone(P12, note).Listen
Press ▶ Start (your browser needs this click to allow sound) and hold the button.
The code
function setup() {
pinMode(P10, INPUT_PULLUP);
}
function loop() {
if (digitalRead(P10) == LOW) {
const notes = [262, 294, 330, 349, 392, 440, 494, 523];
for (let i = 0; i < notes.length; i++) {
tone(P12, notes[i]);
delay(200);
}
noTone(P12);
}
}
Copy this into the Code tab. It is Arduino-style JavaScript. The real board uses the same pin names (S1, P10…) in TinkerPie Studio.
How it works
A higher frequency is a higher note. The buzzer clicks on and off that many times each second.
← Make a servo sweep · All 24 circuit tutorials · Why LEDs need a resistor →