Skip to main content

From Math to a Loop

Mediumdifficulty

Control lessons are full of velocities, accelerations, and accumulated error. The Control Hub never sees any of those directly. It sees a number from an encoder each time through the loop, and it has to build everything else out of those numbers. Getting this translation wrong is one of the most common reasons controller code that looks right misbehaves on a real robot.

What the hub actually gives you​

Four facts about the hardware shape everything else:

  • It loops. The Control Hub runs read → compute → write somewhere around 20 to 50 times a second. Between loops it knows nothing new.
  • It counts ticks. An encoder reports counts, not inches or radians. PID gains, feedforward, and odometry mean nothing until those counts are converted.
  • The loop time wobbles. Vision frames, logging, and garbage collection make some loops longer than others. Code that assumes a fixed period gets every time-based calculation slightly wrong.
  • Hardware access takes time. Every encoder, IMU, and sensor read is a trip to the hub, and so is every motor command. Before blaming the math, measure the loop period and count the hub trips.

Handle those four and the math in the rest of the site carries over to the robot as written.

Rates of change from two readings​

Start with a number you can check. On one loop the lift encoder converts to 12.0 in. On the next loop, 0.020 s later, it reads 12.5 in. The lift moved 0.5 in in 0.020 s, so it's moving at

12.5−12.00.020=25 in/s.\frac{12.5 - 12.0}{0.020} = 25 \text{ in/s}.

That's the slope formula from algebra, rise over run, with position as the rise and time as the run. Calculus writes the exact version as dx/dtdx/dt, the slope at a single instant. The robot can't measure a single instant, so it uses the slope across one loop:

dxdt≈xk−xk−1Δt\frac{dx}{dt} \approx \frac{x_k - x_{k-1}}{\Delta t}

where xkx_k is this loop's reading, xk−1x_{k-1} is last loop's, and Δt\Delta t is the time between them.

Running totals go the other way. Suppose a controller wants to add up how much error it has seen over time. If the error is 2 in for one 0.020 s loop, that loop contributes 2×0.020=0.042 \times 0.020 = 0.04 in·s. If the next loop has an error of 1.5 in and lasts 0.025 s, it adds 0.03750.0375. Keep adding one rectangle per loop and you have the integral, ∫e dt\int e\,dt:

∫e dt≈∑kek Δtk\int e\,dt \approx \sum_k e_k\,\Delta t_k

Predicting forward uses the same idea. If the lift is at 12.5 in and moving at 25 in/s, then one 0.020 s loop later it should be near 12.5+25×0.020=13.012.5 + 25 \times 0.020 = 13.0 in. In symbols, xk+1=xk+vk Δtx_{k+1} = x_k + v_k\,\Delta t. This is called forward Euler, and it's how most robot code steps a model ahead.

Every one of these has Δt\Delta t in it. If the loop took 35 ms and your code assumes 20 ms, every velocity, integral, and prediction is wrong by the same factor, which is why Δt\Delta t is always measured.

Ticks to real units​

The conversion you'll use most turns encoder ticks into distance. One full turn of a wheel covers its circumference, 2πr2\pi r, so each tick covers that distance divided by the ticks in one turn:

meters=ticks×2πrNout\text{meters} = \text{ticks} \times \frac{2\pi r}{N_{\text{out}}}

Here rr is the wheel radius and NoutN_{\text{out}} is the encoder counts per turn of the output shaft, the one the wheel is on. Datasheets often give counts per turn of the motor shaft instead. With a 20:1 gearbox the motor turns 20 times for every output turn, so the output sees 20 times as many counts: Nout=Nmotor×GN_{\text{out}} = N_{\text{motor}} \times G, with G=20G = 20. If a vendor writes the ratio the other way around, flip it once here and nowhere else.

Math
Worked example

Say the motor configuration gives 537.7 counts per output revolution and the wheel is 96 mm across, so r=0.048 mr = 0.048\ \text{m}. One revolution covers 2pi0.048 ~= 0.3016 m, so METERS_PER_TICK = 0.3016 / 537.7 ~= 0.000561 m/tick.

