Full Siren: Tone Loops

Use back-to-back ‘for’ loops to create a sound effect you can control to sound like a laser blaster, siren, alarm, or anything else you can code up!

Code

The code in the editor below already works. Just plug in your Code Speaker and press upload to see what it does! Tinker with it and make changes to see what each line of code controls.

// Create a rising and falling siren on the Speaker void setup(){ pinMode(10,OUTPUT); //Set the speaker as an OUTPUT } void loop(){ for(int i=40; i<800; i++){ //start at 40 hertz and play a new tone up to 800 hertz tone(10,i); //play the tone that is equal to the variable 'i' delay(3); //delay 3 milliseconds before starting the 'for' loop again } //The second 'for' loop only runs after the first 'for' loop has completed for(int i=800; i>40; i--){ //start at 800 hertz and play a new tone down to 40 hertz tone(10,i); //play the tone that is equal to the variable 'i' delay(3); //delay 3 milliseconds before starting the 'for' loop again } } // (c) 2018 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Walkthrough Videos

Watch the videos for line-by-line explanation of how the example program works. Then you'll be ready to make some changes of your own!

Challenges

Can you complete the challenge? Change the code in your code editor above. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!



Concepts

These are the new code concepts covered in this example program. To become a great coder, read through these concepts to learn new vocabulary.

New Concept: Building blocks, revisited

This program has lots of components: loops, variables and conditions. But the program can also be broken down into more easily understood groups. The void loop contains two ‘for’ loops. Each ‘for’ loop contains 4 parts: the variable, the condition, the variable change, and the actions. The actions of each ‘for’ loop are some of the most basic commands you learned: tone and delay.

Programming is about learning how to break down your problems into understandable pieces, translate those pieces to computer code, and then put the pieces back together to build your solution.

Quiz

If you're having trouble, try to run an experimental program or look at the example code to help you find the answer.

1. How many times does each 'for' loop run each time the void loop runs in this program?