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
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 , the slope at a single instant. The robot can't measure a single instant, so it uses the slope across one loop:
where is this loop's reading, is last loop's, and 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 in·s. If the next loop has an error of 1.5 in and lasts 0.025 s, it adds . Keep adding one rectangle per loop and you have the integral, :
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 in. In symbols, . This is called forward Euler, and it's how most robot code steps a model ahead.
Every one of these has 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 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, , so each tick covers that distance divided by the ticks in one turn:
Here is the wheel radius and 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: , with . If a vendor writes the ratio the other way around, flip it once here and nowhere else.
Say the motor configuration gives 537.7 counts per output revolution and the wheel is
96 mm across, so . 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.
24033 Alphatronic's FLYSET workshop covers the practical side of loop-time budgeting on an FTC robot.
Open videoTo 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.
// 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:
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;
}
Delete the 4000 ticks is 2.24 m, and the first 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
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.
A debugger pause, a slow vision frame, or a stalled loop gives a The stalled loop itself is skipped, which is fine. The problem is the next one: 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
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.
It's tempting to average the loop times and multiply by that once instead of using each measured
The integral is . Using the average gives , 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.dt. Why isn't that the same number?Show solution
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.
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.
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.
- FTC SDK / FtcRobotController - the runtime environment that turns Java OpMode loops into repeated sensor-read, compute, and actuator-write cycles.
- Game Manual 0: Software - FTC software structure, encoder usage, and practical robot-code organization.
- WPILib: Sampling, controllers, and motion profiles - competition-robotics reference for discrete control, profiles, and units.
- Dairy Foundation Cookbook: Improving Loop Times - FTC-specific measurements, bulk-read reasoning, and motor-write caching tradeoffs that informed the operational guidance above.
- FTC SDK Javadoc:
LynxModule.BulkCachingMode- the contract forAUTO,MANUAL, and clearing the manual cache before another bulk read. - 24033 Alphatronic, Advanced Motion Control & Loop Time Optimization - FTC workshop companion for loop-time budgeting and motion-control implementation details.