Piano Siren: Tone Looping

Let’s start with basics- beep a single tone on the piano on repeat to learn about loops!


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 and then falling 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 checking the for loop condition again } for(int i = 800; i>40; i--){ //starting at 800 hertz and going down to 40 hertz tone(10,i); //play a tone equal to variable 'i' delay(3); //delay 3 milliseconds before checking the for loop condition 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!


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: Short-term variables & scope

When you write ‘i =…’ in the ‘for’ loop, you’re creating a new variable. That variable is used for one purpose: keeping track of how many times the ‘for’ loop has run. Because it has such a limited purpose, it’s typical to just use ‘i’ as the name, instead of typing out ‘counter’ or ‘forLoopVariable’ or something that might be more descriptive, but harder to type out.

In this program, you are creating the ‘i’ variable twice, once for each ‘for’ loop. Because the variable is created inside the ‘for’ loop, it only exists inside that ‘for’ loop and it gets recreated each time the ‘for’ loops run. This concept that the variable can ‘exist’ some places but not others within the same program is called the variable’s scope.


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

1. What are the four parts of a 'for' loop, in order of how they're typed? Hint: Use your purple cards!