A Melody From Two Arrays
Part of the Outputs section of Coddy's Arduino journey. Lesson 14 of 24.
Notes in a tune are not all the same length. A second array can hold the durations, lined up with the notes: notes[i] and durations[i] belong together.
int notes[] = {262, 262, 392, 392, 440, 440, 392};
int durations[] = {400, 400, 400, 400, 400, 400, 800};Two equal notes in a row would blur into one long note. A short silence after each one keeps them apart, so play the note for its duration and wait a little longer:
tone(8, notes[i], durations[i]);
delay(durations[i] + 50);The duration stops the note, and the extra 50 ms is the gap before the next one.
When the index goes past the last note, the melody is over: wait a moment before starting it again so it does not run into itself.
Challenge
MediumPlay the first line of Twinkle Twinkle Little Star on pin 8:
- notes: 262, 262, 392, 392, 440, 440, 392
- durations: 400 ms each, and 800 ms for the last note
- after each note, wait its duration plus 50 ms
- after the last note, wait one more second and start again
Press Run, then Check.
Try it yourself
const int buzzerPin = 8;
// make the notes and durations arrays, and the index, here
void setup() {
}
void loop() {
// play one note, wait its duration plus 50 ms, move to the next one
// after the last note, wait a second and start again
}
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