Programming
The control loop: a steady beat
See it first
Algorithm teardown
Inside a balance control loop
The teardown opens on its “The loop” mode, which shows this principle. Drag to turn it.
One step at a time
Step by step
The control loop: a steady beat
Step 1 of 5
Wait for the tick
A timer fires every 2 ms; not delay(), which ignores how long the rest took.
In words
A controller is designed assuming Δt is constant. If one loop runs late because of a log print or Wi-Fi, the derivative comes out wrong and the motor command jumps.
So fast work and slow work are kept apart: the control loop runs from a timer or a high-priority task; display and networking live in another task, and every loop checks whether it finished on time.
The formula
Δt = 1 / f_loop
In code
const float DT = 0.002f; // 500 Hz
void loop() {
waitForTick(); // a timer, not delay()
float tilt = imu.readTilt(); // 1. read
float u = controller(tilt, DT); // 2. compute
motor.setTorque(u); // 3. write
if (overran()) faults++; // 4. check the timing
}Where you meet this in a robot
In the balance-loop teardown, watch data run around the loop at its beat; in the workshop you tune that loop yourself.