Datasheet

Chapter 1 Your Shield-Bot’s Brain
34Robotics with the BOE Shield-Bot
statement that follows the for loop’s code block. In this case, the condition is “if i is less
than or equal to 10.”
Increment: how to change the value of
i for the next time through the loop. The
expression
i++ is equivalent to i = i + 1. It makes a nice shorthand approach for adding 1
to a variable. Notice that
++ comes after i, meaning “use i as-is this time through the
function, and then increment it afterward.” This is the post increment use of the operator.
The first time though the loop, the value of
i starts at 1. So, Serial.println(i) displays
the value 1 in the Serial Monitor. The next time through the loop,
i++ has made the value of
i
increase by 1. After a delay (so you can watch the individual values appear in the Serial
Monitor), the
for statement checks to make sure the condition i <= 10 is still true. Since i
now stores 2, it is true since 2 is less than 10, so it allows the code block to repeat again. This
keeps repeating, but when
i gets to 11, it does not execute the code block because it’s not
true according to the
i <= 10 condition.
Adjust Initialization, Condition, and Increment
As mentioned earlier, i++ uses the ++ increment operator to add 1 to the i variable each
time through the
for loop. There are also compound operators for decrement --, and
compound arithmetic operators like
+=, -=, *=, and /=. For example, the += operator can be
used to write i = i + 1000 like this:
i+=1000.
Save your sketch, then save it as CountHigherInSteps.
Replace the
for statement in the sketch with this:
for(int i = 5000; i <= 15000; i+=1000)
Run the modified sketch and watch the output in the Serial Monitor.
A Loop that Repeats While a Condition is True
In later chapters, you’ll use a while loop to keep repeating things while a sensor returns a
certain value. We don’t have any sensors connected right now, so let’s just try counting to
ten with a
while loop:
int i = 0;
while(i < 10)
{
i = i + 1;
Serial.println(i);
delay(500);
}