Use a ‘for’ loop to control where your tone starts, how high it will play, and how fast it gets there. Sounds like a siren!

The code in the editor below already works Just plug in your Code Piano 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 tone on the Piano 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 } } // (c) 2018 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

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!


Challenge

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!

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: Loops within loops

In this project, you gained more control over how your code runs. In past projects, you had the void loop running an infinite number of times. Now, you can write a loop within the loop, which gives you more control over how the code will run.

New Concept: Speed, revisited

Your ‘for’ loop runs 760 times in this program (800-40). That means the time it takes to complete is 760 * the number of milliseconds delay within the ‘for’ loop. By changing the delay from 3 milliseconds to 6 milliseconds, you’re actually making the change from 2280 milliseconds (7603) to 4560 milliseconds (760*6). Even those tiny differences can have a big impact when you’re running a loop hundreds or thousands of times.


Quiz

If you're having trouble coming up with an answer to a quiz question, try to run an experimental program or look at the example code to help you find the answer.

1. How many times does the 'for' loop run for each void loop?