Hardware Reference
In-Depth Information
Listing 2-2: LED with Changing Blink Rate—blink.ino
const int LED=9; //define LED for Pin 9
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
}
void loop()
{
for (int i=100; i<=1000; i=i+100)
{
digitalWrite(LED, HIGH);
delay(i);
digitalWrite(LED, LOW);
delay(i);
}
}
Compile the preceding code and load it onto your Arduino. What happens?
Take a moment to break down the for loop to understand how it works. The
for loop declaration always contains three semicolon-separated entries:
The first entry sets the index variable for the loop. In this case, the index
variable is i and is set to start at a value of 100 .
The second entry specifies when the loop should stop. The contents of
the loop will execute over and over again while that condition is true. <=
indicates less than or equal to. So, for this loop, the contents will continue
to execute as long as the variable i is still less than or equal to 1000 .
The final entry specifies what should happen to the index variable at the
end of each loop execution. In this case, i will be set to its current value
plus 100 .
To better understand these concepts, consider what happens in two passes
through the for loop:
1. i equals 100 .
2. The LED is set high, and stays high for 100ms, the current value of i .
3. The LED is set low, and stays low for 100ms, the current value of i .
4. At the end of the loop, i is incremented by 100 , so it is now 200 .
5. 200 is less than or equal to 1000 , so the loop repeats again.
6. The LED is set high, and stays high for 200ms, the current value of i .
7. The LED is set low, and stays low for 200ms, the current value of i .
Search WWH ::




Custom Search