Loops and repetition
What you’ll learn
forloops: repeat a set number of timeswhileloops: repeat while something is true- How the main
loop()fits with these, and how to avoid freezing your robot
for loops
for (int i = 0; i < 5; i++) { // runs 5 times, with i = 0, 1, 2, 3, 4}The three parts: start (int i = 0), keep going while (i < 5), change each time (i++, add one).
while loops
while (digitalRead(2) == HIGH) { // keep waiting until the button is pressed}A while loop runs as long as its condition is true. If the condition never becomes false, it runs forever.
The forever loop
loop() itself is a forever loop: the Arduino calls it again and again. In a robot, loop() should usually run quickly so the robot keeps re-reading its sensors.
Example: blink 3 times at start-up
void setup() { pinMode(LED_BUILTIN, OUTPUT); for (int i = 0; i < 3; i++) { digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200); }}void loop() {}Example: wait for a start button
void setup() { pinMode(2, INPUT_PULLUP); while (digitalRead(2) == HIGH) {} // wait here until pressed // ...then the robot starts}Example: averaging readings
long total = 0;for (int i = 0; i < 10; i++) total += analogRead(A0);int average = total / 10;Try it
loop() in the robot simulator already repeats 50 times a second. Here’s a counter that uses it:
Robot commands
motors(left, right): wheel power, −100 to 100lineLeft(),lineRight():trueover the black linedistance(): cm to the nearest thing ahead (max 200)distanceLeft(),distanceRight(): cm to the sideslinePosition(): where the line is, −1 (left) to 1 (right), ornullmillis(): milliseconds since Runprint(value): show a message belowsetup()runs once;loop()runs 50 times a second
Count to 10Easy
Write a for loop that prints 1 to 10.
for (int i = 1; i <= 10; i++) Serial.println(i);
Times tableMedium
Print the 7 times table up to 7 × 12.
for (int i = 1; i <= 12; i++) { Serial.print(i); Serial.print(" x 7 = "); Serial.println(i * 7); }
Stop after 5 secondsHard
In the simulator, drive forward and stop after 5 seconds without using millis().
loop() runs 50 times per second. Count the calls.
Show an answer
let ticks = 0;function loop() { ticks++; if (ticks < 250) motors(50, 50); // 250 calls = 5 s else motors(0, 0);}Quick check
Finished this lesson?