Notes in an Array
Part of the Outputs section of Coddy's Arduino journey. Lesson 13 of 24.
A melody is a list of notes. An array keeps a list of values under one name:
int notes[] = {262, 294, 330, 349}; // C, D, E, FEach value has a position called its index, and counting starts at 0: notes[0] is 262, notes[1] is 294, and the last one, notes[3], is 349. There is no notes[4]: reading it gives whatever happens to be in memory after the array.
The index can be a variable. Keep one, play the note it points at, then move it on:
int i = 0;
void loop() {
tone(8, notes[i]);
delay(400);
i = i + 1;
if (i == 4) {
i = 0;
}
}Each time loop() runs, the next note plays. After the last one, the index goes back to 0 and the tune starts again.
Challenge
EasyPlay the notes C, D, E and F one after another on pin 8, 400 ms each, again and again:
- keep the four frequencies in an array: 262, 294, 330, 349
- use an index variable to play the next one each time
loop()runs - after the last note, go back to the first
Press Run, then Check.
Try it yourself
const int buzzerPin = 8;
// make the notes array and the index variable here
void setup() {
}
void loop() {
// play the note at the index, wait 400 ms, move to the next one
}
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