Repetition: while loops

Theory

Imagine the following code that gradually sweeps a servo motor through its range of motion.

void loop() {
  servo1.write(0);
  delay(50);
  servo1.write(10);
  delay(50);
  servo1.write(20);
  delay(50);
  servo1.write(30);
  delay(50);
  servo1.write(40);
  delay(50);
  // ...
}

This code is very repetitive. Surely there is a better way!

Behold, the while loop:

void loop() {
  int angle = 0;

  while (angle < 180) {
    servo1.write(angle);
    angle = angle + 10;
    delay(50);
  }
}

A while loop does the following things:

  1. Check the condition (the question inside the parentheses). If the condition is false, immediately skip the whole block of code inside the curly braces { to }.
  2. If the condition is true, run the code inside the curly braces { to }.
  3. Go back to step 1.

Exercise

Using the same wiring as the previous lesson, implement smooth motion of the servo motor such that it slowly tracks from one side to the other and back again.


This work is licensed under a Creative Commons Attribution 4.0 International License. For comments or corrections, please contact [email protected].