Flight control: PID, cascades, filters and loops · 6 MIN READ
A Kalman filter for altitude and climb rate
Write a 1-D constant-velocity Kalman filter that fuses GPS altitude, barometer and a climb-rate measurement, follow its state, covariance, predict and update steps, tune process and measurement noise, and reject outliers with an innovation gate that cannot lock out the truth.
A complementary filter has a fixed blend. A Kalman filter computes the blend at every step from its own uncertainty: right after start-up it trusts the measurements almost completely, once it has converged it leans on its model, and it weighs a 1.2 m GPS altitude against a 0.3 m barometer by their variances. It also estimates states it does not measure, such as the climb rate from altitude samples alone, fuses a direct measurement of them when one exists, and says how surprising each sample is, which is the basis for rejecting glitches. PX4's EKF2 and ArduPilot's EKF3 run the same predict-update cycle with many more states.
drones · A MAP OF THE IDEA
- Predict x and P each step
- Gate the innovation
- Update with K = P/(P+R)
- Reset after many rejects
Useful when
- Weights sensors by their noise and adapts the gain as it converges.
- Estimates unmeasured states such as climb rate, with an uncertainty.
Watch out
- An overconfident filter gates out good data and diverges.
- Q is a modelling knob; a wrong model cannot be tuned away entirely.
Implementation & operation cost: A small state vector, a covariance update per step, and log-driven tuning of Q, R and the gates.
State, covariance, predict, update
The state is x = [altitude, climb rate] and P is its 2x2 covariance. Predict assumes constant velocity: altitude += climb rate * dt, and P = F P F^T + Q, where Q models an unknown acceleration with variance q as q * [[dt^4/4, dt^3/2], [dt^3/2, dt^2]]. Update with an altitude sensor (H = [1 0]) forms the innovation y = z - altitude and its predicted variance S = P00 + R, computes the gain K = [P00 / S, P10 / S], adds K * y to the state and shrinks P to (I - K H) P. R is the sensor's noise variance: 1.2^2 m^2 for the simulator's GPS altitude and 0.3^2 for its barometer. A sensor that measures the climb rate uses H = [0 1]: the same equations then pick row and column 1 instead of 0. Sensors arriving together are fused one after the other. With 2x2 matrices, float64 and plain arrays are enough; larger filters use the Joseph form of the covariance update to keep P symmetric and positive.
Five filters on one flight
The program predicts at 50 Hz and updates at 5 Hz with the GPS altitude and then the barometer, over a flight with climbs to 35 m and descents to 20 m. Three barometer samples are corrupted on purpose (+8 m twice, -6 m once), as a pressure spike or a sensor glitch would. Five filters start from P = diag(100, 25): Q 0.5, Q 10 and Q 300 with a 4-sigma innovation gate, Q 10 without a gate, and a gated Q 10 filter that also fuses the telemetry's climb rate (0.15 m/s of noise) with H = [0 1]. A gated filter that rejects five samples in a row from one sensor resets that state to the sensor. The program prints the convergence of the Q 10 filter's barometer gains and an error table against the true state.
package main
// A 1-D constant-velocity Kalman filter for altitude and climb rate, fed at
// 5 Hz by the simulator's GPS altitude (about 1.2 m of slowly wandering
// error) and barometer (0.3 m, three glitches injected); one filter also
// fuses the telemetry's climb rate (0.15 m/s of noise).
import (
"fmt"
"math"
"gopherforge.app/drone"
)
// Sensors, and the state each one measures: H = [1 0] for altitude,
// H = [0 1] for climb rate.
const (
GPS = iota
Baro
Vel
)
var measures = [3]int{GPS: 0, Baro: 0, Vel: 1}
// Kalman estimates X = [altitude m, climb rate m/s] with covariance P.
type Kalman struct {
X [2]float64
P [2][2]float64
Q float64 // variance of unmodelled acceleration, (m/s^2)^2
R [3]float64 // measurement variance per sensor
Gate float64 // reject innovations beyond Gate standard deviations; 0 = off
MaxMisses int // consecutive rejections before a reset
misses [3]int
Rejected, Resets int
}
func NewKalman(q, gate float64) *Kalman {
return &Kalman{
P: [2][2]float64{{100, 0}, {0, 25}}, // we know nothing yet
Q: q,
R: [3]float64{GPS: 1.2 * 1.2, Baro: 0.3 * 0.3, Vel: 0.15 * 0.15},
Gate: gate,
MaxMisses: 5,
}
}
// Predict moves the state forward by dt assuming constant velocity, and
// grows the covariance by the acceleration the model ignores.
func (k *Kalman) Predict(dt float64) {
k.X[0] += k.X[1] * dt
p := k.P
p00 := p[0][0] + dt*(p[0][1]+p[1][0]) + dt*dt*p[1][1]
p01 := p[0][1] + dt*p[1][1]
p10 := p[1][0] + dt*p[1][1]
dt2 := dt * dt
k.P = [2][2]float64{
{p00 + k.Q*dt2*dt2/4, p01 + k.Q*dt2*dt/2},
{p10 + k.Q*dt2*dt/2, p[1][1] + k.Q*dt2},
}
}
// Update fuses one measurement of state i = measures[sensor]. It returns
// the gains applied to altitude and climb rate (zero when rejected).
func (k *Kalman) Update(sensor int, z float64) (k0, k1 float64) {
i, r := measures[sensor], k.R[sensor]
y := z - k.X[i] // innovation
s := k.P[i][i] + r // its predicted variance
if k.Gate > 0 && y*y > k.Gate*k.Gate*s {
k.misses[sensor]++
if k.misses[sensor] < k.MaxMisses {
k.Rejected++
return 0, 0
}
// The sensor has disagreed for a second: we are probably the ones
// who are wrong. Take its value and forget our confidence.
k.Resets++
k.misses[sensor] = 0
k.X[i] = z
k.P[0][1], k.P[1][0] = 0, 0
k.P[i][i] = r
k.P[1-i][1-i] += 4
return 0, 0
}
k.misses[sensor] = 0
k0, k1 = k.P[0][i]/s, k.P[1][i]/s
k.X[0] += k0 * y
k.X[1] += k1 * y
p := k.P // P = (I - K H) P, where H picks row i
k.P = [2][2]float64{
{p[0][0] - k0*p[i][0], p[0][1] - k0*p[i][1]},
{p[1][0] - k1*p[i][0], p[1][1] - k1*p[i][1]},
}
return k0, k1
}
type rms struct{ sum float64 }
func (r *rms) add(e float64) { r.sum += e * e }
func (r rms) of(n int) float64 { return math.Sqrt(r.sum / float64(n)) }
// glitch adds pressure spikes to a few barometer samples.
func glitch(sample int) float64 {
switch sample {
case 120, 121:
return 8
case 200:
return -6
}
return 0
}
func main() {
sim := drone.New(drone.Config{Seed: 4})
d := sim.Drone()
names := []string{"Q 0.5, gate 4", "Q 10, gate 4", "Q 300, gate 4", "Q 10, no gate", "Q 10, gate 4, +vel"}
filters := []*Kalman{NewKalman(0.5, 4), NewKalman(10, 4), NewKalman(300, 4), NewKalman(10, 0), NewKalman(10, 4)}
fuseVel := []bool{false, false, false, false, true}
altErr := make([]rms, len(filters))
velErr := make([]rms, len(filters))
var gpsErr, baroErr, diffErr, velErr0 rms
var lastTel, prevBaro float64
var samples int
var gains [][3]float64
estimate := func(float64) {
for _, k := range filters {
k.Predict(sim.Dt())
}
tel := d.Telemetry()
if tel.Time <= lastTel {
return
}
lastTel = tel.Time
samples++
baro := tel.BaroAlt + glitch(samples)
st := d.State()
for i, k := range filters {
k.Update(GPS, tel.GPS.Z)
kz, kv := k.Update(Baro, baro)
if fuseVel[i] {
k.Update(Vel, tel.Velocity.Z)
}
if i == 1 && (samples <= 3 || samples == 10 || samples == 50) {
gains = append(gains, [3]float64{float64(samples), kz, kv})
}
altErr[i].add(k.X[0] - st.Pos.Z)
velErr[i].add(k.X[1] - st.Vel.Z)
}
gpsErr.add(tel.GPS.Z - st.Pos.Z)
baroErr.add(baro - st.Pos.Z)
velErr0.add(tel.Velocity.Z - st.Vel.Z)
if samples > 1 {
diffErr.add((baro-prevBaro)/0.2 - st.Vel.Z)
}
prevBaro = baro
}
d.Arm()
d.TakeOff(15)
sim.RunUntil(40, func(t float64) bool { estimate(t); return d.State().Mode == drone.Hold })
for _, wp := range []drone.Vec3{{X: 30, Z: 35}, {X: 30, Y: 30, Z: 20}, {Y: 30, Z: 28}} {
d.GoTo(wp)
sim.RunUntil(90, func(t float64) bool { estimate(t); return d.Arrived() })
sim.Run(5, estimate)
}
d.ReturnHome()
sim.RunUntil(120, func(t float64) bool { estimate(t); return d.State().Landed })
fmt.Println("barometer gains of the Q 10 filter:")
for _, g := range gains {
fmt.Printf(" update %2.0f: altitude %.3f, climb rate %.3f /s\n", g[0], g[1], g[2])
}
fmt.Printf("%d samples at 5 Hz over %.0f s, 3 baro glitches injected\n", samples, sim.Time())
fmt.Printf("%-25s %8s %10s %8s %6s\n", "estimate", "alt RMSE", "rate RMSE", "rejected", "resets")
fmt.Printf("%-25s %6.2f m %10s\n", "raw GPS Z", gpsErr.of(samples), "-")
fmt.Printf("%-25s %6.2f m %6.2f m/s\n", "raw baro", baroErr.of(samples), diffErr.of(samples-1))
fmt.Printf("%-25s %8s %6.2f m/s\n", "raw telemetry vel Z", "-", velErr0.of(samples))
for i, k := range filters {
fmt.Printf("%-25s %6.2f m %6.2f m/s %8d %6d\n", "Kalman "+names[i], altErr[i].of(samples), velErr[i].of(samples), k.Rejected, k.Resets)
}
sim.Save()
}The first barometer update has an altitude gain of 0.940, because the GPS update just before it already cut the variance from 100 m^2; the second has a climb-rate gain of 4.017 /s as the filter learns velocity from the first difference. By update 10 the gains are 0.395 and 0.504, by update 50 0.384 and 0.498: converged. Raw GPS altitude has an RMSE of 1.14 m, raw barometer 0.77 m including the glitches, and its differences give a 4.49 m/s climb rate; the telemetry's climb rate is off by 0.16 m/s. Q 10 with the gate reaches 0.22 m and 0.49 m/s, rejecting exactly the 3 glitches. Q 0.5 lags every manoeuvre: 20 rejections, 3 resets, 0.54 m. Q 300 follows the noise (0.67 m/s), and without a gate the glitches pull Q 10 to 0.51 m. Fusing the climb rate brings altitude to 0.13 m with a rate error of 0.17 m/s, about the measurement's own; its 5 rejections are the 3 glitches and two climb-rate samples at the start of the descent from 35 m, where the drone accelerates harder than Q allows.
Tuning Q and R
R comes from the sensor: log it at rest and measure the variance, or start from the datasheet. Q is the modelling error, everything the constant-velocity model ignores. Here the autopilot accelerates at up to 8 m/s^2 when it starts a climb, so q of about 10 (m/s^2)^2 fits, and the table shows both failure directions. Too small a Q makes the filter overconfident: it lags manoeuvres, its innovations grow, and with a gate it starts rejecting good data. Too large a Q makes it follow every measurement, and the climb rate becomes noisy. A consistency check helps: innovations should average zero, and y^2 / S should average about 1. Better than inflating Q is a better model: feed the accelerometer into the prediction as EKF2 does with the IMU, so Q only covers accelerometer noise and bias. R also assumes white noise, and the simulator's GPS error, like real GNSS, wanders slowly (a Gauss-Markov process with a 20 s time constant), so a filter that treats it as white trusts the GPS too much. The barometer dominates here; when GPS must carry the altitude, add its slowly varying error as a state, as full navigation filters do.
Innovation gates and their trap
Before an update, y^2 / S tells how surprising the sample is in units of its expected variance. With Gaussian noise a 3-sigma gate still rejects 0.27% of good samples; models are never perfect, so practical gates are often 3 to 5 sigma, and PX4's EKF2 exposes them as parameters such as EKF2_BARO_GATE. The trap is a filter that has drifted: then the truth looks like an outlier, every sample is rejected and the estimate never recovers. Count consecutive rejections per sensor and reset to the sensor after a timeout, as production estimators do, and log every rejection and reset.
i, r := measures[sensor], k.R[sensor]
y := z - k.X[i] // innovation
s := k.P[i][i] + r // its predicted variance
if k.Gate > 0 && y*y > k.Gate*k.Gate*s {
k.misses[sensor]++
if k.misses[sensor] < k.MaxMisses {
k.Rejected++
return 0, 0
}
k.Resets++ // the sensor kept disagreeing: trust it
k.misses[sensor] = 0
k.X[i] = z
k.P[0][1], k.P[1][0] = 0, 0
k.P[i][i] = r
k.P[1-i][1-i] += 4
return 0, 0
}The test compares y^2 with Gate^2 * S, so Gate is in standard deviations and no square root is needed. After MaxMisses rejections in a row the filter assumes it is the one that is wrong: it takes the measurement as the value of the state that sensor measures, with the sensor's variance, drops the correlation and widens the other state's variance so the next samples can correct it.
Fly it in GopherForge
Create New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay) and Run. The console shows the gains and the error table; Output replays the flight, whose climbs and descents are what the constant-velocity model has to follow. Edit the glitch function, change Q or the gate in the NewKalman calls, set the gate to 3, or fuse the climb rate in every filter, and watch the errors, rejections and resets change.
TAKE THIS WITH YOU
A Kalman filter computes its blend from the covariance: high gain while uncertain, a steady gain once converged, weights set by each sensor's variance. Tune R from sensor noise and Q from what the model ignores, gate innovations in standard deviations, and reset after repeated rejections so a gate cannot lock out the truth.
Check your understanding
In a 1-D altitude Kalman filter, what determines the gain, the fraction of each barometer innovation applied to the estimate?
Go to the source
Progress stays in this browser. No account needed.