Suppose I want the servo motor to move from 0° to 180°.
I could write:
myServo.write(0);
myServo.write(1);
myServo.write(2);
...
myServo.write(180);
But that would mean writing more than 180 lines of code!
Instead, we use a for loop, which allows us to repeat the same instructions automatically.
for (int angle = 0; angle <= 180; angle++) {
myServo.write(angle);
delay(15);
}
A for loop has three parts:
for (initialization; condition; increment)
Let’s understand each part.
int angle = 0
Here, I create a variable called angle and give it a starting value of 0.
So, the servo starts from 0 degrees.
angle <= 180
This means:
Continue repeating as long as the angle is less than or equal to 180.
angle++
This means:
Increase the value of angle by 1 after every repetition.
It is the same as:
angle = angle + 1;
angle = 0
So,
myServo.write(0);
The servo moves to 0°.
angle = 1
So,
myServo.write(1);
The servo moves to 1°.
angle = 2
So,
myServo.write(2);
The servo moves to 2°.
This continues:
0°
1°
2°
3°
...
180°
When the angle becomes 181,
181 <= 180
is false.
So the loop stops.
Now look at the second loop:
for (int angle = 180; angle >= 0; angle--) {
myServo.write(angle);
delay(15);
}
Here,
angle--
means
angle = angle - 1;
So the servo moves like this:
180°
179°
178°
...
2°
1°
0°
for (int angle = 0; angle <= 180; angle++)
means:
Start from 0, continue until 180, and increase by 1 each time.
And
for (int angle = 180; angle >= 0; angle--)
means:
Start from 180, continue until 0, and decrease by 1 each time.
A for loop is used when we know how many times we want to repeat a set of instructions.