This program creates a siren that automatically rises and falls according to your code. To control the noise, you'll use a for loop- a counting loop within the void loop.
Read the Code Walkthrough Text (click to open)
New Concept: For Loops
The for loop repeats some code a set number of times, then completes and exits. Every for loop has three parts: a variable with a value, a condition based on that variable, and a way to modify that variable each time the for loop runs.
Think of the for loop as answering these questions: "What is my starting point?"- the variable. "How do I know I'm finished?"- the conditional. "How do I get there?"- the modifier statement. Finally, "What do I do each time I run?"- the code that repeats each time the for loop runs.
Take for example a tone that should increase from 0 to 500 hertz, one hertz at a time, then stop increasing. You need to start the tone at 0 by making a variable with a value of 0. You need to set a condition so that as long as the variable is less than 501, the variable increases in value. And finally, you need to define that the variable should increase by one (not two or ten) as it ascends.
The for loop only modifies the variable and keeps track of it. In this example, you still need to include the tone commands and the delays between tones. You could also include an LED blink or any other code. The for loop's job is to repeat from the starting point you gave it to the ending point you gave it and follow the rule for how to change along the way.
Keep in mind that once the for loop starts, it will repeat without checking other code around it. For example, if you have an if statement that is supposed to stop the for loop from running, that if statement has to be inside the for loop. Otherwise, it won't be checked by the computer until the for loop has ended.