How fast you have to sample​

Between loops the robot is blind and acts on its last reading. Increase dt in the demo and watch a smooth signal turn into a staircase and then, past a certain point, into something that doesn't resemble the original at all.

Live demoWhat your robot loop actually sees
true (continuous) signalsampled & held every dtwhat the code reconstructsnow
A typical FTC loop is ~20–50 ms.
Loop rate: —Samples / wave: —Quality: —
Advanced Motion Control & Loop Time Optimization -

24033 Alphatronic's FLYSET workshop covers the practical side of loop-time budgeting on an FTC robot.

Open video
Math
The Nyquist limit

To see a motion that repeats f times a second at all, you have to sample faster than 2f. Below that, the motion aliases: it looks slower than it is, or disappears. Seeing a motion isn't the same as controlling it, though. Controllers usually need to run many times faster than the motion they're correcting, so a loop that's too slow can't control a fast, springy mechanism no matter how the gains are tuned.

Measure dt and convert units in one place​

Measure the loop time every iteration, and do the tick conversion in exactly one place so every controller downstream works in real units.

FTCUnits, defined once
// Never recomputed inline, never retyped in a subsystem.
static final double WHEEL_R = 0.048; // meters
static final double TICKS_PER_OUTPUT_REV = 537.7;
static final double METERS_PER_TICK =
2 * Math.PI * WHEEL_R / TICKS_PER_OUTPUT_REV;
static final double MAX_VALID_DT = 0.25; // s; beyond this, something stalled

Then measure the loop time every loop, and grab a first reading before computing any velocity:

FTCReal loop time, with a seed and a dt guard
private final ElapsedTime timer = new ElapsedTime();
private boolean havePreviousSample;
private double lastMeters, integral, distanceFromVelocity, derivative;

void update(double error) {
double meters = motor.getCurrentPosition() * METERS_PER_TICK;

if (!havePreviousSample) {
lastMeters = meters;
timer.reset();
havePreviousSample = true;
return; // no dt yet, so no derivative yet
}

double dt = timer.seconds();
timer.reset();

if (!Double.isFinite(dt) || dt <= 0 || dt > MAX_VALID_DT) {
lastMeters = meters; // RE-SEED, do not just skip
derivative = 0;
return;
}

derivative = (meters - lastMeters) / dt; // m/s over THIS interval
integral += error * dt; // this rectangle's own dt
distanceFromVelocity += derivative * dt;
lastMeters = meters;
}
ExerciseWhat the seed prevents

Delete the havePreviousSample branch. lastMeters starts at 0, but the encoder might already read 4000 ticks when the OpMode starts. What velocity does the first loop compute, and what does the controller do with it?

Show solution

4000 ticks is 2.24 m, and the first dt is about 20 ms, so the computed velocity is around 112 m/s, roughly 250 mph. A D term sees that once and slams the output to its limit before the mechanism has moved. Waiting one loop for a real first reading avoids it.

ExerciseWhy re-seed instead of skip

A debugger pause, a slow vision frame, or a stalled loop gives a dt far outside the valid range. Suppose the loop stalls for 2 seconds while the mechanism keeps moving at 1 m/s. What happens on the loop after the stall if the guard just skips without updating lastMeters?

Show solution

The stalled loop itself is skipped, which is fine. The problem is the next one: lastMeters is still from before the stall, so the code divides 2 m of travel by a 20 ms dt and reports 100 m/s instead of 1 m/s. Re-seeding throws away one velocity reading. Skipping without re-seeding corrupts the next one.

ExerciseWhy the integral cannot use an average dt

It's tempting to average the loop times and multiply by that once instead of using each measured dt. Why isn't that the same number?

Show solution

