498
Control Lab FRC Programming Curriculum
Fundamentals · L05 of 8

Loops

Prereqs: fundamentals-04
Objectives 0 / 3

Hook

A teammate writes code to auto-align the robot. It works perfectly — the arm moves to exactly 90° on the first try. But the moment you enable, the robot dashboard freezes. The joysticks stop responding. The entire robot locks up for two seconds, then continues.

The code wrote a while loop that ran inside periodic():

void periodic() {
    while (arm.getAngle() < 90) {
        arm.setMotor(0.5);
    }
}

The WPILib scheduler calls periodic() every 20ms. The while loop inside it never returns until the arm reaches 90°. While it’s running, nothing else in the robot’s program can execute — no joystick input, no safety checks, nothing.

Core concept

Key Concept

A loop repeats its body until its condition becomes false. On a robot, periodic() is the loop — it runs 50 times per second. Code inside periodic() must return quickly every call; blocking loops go outside or in separate threads.

Walk-through

A while loop:

int i = 0;
while (i < 4) {
    i = i + 1;
}
// i is 4 here

A for loop (equivalent, more compact):

for (int i = 0; i < 4; i++) {
    // body
}

Use for when you know how many iterations you want. Use while when you’re waiting for a condition.

The FRC robot loop

Your robot’s main loop already exists — it’s the WPILib scheduler. It calls periodic() on every subsystem and runs any active commands, 50 times per second. You don’t write that loop; you write what goes inside it.

The correct way to handle the arm alignment above:

void periodic() {
    if (arm.getAngle() < 90) {
        arm.setMotor(0.5);
    } else {
        arm.setMotor(0.0);
    }
}

This checks the condition once per call and returns immediately. The arm moves a little each cycle. Over many cycles, it reaches 90°.

Note

This is exactly the 5-step controller from Lesson 01. periodic() is step 5 — “go back to step 1” — built into the framework.

⚠ Heads up

Never use Thread.sleep(), while (condition) {} blocking loops, or any other delay inside periodic(). The robot scheduler will watchdog-trip and report brownout or loop overrun errors.

Interactive demo

Trace a while loop that counts up. Watch how the condition is checked before each iteration:

Code Tracer
01check: i < 4?// 0 < 4 → true
02total = total + i// 0+0=0
03i = i + 1// i is now 1
04check: i < 4?// 1 < 4 → true
05total = total + i// 0+1=1
06i = i + 1// i is now 2
07check: i < 4?// 2 < 4 → true
08total = total + i// 1+2=3
09i = i + 1// i is now 3
10check: i < 4?// 3 < 4 → true
11total = total + i// 3+3=6
12i = i + 1// i is now 4
13check: i < 4?// 4 < 4 → false, exit
State
i0
total0

Step through to see values update.

Initial state

Try it yourself

⚡ Try it yourself

A different loop with a different condition. Predict the final values of i and product without running it.

int i = 1;
int product = 1;
while (i <= 4) {
    product = product * i;
    i = i + 1;
}
⚡ Check your understanding

What is product when the loop ends?

⚡ Check your understanding

What is i when the loop ends?

Key takeaways

  • A while loop checks its condition before each iteration. When the condition is false, the loop exits immediately.
  • The final value of the loop variable is the first value that failed the condition.
  • periodic() is the robot’s main loop — it must return within ~20ms or the robot misbehaves.
  • Replace blocking while loops in periodic() with stateful conditionals that check once and return.

Common confusions

“I wrote while (true) — now the robot doesn’t respond.” You’ve blocked periodic(). Kill the code (Ctrl+C or disable), remove the blocking loop, and use a state machine or command instead.

“My loop runs one too many or one too few times.” Check whether the condition uses < or <=. Off-by-one errors are extremely common.

Challenge

⚡ Try it yourself

The driver calls a countdown before auto starts. Use a loop to print the numbers 5 down to 1, then print "GO!". No hardcoded print statements — one loop handles the countdown.

Code EditorJavaCtrl+Enter to run
Stuck? Show hint

Start i at 5, loop while i >= 1, decrement each iteration. Print 'GO!' after the loop.

What’s next

In Lesson 05, we’ll look at functions — how to name and reuse blocks of code so you’re not copying the same logic into five different places.