// Copyright 2007, Sandeep Gangadharan // For more free scripts go to http://www.sivamdesign.com/scripts/

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.

Code

/* * Play a tone ascending, then descending, on a speaker using 'for' loops */ void setup() { pinMode(A5, OUTPUT); //speaker } void loop() { //starting at 40, increase pitch by 1 until it equals 1999 for (int pitch = 40; pitch < 2000; pitch++) { tone(A5, pitch); //play the pitch delay(5); //time before the next pitch is played } //starting at 2000, decrease pitch by 1 until it equals 41 for (int pitch = 2000; pitch > 40; pitch--) { tone(A5, pitch); //play the pitch delay(5); } } // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Challenges

How many can you complete? Change the code and hardware according to the challenges below. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!

Videos

Read the Code Walkthrough Text (click to open)

Concepts

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. 


Quiz

If you're having trouble, try to run a program that can help you find the answer.

1. Which of the following is not a part of creating a'for' loop?




2. How many times will a 'for' loop run?