Skip to content

ProgrammingPrograms That Run Forever

Loop Timing

A control loop runs at a steady rate: period = 1 / frequency, and all the work must fit inside it.

Not started Jump to practice

A robot's program is one big loop: read sensors, decide, act, repeat. How often it repeats matters as much as what it does.

Key idea

A control loop runs at a steady rate $f$ (in hertz, times per second). Its period is $T = 1/f$. All the work of one pass must fit inside the period, with room to spare.

Worked example: Period

A loop runs at 50 Hz. What is its period?
  1. $T = 1/50\ \text{s} = 0.02\ \text{s} = 20\ \text{ms}$.

Answer: 20 ms.

Worked example: Will it fit?

Reading the sensors takes 6 ms, the math takes 3 ms, and sending the motor commands takes 2 ms. Can the loop run at 100 Hz?
  1. Work per pass: $6 + 3 + 2 = 11\ \text{ms}$.
  2. At 100 Hz the period is 10 ms.

Answer: No. It needs at least 11 ms, so at most about 90 Hz; 50 Hz would leave a safe margin.

Why it works

Controllers like PID assume the time step $\Delta t$ is steady. If the loop sometimes takes 10 ms and sometimes 40 ms, the math is wrong and the robot shakes. Good code measures the time each pass and waits for the rest of the period, instead of sleeping a fixed amount.

Common mistake

Mixing milliseconds and seconds, or forgetting that the work itself takes time. A loop that does 15 ms of work and then sleeps 20 ms runs every 35 ms, not every 20.

Practice

Pass with 3 right answers, the last 2 in a row. Each right answer earns 2 XP.

Loading practice…

Builds on

Leads to

Sources and further reading