Skip to main content
Torqheart
← Foundations

Programming

The control loop: a steady beat

Most robot code is a loop at a fixed beat: read sensors → compute → command motors → wait for the next tick. A steady beat matters as much as the formula.

See it first

Algorithm teardown

Inside a balance control loop

Open full screen
FreeThe loop, P and D🔒 In the workshopLate sensor, Motor limitsAn algorithm has no housing to open. What we take apart is its loop: the blocks it is made of and the numbers flowing between them, next to the motion they produce in 3D (drag to turn it). A teaching model; every number's source is in sources.md.

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.