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)
- Upload 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); }
Want to condense your code a little? You can use the increment operator (++) to increase the value of i inside the Serial.println statement. Notice that ++ is on the left side of the i variable in the example below. When ++ is on the left of a variable, it adds 1 to the value of i before the println function executes. If you put ++ to the right, it would add 1 after println executes, so the display would start at zero.
int i = 0; while(i < 10) { Serial.println(++i); delay(500); }
The loop function, which must be in every Arduino sketch, repeats indefinitely. Another way to make a block of statements repeat indefinitely in a loop is like this:
int i = 0; while(true) { Serial.println(++i); delay(500); }
So why does this work? A while loop keeps repeating as long as what is in its parentheses evaluates as true. The word ’true’ is actually a pre-defined constant, so while(true) is always true, and will keep the while loop looping. Can you guess what while(false) would do?
- Try these three different while loops in place of the for loop in the CountToTen sketch.
- Also try one instance using Serial.println(++i), and watch what happens in the Serial Monitor.
- Try while(true) and while(false) also.