Take your laser blaster sound effects to the next level using your latest and greatest coding skills.
The code in the editor below already works Just plug in your Code Rocket and press upload to see what it does! Tinker with it and make changes to see what each line of code controls.
New Concept: Nesting
You’ve been using this concept in nearly every program so far, but it’s time to give it a name. Nesting is about organizing your code, both visually (to make it easier for humans to understand) and logically. In this program, you have a void loop. Inside that, there is an ‘if’ statement. Inside that, there is a ‘for’ loop. Inside the ‘for’ loop are tone and delay commands. To help display that logic clearly, programmers will usually indent each ‘layer’ of the nested statements deeper than the last. That is why you’ll sometimes see multiple closing curly braces ( } ) on one line after another. Each curly brace is ending a different ‘layer’ of the nested statements above.
Now let’s think about why you need to nest. Working backward, if you wrote out the intention of the first ‘blaster’ sound effect, you might write:
“Play a tone of ‘i’ on pin 2. Only do that if the ‘for’ loop condition is true. Only check the ‘for’ loop condition when if the ‘if’ statement is true.”
In this case, you have two conditions that both have to be true in order for your tone to play. The layers of nesting are what allow you to check all those conditions in sequence.
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 milliseconds does it take for one of the 'for' loops to run in the example code? Hint: Take the number of times the loop runs and multiply it by any delays inside the for loop.