RECREATE A COMPLETE PROGRAM
Once you’ve created a melody that you like, you’ll probably want to add the blinking behavior you created in the last section back to your program. Do this by removing the // characters that are in front of the blinkPattern procedure call in loop. Compile and upload your new code. See how your blinking and singing monster behaves. At this point, you may also want to adjust your blinkPattern or song procedures so that they work well together.
void loop() { blinkPattern(); song(2000); delay(5000); }
Notice how the song doesn’t begin until your LED is finished blinking and, likewise, your blinking doesn’t begin until the song has stopped. Remember that Arduino executes your program line by line in order. It can only do one thing at a time. It needs to finish one thing before it moves on to the next. In the example above, since blinkPattern(); is the first line in loop, the first thing the monster does is blink. Then, since song(2000); is the second line in loop, it plays its song. Then the monster delays (does nothing) for five seconds.
SAVE YOUR CODE
Once you are happy with your program, save it by clicking on the downward pointing arrow in the Toolbar. Your entire program should now look something like the code below. The bodies of the song and blinkPattern procedures will be different in your code. The loop section may be slightly different as well.
int led = A4; int speaker = 5; // speaker is attached to pin 5 int C = 1046; int D = 1175; int E = 1319; int F = 1397; int G = 1598; int A = 1760; int B = 1976; int C1 = 2093; void setup() { pinMode(led, OUTPUT); pinMode(speaker, OUTPUT); } void loop() { blinkPattern(); song(2000); delay(5000); } void song(int duration) { tone(speaker, C); delay(duration); tone(speaker, D); delay(duration); tone(speaker, E); delay(duration); tone(speaker, F); delay(duration); tone(speaker, G); delay(duration); tone(speaker, A); delay(duration); tone(speaker, B); delay(duration); tone(speaker, C1); delay(duration); noTone(speaker); delay(duration); } void blinkPattern() { digitalWrite(led, HIGH); delay(100); digitalWrite(led, LOW); delay(100); digitalWrite(led, HIGH); delay(500); digitalWrite(led, LOW); delay(500); }