In this lesson you'll be learning about the "for" command. Full details on this command can be found on page 21 of the Arduino Programming guide. The "for" command is the next iteration of our repetition lessons. It will keep repeating what ever is in the brackets as long as the "condition" is true. You'll need to set up your circuit so that you have an LED (with appropriate resistors) plugged into pins digital pins 8-13.
The "for" process above will light up each pin starting at 13 and counting down to 8 in sequence, turning it off before it lights the next one. You'll notice " int ledPin=13" in the for statement. In this case ledPin only has meaning inside the for loop, this variable is not declared at the beginning of the program. The basic structure of "for" is as follows:
All for loops will have an integer variable associated with them. I chose to use ledPin as the variable name since we'll be lighting an LED. The process runs as a loop. The condition is checked, if true the code in the brackets is run and then the expression is executed. Then it checks to see if the condition is still true. It functions just like our while loop. In this loop, is ledPin greater than or equal to 8? If true the code is run and Expression are completed. For our loop, the value of ledPin will be decreased by 1 each time through, which will cause the next LED to light up. When ledPin is decreased to 7 the condition is no longer true and the process stops. Overall, this is very similar to how we used our while loop. You'll rapidly find that there are often many ways to complete the same task. Some of these ways will work better in certain conditions than others, but often it doesn't matter how you do it. The full sketch is listed below:
Additional Tasks:
There is another, probably better way, to write the expression "ledPin = ledPin - 1". This is to use incremental operators.
So, if x=2, x+=5 would set x to be 7. Again if x=2, x*=5 would set x to be 10.
Additional Tasks:
|