Skip to content
RoboLearn
Not completed

Loops and repetition

ProgrammingBeginner25 minPractise loops ↓Before this: Arduino C++ basics

What you’ll learn

  • for loops: repeat a set number of times
  • while loops: 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.

Finished this lesson?