Datasheet
Chapter 4 • BOE Shield-Bot Navigation
130 • Robotics with the BOE Shield-Bot
Example Sketch – PlayOneNote
Here is an example that displays an individual array element’s value in the Serial Monitor,
and also uses that value to make the BOE Shield-Bot’s piezospeaker play a musical note.
Create, save, and run the PlayOneNote sketch, and run it on the Arduino.
Open the Serial Monitor as soon as the sketch is done loading.
Verify that the Serial Monitor displays “note = 1397.”
Verify that the speaker played a tone.
Modify the sketch to play and print the value of 1568 using
note[4].
Test your modified sketch.
// Robotics with the BOE Shield – PlayOneNote
// Displays and plays one element from note array.
int note[] = {1047, 1147, 1319, 1397, 1568, 1760, 1976, 2093};
void setup()
{
Serial.begin(9600);
Serial.print("note = ");
Serial.println(note[3]);
tone(4, note[3], 500);
delay(750);
}
void loop()
{
}
Example Sketch – PlayNotesWithLoop
Many applications use variables to access elements in an array. The next sketch declares a
variable named
index and uses it to select an array element by its index number.
The familiar
for loop can automatically increment the value of index. The code to play and
display notes is inside the
for loop, and index is used to select the array element. For the
first trip through the loop,
index will be 0, so the value stored in note[0] will be used
wherever
note[index] appears in a print or tone function. With each trip through the
loop,
index will increment until the sketch has displayed and played all the notes in the
array.
Create, save, and run PlayNotesWithLoop, then open the Serial Monitor as soon
as the sketch is done loading.