Flight control: PID, cascades, filters and loops · 5 MIN READ
Fixed-rate loops in Go: tickers, jitter, GC and allocations
Run a supervisory control loop at a fixed rate with time.Ticker, understand dropped ticks, jitter and the monotonic clock, keep allocations out of the loop body and prove it with testing.AllocsPerRun, and decide what belongs in firmware instead.
A control loop assumes its dt. When an iteration starts late, the integral and derivative terms are computed with the wrong time step, and a burst of catch-up iterations is worse than a skipped one. Go is a good language for the 10 to 50 Hz supervisory loops of a companion computer or ground station and the wrong one for the kilohertz rate loop inside a flight controller. This lesson runs three loop styles on a virtual clock, so the results are the same on every run, then counts the heap allocations of two versions of a loop body.
drones · A MAP OF THE IDEA
- NewTicker, defer Stop
- dt from monotonic clock
- Zero-alloc loop body
- Count and log overruns
Useful when
- A ticker keeps a fixed grid and never bursts after a stall.
- AllocsPerRun turns "no allocations" into a test you can keep.
Watch out
- Go on Linux cannot promise hard deadlines; fast loops stay in firmware.
- The first tick after a stall is late; dt must come from the clock.
Implementation & operation cost: A ticker, a measured dt, preallocated buffers and a test that pins the allocation count at zero.
What time.Ticker promises
A Ticker delivers ticks on a fixed grid, so the work inside the loop does not stretch the period, and the time package documents that it adjusts the interval or drops ticks to make up for slow receivers: at most one tick waits, the others are lost, and the grid keeps its phase. Since Go 1.23 timer channels are unbuffered and Stop or Reset guarantee that no stale tick is received afterwards, but a receiver that comes back late still gets one tick at once. Two common alternatives behave worse: time.Sleep(period) after the work makes the period work plus period, and a deadline loop that adds the period and sleeps until the deadline without ever skipping runs late iterations back to back after a stall. Whatever the loop, measure dt instead of assuming it.
func run(ctx context.Context, period time.Duration, step func(dt time.Duration)) (overruns int, err error) {
t := time.NewTicker(period)
defer t.Stop()
last := time.Now()
for {
select {
case <-ctx.Done():
return overruns, ctx.Err()
case <-t.C:
now := time.Now()
dt := now.Sub(last) // monotonic: immune to clock changes
last = now
if dt > 2*period {
overruns++
dt = 2 * period // do not integrate a huge step
}
step(dt)
}
}
}time.Now carries a monotonic clock reading and Sub uses it, so an NTP correction of the wall clock cannot produce a negative or huge dt. Overruns are counted for the logs, and dt is limited so that one stall does not turn into one giant integration step in the controller.
Three loops on a virtual clock
Sleeping in a lesson program would make its output depend on the machine, so the program models time with integer durations. Each loop body takes 8 to 12 ms from a seeded generator, and two stalls are injected: a 90 ms blocking log write at 0.6 s and 30 ms of CPU contention at 1.3 s. The sleep loop, the ticker and the catch-up deadline loop each run for 2 s at a 20 ms period. The table counts runs, 20 ms slots in which no iteration started, dropped ticks, the smallest and largest gap between starts, the worst lag behind the tick an iteration serves and the number of stale runs, those more than one period late. Then testing.AllocsPerRun measures two versions of a loop body.
package main
// Loop timing on a virtual clock: three ways to run a 50 Hz control loop
// meet the same jittery workload and two stalls. Then testing.AllocsPerRun
// counts heap allocations of two versions of the loop body.
import (
"fmt"
"math/rand/v2"
"strconv"
"testing"
"time"
)
const (
period = 20 * time.Millisecond // 50 Hz
horizon = 2 * time.Second
)
type stall struct {
at, dur time.Duration
why string
}
var stalls = []stall{
{600 * time.Millisecond, 90 * time.Millisecond, "blocking log write"},
{1300 * time.Millisecond, 30 * time.Millisecond, "CPU contention"},
}
// worker decides how long each loop body takes: 8-12 ms of work plus any
// stall due at the moment it starts. Every loop style gets the same seed.
type worker struct {
rng *rand.Rand
next int
}
func newWorker() *worker { return &worker{rng: rand.New(rand.NewPCG(5, 50))} }
func (w *worker) run(start time.Duration) time.Duration {
d := 8*time.Millisecond + time.Duration(w.rng.IntN(4000))*time.Microsecond
if w.next < len(stalls) && start >= stalls[w.next].at {
d += stalls[w.next].dur
w.next++
}
return d
}
// iteration records when a loop body started and the tick it served.
type iteration struct{ start, sched time.Duration }
// sleepLoop: work, then time.Sleep(period). The period becomes work+period.
func sleepLoop() []iteration {
w := newWorker()
var runs []iteration
for now := time.Duration(0); now < horizon; {
runs = append(runs, iteration{now, -1})
now += w.run(now)
now += period
}
return runs
}
// tickerLoop models time.Ticker: ticks on a fixed grid, at most one tick
// waits for a slow receiver, later ones are dropped.
func tickerLoop() (runs []iteration, dropped int) {
w := newWorker()
var now time.Duration
fire := period
waiting, value := false, time.Duration(0)
for {
for ; fire <= now; fire += period { // ticks that fired while we worked
if waiting {
dropped++
} else {
waiting, value = true, fire
}
}
if !waiting { // block in <-ticker.C until the next tick
now, waiting, value = fire, true, fire
fire += period
}
if now >= horizon {
return runs, dropped
}
waiting = false
runs = append(runs, iteration{now, value})
now += w.run(now)
}
}
// catchUpLoop sleeps until next deadline, then deadline += period. It never
// skips, so after a stall it runs late iterations back to back.
func catchUpLoop() []iteration {
w := newWorker()
var runs []iteration
var now time.Duration
for next := period; ; next += period {
if now < next {
now = next
}
if now >= horizon {
return runs
}
runs = append(runs, iteration{now, next})
now += w.run(now)
}
}
func report(name string, runs []iteration, dropped string) {
hit := make([]bool, horizon/period)
minGap, maxGap := time.Hour, time.Duration(0)
stale, lag := 0, time.Duration(-1)
for i, r := range runs {
hit[r.start/period] = true
if i > 0 {
gap := r.start - runs[i-1].start
minGap, maxGap = min(minGap, gap), max(maxGap, gap)
}
if r.sched >= 0 {
lag = max(lag, r.start-r.sched)
if r.start-r.sched > period {
stale++
}
}
}
empty := 0
for _, h := range hit[1:] {
if !h {
empty++
}
}
worst, staleRuns := "-", "-"
if lag >= 0 {
worst, staleRuns = ms(lag), strconv.Itoa(stale)
}
fmt.Printf("%-9s %4d %6d %8s %8s %8s %8s %6s\n", name, len(runs), empty, dropped, ms(minGap), ms(maxGap), worst, staleRuns)
}
func ms(d time.Duration) string { return strconv.FormatFloat(float64(d)/1e6, 'f', 1, 64) + " ms" }
// ---- allocations in the loop body
type Command struct{ Vx, Vy, Vz, Yaw float64 }
type loopState struct {
window []float64 // last N altitude samples
head int
cmd *Command
last Command
note string
buf []byte
}
// bodyAllocating copies the window, allocates a new command and formats a note
// on every tick.
func bodyAllocating(s *loopState, alt float64) {
w := make([]float64, len(s.window))
copy(w, s.window[1:])
w[len(w)-1] = alt
s.window = w
s.cmd = &Command{Vz: 0.8 * (10 - mean(w))}
s.note = strconv.FormatFloat(s.cmd.Vz, 'f', 2, 64)
}
// bodyReusing writes into a ring buffer, stores the command by value and
// appends the note into a buffer that keeps its capacity.
func bodyReusing(s *loopState, alt float64) {
s.window[s.head] = alt
s.head = (s.head + 1) % len(s.window)
s.last = Command{Vz: 0.8 * (10 - mean(s.window))}
s.buf = strconv.AppendFloat(s.buf[:0], s.last.Vz, 'f', 2, 64)
}
func mean(xs []float64) float64 {
sum := 0.0
for _, x := range xs {
sum += x
}
return sum / float64(len(xs))
}
func main() {
fmt.Printf("virtual clock: %v period (50 Hz) for %v, loop body 8-12 ms\n", period, horizon)
for _, s := range stalls {
fmt.Printf("stall: %v %s at %v\n", s.dur, s.why, s.at)
}
fmt.Printf("%-9s %4s %6s %8s %8s %8s %8s %6s\n", "loop", "runs", "empty", "dropped", "min gap", "max gap", "max lag", "stale")
report("sleep", sleepLoop(), "-")
runs, dropped := tickerLoop()
report("ticker", runs, strconv.Itoa(dropped))
report("catch-up", catchUpLoop(), "0")
s := &loopState{window: make([]float64, 25), buf: make([]byte, 0, 32)}
alt := 9.5
a := testing.AllocsPerRun(1000, func() { bodyAllocating(s, alt) })
b := testing.AllocsPerRun(1000, func() { bodyReusing(s, alt) })
fmt.Printf("allocations per tick: allocating body %.0f, reusing body %.0f\n", a, b)
fmt.Printf("at 50 Hz that is %.0f vs %.0f heap objects a minute\n", a*50*60, b*50*60)
}The sleep loop manages only 63 runs instead of 99, leaving 37 empty slots: its period became the body plus 20 ms (the smallest gap is 28.1 ms). The ticker makes 94 runs and drops 5 ticks; its smallest gap is 18.3 ms, so it never bursts, and only 2 runs are stale, the late tick after each stall, the worse one 80.4 ms late. The catch-up loop makes 99 runs and drops nothing, but its smallest gap is 8.1 ms: after the stall it runs 6 stale iterations back to back on old data. The allocating loop body makes 3 heap allocations per tick, the reusing one 0, which at 50 Hz is 9000 objects a minute against none.
Garbage collection and the loop body
Go's collector runs concurrently with the program. Its stop-the-world phases are short, usually well under a millisecond, but while a cycle runs the background marker uses about a quarter of GOMAXPROCS, and a goroutine that allocates may be drafted into mark assist. A loop body that does not allocate triggers fewer cycles and is not drafted. The allocating body above makes three objects: a slice made with a non-constant length, a *Command stored in a heap object, and the string from strconv.FormatFloat. The reusing body writes into a ring buffer, stores the command by value and appends into a byte slice that keeps its capacity. Find escapes with go build -gcflags=-m, pin the count with testing.AllocsPerRun in a test, and on small boards set GOMEMLIMIT (or debug.SetMemoryLimit) so the runtime collects before the operating system kills the process; GOGC trades memory for collection frequency.
What stays in firmware
Rate and attitude loops run at hundreds of hertz to kilohertz with deadlines in microseconds, on real-time operating systems (NuttX under PX4, ChibiOS under ArduPilot on most boards) with fixed priorities and the IMU's interrupts driving them. A Go process on Linux shares the CPU with the kernel, other processes and the USB and Wi-Fi drivers; a few milliseconds of jitter are normal and occasional spikes of tens of milliseconds happen. That is acceptable for 10 to 50 Hz setpoints when the autopilot has its own timeout and failsafe, which PX4's offboard mode does. Log dt for every tick, keep a histogram, alert on overruns, and design the outer loop so that a missed tick costs accuracy, not safety.
Fly it in GopherForge
This program does not use the simulator: run it in any Go project, or create New project > Robotics and simulation > Drone flight and replace main.go with it (mission.go can stay), then Run and read the console. To connect it to a flight, call bodyReusing from the control function of sim.Run with d.State().Pos.Z: the simulator calls that function at exactly 50 Hz of simulated time, the ideal loop this lesson approximates, and Output replays the flight.
TAKE THIS WITH YOU
Use time.Ticker for fixed-rate loops: its grid does not drift, and after a stall it delivers one late tick and drops the rest instead of bursting. Compute dt from the monotonic clock, keep the loop body free of allocations and prove it with AllocsPerRun, set GOMEMLIMIT on small boards, and leave kilohertz loops to firmware.
Check your understanding
A 50 Hz loop reads from a time.Ticker and one iteration blocks for 90 ms. What happens to the ticks that fell due during the stall?
Go to the source
Progress stays in this browser. No account needed.