Flight control: PID, cascades, filters and loops · 5 MIN READ
Complementary filter: fusing a fast drifting signal with a slow noisy one
Estimate altitude by integrating a biased vertical velocity at 50 Hz and correcting it with the 5 Hz barometer, choose the time constant tau and alpha = tau / (tau + dt), and measure the result as RMSE against the true altitude.
Sensors on a drone are either fast and smooth but drifting, or absolute but noisy and slow. Integrating an inertial vertical velocity gives a clean altitude that walks away over time; the barometer never walks away but jumps by tens of centimetres from sample to sample. A complementary filter takes the high frequencies from the first and the low frequencies from the second, with one parameter, the crossover time constant. It costs a few multiplications per step and is the right first estimator to write before a Kalman filter.
drones · A MAP OF THE IDEA
- Integrate fast signal
- Blend with alpha
- Correct on baro sample
- Score RMSE vs truth
Useful when
- A few multiplications per step, no matrices, easy to reason about.
- Real motion passes without lag; each sensor's error is cut where it is large.
Watch out
- A sensor bias leaves a steady error of bias times tau.
- An alpha computed for one rate but applied at another changes tau.
Implementation & operation cost: One state and one parameter per signal, plus a bias state when the fast sensor drifts.
High-pass plus low-pass equals one
The filter is z = alpha * (z + v * dt) + (1 - alpha) * baro with alpha = tau / (tau + dt), where dt is the period at which the blend runs. Seen from the velocity path it is a high-pass filter, seen from the barometer a low-pass filter, both with time constant tau, and the two transfer functions add up to exactly one. A real altitude change therefore passes through without lag, while each sensor's error is suppressed where it is large: barometer noise faster than tau, velocity bias slower than tau. Two consequences follow directly. A constant velocity bias b leaves a steady altitude error of b * tau. White barometer noise of sigma passes with a standard deviation of about sigma * sqrt((1 - alpha) / (1 + alpha)).
Five time constants on one flight
The program flies a take-off to 20 m, three waypoints at 32, 12 and 26 m and a return home. Its velocity sensor is the true climb rate plus a 0.10 m/s bias and 0.10 m/s of noise at 50 Hz, a stand-in for an inertial vertical velocity. The simulator's Telemetry().Velocity is noisy too (0.15 m/s vertically, at 5 Hz) but has no bias, and bias is what makes integration drift, so the lesson models its own sensor. Five filters with different tau run side by side on the same data: each integrates the velocity every step and blends in each new barometer sample with alpha = tau / (tau + 0.2). All estimates are scored at every barometer sample against the true altitude.
package main
// A complementary filter for altitude: a 50 Hz vertical-velocity signal
// with a bias (fast, smooth, drifts when integrated) fused with the 5 Hz
// barometer (no drift, 0.3 m of noise). Several time constants run side by
// side on the same flight and are scored against the true altitude.
import (
"fmt"
"math"
"math/rand/v2"
"gopherforge.app/drone"
)
// Complementary blends a prediction from velocity with a measurement.
type Complementary struct {
Tau float64 // time constant, s: below it trust the baro, above it the velocity
Z float64
}
// Predict integrates the velocity signal over one step.
func (f *Complementary) Predict(vz, dt float64) { f.Z += vz * dt }
// Correct blends in a barometer sample that arrives every period seconds.
func (f *Complementary) Correct(baro, period float64) {
alpha := f.Tau / (f.Tau + period)
f.Z = alpha*f.Z + (1-alpha)*baro
}
type score struct{ sumSq, maxAbs, sum float64 }
func (s *score) add(err float64) {
s.sumSq += err * err
s.sum += err
s.maxAbs = math.Max(s.maxAbs, math.Abs(err))
}
func main() {
sim := drone.New(drone.Config{Seed: 3})
d := sim.Drone()
noise := rand.New(rand.NewPCG(3, 33))
const bias, sigma = 0.10, 0.10 // velocity sensor: m/s bias, m/s noise
const baroPeriod = 0.2
taus := []float64{0.1, 0.3, 1, 3, 10}
filters := make([]*Complementary, len(taus))
for i, tau := range taus {
filters[i] = &Complementary{Tau: tau}
}
deadReckoned := 0.0
scores := make([]score, len(taus)+2) // baro, dead reckoning, filters
var lastBaro float64
var samples int
estimate := func(float64) {
st := d.State()
vz := st.Vel.Z + bias + sigma*noise.NormFloat64()
dt := sim.Dt()
deadReckoned += vz * dt
for _, f := range filters {
f.Predict(vz, dt)
}
tel := d.Telemetry()
if tel.Time > lastBaro { // a new barometer sample
lastBaro = tel.Time
truth := st.Pos.Z
scores[0].add(tel.BaroAlt - truth)
scores[1].add(deadReckoned - truth)
for i, f := range filters {
f.Correct(tel.BaroAlt, baroPeriod)
scores[i+2].add(f.Z - truth)
}
samples++
}
}
d.Arm()
d.TakeOff(20)
sim.RunUntil(40, func(t float64) bool { estimate(t); return d.State().Mode == drone.Hold })
for _, wp := range []drone.Vec3{{X: 40, Z: 32}, {X: 40, Y: 40, Z: 12}, {Y: 40, Z: 26}} {
d.GoTo(wp)
sim.RunUntil(90, func(t float64) bool { estimate(t); return d.Arrived() })
}
d.ReturnHome()
sim.RunUntil(120, func(t float64) bool { estimate(t); return d.State().Landed })
fmt.Printf("%.0f s flight, %d baro samples; velocity bias %.2f m/s\n", sim.Time(), samples, bias)
fmt.Printf("%-23s %8s %8s %8s\n", "estimate", "RMSE", "max", "mean")
names := []string{"raw baro", "integrated velocity"}
for _, tau := range taus {
alpha := tau / (tau + baroPeriod)
names = append(names, fmt.Sprintf("tau %4.1f s, alpha %.3f", tau, alpha))
}
for i, s := range scores {
n := float64(samples)
fmt.Printf("%-23s %6.2f m %6.2f m %6.2f m\n", names[i], math.Sqrt(s.sumSq/n), s.maxAbs, s.sum/n)
}
sim.Save()
}The raw barometer has an RMSE of 0.31 m, close to its specified 0.3 m, with a worst sample 0.87 m off. Integrated velocity alone drifts to an RMSE of 2.93 m and a mean of 2.55 m, the 0.10 m/s bias accumulating over the 51 s flight. tau 0.1 s still passes much of the barometer noise (0.22 m); tau 1.0 s is best at 0.15 m, with a mean error of 0.12 m, close to b * tau = 0.10 m. Longer constants trade noise for bias: tau 3.0 s has a mean of 0.30 m and tau 10.0 s 0.82 m, still on its way to 1.0 m when the flight ends.
Choosing tau, and removing the bias
Choose tau where the two error sources cross: shorter than the time over which the fast sensor drifts noticeably, longer than the period over which the slow sensor's noise averages out. Logged flights make this concrete: replay the log through several values, as the program does, and pick the bottom of the curve. If the bias can be estimated, tau can grow. With an accelerometer as the fast sensor, a third-order complementary filter integrates acceleration to velocity and velocity to altitude, and feeds the barometer error back into all three states, including a bias estimate, which removes the b * tau offset.
// Accelerometer-driven altitude filter with a bias estimate.
// Choosing K1 = 3/tau, K2 = 3/tau^2, K3 = 1/tau^3 puts all three
// error poles at -1/tau.
func (f *Alt3) Predict(accZ, dt float64) {
f.V += (accZ - f.Bias) * dt
f.Z += f.V * dt
}
func (f *Alt3) Correct(baro, period float64) {
e := baro - f.Z
f.Z += f.K1 * e * period
f.V += f.K2 * e * period
f.Bias -= f.K3 * e * period
}If the accelerometer reads high, the predicted altitude climbs above the barometer, e turns negative, and the bias estimate grows until the prediction stops running away. The error dynamics have the characteristic polynomial s^3 + K1 s^2 + K2 s + K3, so the suggested gains make it critically damped with one time constant.
Where complementary filters live, and how they fail
Small flight controllers have long used complementary filters for attitude (gyro plus accelerometer) and altitude; PX4 and ArduPilot now run extended Kalman filters (EKF2, EKF3), but the complementary filter remains the tool of choice in companion and ground code: smoothing a rangefinder with inertial velocity, blending visual odometry with GPS for display, cleaning telemetry plots. Typical bugs: alpha computed for one rate and applied at another (computed for 50 Hz but applied per 5 Hz sample makes tau ten times longer); blending a held, stale sample at every fast step; starting the state at zero instead of the first absolute sample; mixing a sea-level altitude with a take-off-relative one; and forgetting that propeller wash and ground effect bias a barometer near the ground.
Fly it in GopherForge
Start from New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go may stay) and Run. The console prints the RMSE table; Output replays the flight with its climbs and descents in the altitude strip. Change the bias, the noise or the list of taus at the top of main and watch the best time constant move: with a smaller bias the optimum shifts to longer tau, with more barometer noise as well.
TAKE THIS WITH YOU
A complementary filter trusts the fast sensor above 1/tau and the absolute sensor below it, so real motion passes without lag while barometer noise and velocity drift are both suppressed. Pick tau between the two error sources, and remember that a velocity bias b costs a steady error of b times tau.
Check your understanding
A complementary filter integrates a vertical velocity with a constant bias b and corrects it with a barometer using time constant tau. What altitude error remains in steady flight?
Go to the source
Progress stays in this browser. No account needed.