The integral is ∑eiΔti\sum e_i \Delta t_i. Using the average gives Δtˉ∑ei\bar{\Delta t} \sum e_i, and the two only match if the error has nothing to do with loop time. It usually does: the slowest loops happen when the robot is busiest, which is often when the error is largest. There's also a simpler problem. The controller needs the integral now, not after the match.

Warn
What a hard-coded dt does

If you assume dt = 0.02 but the loop really takes 35 ms, the integral and the derivative are both off by a factor of 1.75, in opposite directions. The integral grows about 1.75 times too slowly, because you add 0.02 s of area for every 0.035 s that actually passed. The derivative reads about 1.75 times too large, because you divide a 35 ms change by 20 ms. Nothing throws an error, and the symptoms are easy to mistake for integral windup.

Treat loop time as a measured hardware budget​

The dt above goes into every controller calculation, but one loop's dt doesn't tell you whether the robot is consistently responsive. For that, keep a short window of loop periods. One slow loop is usually harmless. A high average, a bad worst case, or a big gap between the two is worth chasing.

FTCLoop-time window: average and worst period
private static final int LOOP_WINDOW = 100;
private final ElapsedTime loopTimer = new ElapsedTime();
private boolean haveLoopPeriod;
private int loopSamples;
private double loopSumMs, loopWorstMs;

@Override
public void start() {
loopTimer.reset(); // do not count init time as a control period
haveLoopPeriod = false;
}

void loop() {
double periodMs = loopTimer.milliseconds(); // duration since the previous loop began
loopTimer.reset();
if (haveLoopPeriod) recordLoopPeriod(periodMs);
haveLoopPeriod = true;

// One hardware cycle: refresh -> read -> compute -> write.
updateRobot();
}

void recordLoopPeriod(double periodMs) {
if (!Double.isFinite(periodMs) || periodMs <= 0) return;

loopSamples++;
loopSumMs += periodMs;
loopWorstMs = Math.max(loopWorstMs, periodMs);

if (loopSamples == LOOP_WINDOW) {
telemetry.addData("loop avg / worst ms", "%.1f / %.1f",
loopSumMs / LOOP_WINDOW, loopWorstMs);
loopSamples = 0;
loopSumMs = 0;
loopWorstMs = 0;
}
}

This is for diagnosis only. Controllers should keep using each loop's own dt. The window is how you notice that adding vision, logging, or a new subsystem made the loop slower or less steady.

One owner for bulk caching​

A lot of slow loops are slow because of hub communication, not arithmetic. Reads from the same REV hub can share one bulk read (I2C devices are separate). Start with the SDK's BulkCachingMode.AUTO. Only switch to MANUAL when one piece of code clearly owns the cache and clears it before every hardware cycle. If Road Runner, Pedro, or another framework already manages this, don't set it again in a subsystem.

FTCManual bulk caching: one clear at the start of each cycle
private List<LynxModule> hubs;

// import com.qualcomm.hardware.lynx.LynxModule;
// import java.util.List;

void initBulkCaching() {
hubs = hardwareMap.getAll(LynxModule.class);
for (LynxModule hub : hubs) {
hub.setBulkCachingMode(LynxModule.BulkCachingMode.MANUAL);
}
}

void updateRobot() {
for (LynxModule hub : hubs) {
hub.clearBulkCache(); // exactly once, before this cycle's reads
}

readSensors(); // eligible hub reads now share fresh cached data
computeCommands();
writeActuators();
}

Forgetting to clear is worse than being slow, because the next loop reads old encoder or IMU data. Don't scatter clearBulkCache() across subsystems, and don't switch to MANUAL just because it sounds faster. Profile first, then give one component the job.

Caching motor writes, if you need to​

Sending the same motor power or servo position every loop adds hub traffic without changing anything. Skipping repeated writes can help, but a wrapper that ignores small changes also adds a deadband to every controller behind it. Only add one after measurements show writes are the bottleneck, write down the threshold, test it on a closed-loop mechanism, and keep it at the hardware boundary.

That's the end of Module 1. Module 2 starts with the actuator all of this is controlling: How a Motor Works.

Sources & references