Datasheet

BOE Shield-Bot Navigation • Chapter 4
Robotics with the BOE Shield-Bot 131
Verify that the Serial Monitor displays each note in the array as the speaker plays
it.
// Robotics with the BOE Shield PlayNotesWithLoop
// Displays and plays another element from note array.
int note[] = {1047, 1147, 1319, 1397, 1568, 1760, 1976, 2093};
void setup()
{
Serial.begin(9600);
for(int index = 0; index < 8; index++)
{
Serial.print("index = ");
Serial.println(index);
Serial.print("note[index] = ");
Serial.println(note[index]);
tone(4, note[index], 500);
delay(750);
}
}
void loop()
{
}
What do you think will happen if you change the for loop to match the one
below? Try it!
for(int index = 7; index >= 0; index--);
Using the sizeof Function
Let’s say you want to compose a musical melody that has more, or fewer, notes. It’s easy to
forget to update the
for loop to play the correct number of notes. The Arduino library has
a
sizeof function that can help with this. It can tell you both the size of the array in bytes,
and the size of the array’s variable type (like
int). Your code can then divide the number of
bytes for the variable type into the number of bytes in the array. The result is the number of
elements in the array.
Here is an example of using this technique. It loads a variable named
elementCount with
the number of elements in the
note array:
int note[] = {1047, 1147, 1319, 1397, 1568, 1760, 1976, 2093};