When designing a sketch, you’ll often repeat the same function. You could
simply copy and paste the function to duplicate it in a sketch, but that’s inefficient
and a waste of your Arduino’s program memory. Instead, you can
use for loops. The benefit of using a for loop is that you can determine how
many times the code inside the loop will repeat.
To see how a for loop works, enter the following code as a new sketch:
Project 2 - Repeating with for Loops
int d = 100;
void setup()
{
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
}
void loop()
{
First Steps 47
for ( int a = 2; a < 7 ; a++ )
{
digitalWrite(a, HIGH);
delay(d);
digitalWrite(a, LOW);
delay(d);
}
}
..................................................................................................................................................................
The for loop will repeat the code within the curly brackets beneath it
as long as some condition is true. Here, we have used a new integer variable,
a, which starts with the value 2. Every time the code is executed, the
a++ will add 1 to the value of a. The loop will continue in this fashion while
the value of a is less than 7 (the condition). Once it is equal to or greater
than 7, the Arduino moves on and continues with whatever code comes
after the for loop.
The number of loops that a for loop executes can also be set by counting
down from a higher number to a lower number. To demonstrate this,
add the following loop to the Project 2 sketch after the first for loop:
u for ( int a = 5 ; a > 1 ; a-- )
{
digitalWrite(a, HIGH);
delay(d);
digitalWrite(a, LOW);
delay(d);
}
Here, the for loop at u sets the value of a equal to 5 and then subtracts
1 after every loop due to the a--. The loop continues in this manner while
the value for a is greater than 1 (a > 1) and finishes once the value of a falls
to 1 or less than 1.
We have now re-created Project 1 using less code. Upload the sketch
and see for yourself!
No comments:
Post a Comment