Your Arduino is doing great blinking. Now, it's time to try making noise. Start by connecting the piezo speaker to pin 3. It has two pins coming out of it. Make sure the one labeled "+" is on the side closer to the Arduino chip (white wire in photo) and the other (black wire in photo) is connected to the outside pin, using any color jumper wires. Note, nothing get connected to the middle pin on the Arduino board. Next, get back into ArduBlock and start with an empty loop. Grab the top tone block from the Pins category. Set the pin# to 3 and leave the frequency at 440. Next add a delay of 1000 milliseconds, then go back to the Pins category and grab a no tone block. Set the pin# to 3 again and add another delay. Without the second delay, It will play a note for a second then be off for 1/1000 second before turning back on. It will be hard to hear it turn off. Try this and hear your robot make noise. Add more tone blocks for more notes and change the delay to change the length of the note.
Switching back to the code, it is almost as simple as the first LED code you wrote. This time, the setup is empty. Within the loop the code is very similar to the ArduBlock code. When using tone, it requires two parameters with a third optional parameter. The first parameter is the pin. The second is the frequency. If you use the third, optional parameter, it is duration. The code below is more similar to what was written above.
void setup()
{
}
void loop()
{
tone(3, 440);
delay( 1000 );
noTone(3);
delay( 1000 );
}
This is not the only way to get the robot to play a one second note at 440Hz. You can also shorten the code to just:
void setup()
{
}
void loop()
{
tone(3, 440, 1000);
delay( 1000 );
}
This makes the code a little tighter and cleaner. It also makes it easier to add more notes.
Independent Challenge: Song
It's time to play a song. Your challenge is to get your robot to play a recognizable song of at least 12 notes and preferably at least 20. Be sure to change the duration and frequency of the notes. Also, a pause of 10 milliseconds between each note ensures that one note doesn't blend into the next. Hint: Nursery rhymes, holiday songs and early-learner band songs are easiest.