Drone software: architecture, MAVLink and telemetry · 6 MIN READ

Sensors and noise: GPS, barometer and IMU, truth against measurement, RMSE and bias

Compare simulated telemetry with the true state over a flight, compute bias and RMSE per sensor, and explain why smoothing one sensor fails and sensor fusion is needed.

Every number a drone reports is an estimate built from imperfect sensors. GPS wanders by metres, a barometer measures altitude changes finely but drifts with the weather, and an IMU measures motion hundreds of times a second but drifts when integrated. Simulation gives you what real flights never do, the truth, so you can measure exactly how wrong each sensor is and in which way.

drones · A MAP OF THE IDEA

  1. Pair report with truth
  2. Error = measured - true
  3. Bias, RMSE, max per axis
  4. Fuse complementary sensors

Useful when

  • Simulation gives exact truth to grade every sensor against.
  • Bias and RMSE separate systematic from random error.

Watch out

  • Slowly wandering GPS error survives averaging and looks like bias.
  • Pairing a report with truth from another instant inflates the error.

Implementation & operation cost: A recording loop that pairs each report with the true state, and three running sums per axis.

01

What each sensor gives you

GNSS gives absolute position and velocity at 5 to 10 Hz; a standalone receiver is good to a metre or a few horizontally and worse vertically, and its errors are correlated over seconds to minutes because they come from multipath, the atmosphere and satellite geometry. RTK with a base station brings that to centimetres. Receivers also measure velocity from Doppler shifts, often to better than 0.1 m/s, with errors that do not wander like position. A barometer turns pressure into altitude with fine resolution, but drifts as the weather and temperature change and is disturbed by propeller wash, ground effect and airspeed. The IMU's accelerometers and gyroscopes run at hundreds of hertz to kilohertz and are excellent over short times, but their biases integrate: velocity error grows with time and position error with its square, and vibration makes it worse. The magnetometer gives heading and is disturbed by motor currents and nearby steel. Each sensor is good where another is weak.

02

Bias, RMSE and maximum error

Define error as measured minus true. The bias is the mean error, the systematic part; the RMSE is the square root of the mean squared error and includes both parts, since RMSE squared equals bias squared plus the variance. The maximum error matters for safety margins such as the buffer between a geofence and the boundary it protects. Horizontal error is the length of a 2D vector: with independent noise of sigma per axis its RMSE is sigma times the square root of 2. An error that wanders more slowly than your measurement window looks like bias: over one short flight its mean is not zero, even though it averages out over hours. Datasheets quote CEP, 2DRMS or 95% figures; know which one you are reading before comparing receivers.

03

Measure the simulator's sensors

The program takes off to 20 m, hovers for 60 s, flies three legs (one climbing to 30 m) in a wind of about 3 m/s with 1.5 m/s gusts, and returns home. Before every step, record pairs the telemetry report with State() when the report is stamped with the current time, the only moment when truth and measurement describe the same instant. It prints the mean error, RMSE and maximum error of GPS position, barometer and velocity; averages N GPS samples in the hover and compares the result with what independent noise would give; measures a 1 s average while moving; integrates velocity from the first GPS fix; and estimates a 1.5 m weather offset added to the baro from GPS altitude.

go
package main

import (
	"fmt"
	"log"
	"math"

	"gopherforge.app/drone"
)

// errStats accumulates measurement errors (measured minus true).
type errStats struct {
	n               int
	sum, sumSq, max float64
}

func (s *errStats) add(e float64) {
	s.n++
	s.sum += e
	s.sumSq += e * e
	s.max = max(s.max, math.Abs(e))
}

func (s *errStats) bias() float64 { return s.sum / float64(s.n) }
func (s *errStats) rmse() float64 { return math.Sqrt(s.sumSq / float64(s.n)) }

// sample is one telemetry report next to the truth at the same instant.
type sample struct {
	t          float64
	truth, gps drone.Vec3
	vel, trueV drone.Vec3
	baro       float64
	moving     bool
}

func main() {
	sim := drone.New(drone.Config{Wind: drone.Vec3{X: 3, Y: -1}, Gust: 1.5, Seed: 7})
	d := sim.Drone()

	var samples []sample
	lastTel := -1.0
	// record runs before every step. Telemetry is refreshed at 5 Hz inside
	// Step, so a report stamped with the current time pairs with State().
	record := func() {
		tel, st := d.Telemetry(), d.State()
		if tel.Time != lastTel && tel.Time == sim.Time() && !st.Landed {
			lastTel = tel.Time
			samples = append(samples, sample{tel.Time, st.Pos, tel.GPS, tel.Velocity, st.Vel,
				tel.BaroAlt, st.Vel.Horizontal().Len() > 1})
		}
	}
	fly := func(limit float64, done func() bool) {
		if !sim.RunUntil(limit, func(float64) bool { record(); return done() }) {
			log.Fatalf("leg not finished: %+v", d.State())
		}
	}

	must(d.Arm())
	must(d.TakeOff(20))
	fly(30, func() bool { return d.State().Mode == drone.Hold })
	sim.Mark("hover 60 s")
	first := len(samples)
	sim.Run(60, func(float64) { record() })
	hover := samples[first:]
	for _, wp := range []drone.Vec3{{X: 80, Y: 0, Z: 20}, {X: 80, Y: 80, Z: 30}, {X: 0, Y: 80, Z: 30}} {
		must(d.GoTo(wp))
		fly(90, d.Arrived)
	}
	must(d.ReturnHome())
	fly(120, func() bool { return d.State().Landed })

	var gpsH, gpsE, gpsN, gpsV, baro, velH, velE, velN errStats
	for _, s := range samples {
		e := s.gps.Sub(s.truth)
		gpsH.add(e.Horizontal().Len())
		gpsE.add(e.X)
		gpsN.add(e.Y)
		gpsV.add(e.Z)
		baro.add(s.baro - s.truth.Z)
		v := s.vel.Sub(s.trueV)
		velH.add(v.Horizontal().Len())
		velE.add(v.X)
		velN.add(v.Y)
	}
	fmt.Printf("%d telemetry samples at 5 Hz over %.0f s of flight\n", len(samples), samples[len(samples)-1].t-samples[0].t)
	fmt.Println("sensor               mean error              RMSE       max |err|")
	row := func(name, bias, unit string, s errStats) {
		fmt.Printf("%-20s %-22s %5.2f %-4s %5.2f %s\n", name, bias, s.rmse(), unit, s.max, unit)
	}
	row("GPS horizontal", fmt.Sprintf("e %+.2f n %+.2f m", gpsE.bias(), gpsN.bias()), "m", gpsH)
	row("GPS vertical", fmt.Sprintf("%+.2f m", gpsV.bias()), "m", gpsV)
	row("barometer", fmt.Sprintf("%+.2f m", baro.bias()), "m", baro)
	row("velocity horizontal", fmt.Sprintf("e %+.3f n %+.3f m/s", velE.bias(), velN.bias()), "m/s", velH)

	// Averaging N samples in the hover. Independent noise would shrink by the
	// square root of N; an error that wanders for tens of seconds does not.
	fmt.Println("GPS horizontal error of an N-sample average, 60 s hover:")
	var one float64
	for _, n := range []int{1, 5, 25, 100} {
		var s errStats
		for i := n; i <= len(hover); i++ {
			var avg drone.Vec3
			for _, h := range hover[i-n : i] {
				avg = avg.Add(h.gps.Sub(h.truth).Scale(1 / float64(n)))
			}
			s.add(avg.Horizontal().Len())
		}
		if n == 1 {
			one = s.rmse()
		}
		fmt.Printf("  N=%3d (%4.1f s): RMSE %.2f m, independent noise would give %.2f m\n",
			n, float64(n)/5, s.rmse(), one/math.Sqrt(float64(n)))
	}

	// In motion an average also lags: it reports where the drone was.
	var lag errStats
	for i := 4; i < len(samples); i++ {
		if !samples[i].moving {
			continue
		}
		var avg drone.Vec3
		for _, s := range samples[i-4 : i+1] {
			avg = avg.Add(s.gps.Scale(0.2))
		}
		lag.add(avg.Sub(samples[i].truth).Horizontal().Len())
	}
	fmt.Printf("GPS 1 s average while moving: RMSE %.2f m over %d samples\n", lag.rmse(), lag.n)

	// Velocity measures change, not position: integrated from the first GPS
	// fix it is smooth, but it keeps that fix's error and slowly adds its own.
	var dr errStats
	p := samples[0].gps
	for i := 1; i < len(samples); i++ {
		a, b := samples[i-1], samples[i]
		p = p.Add(a.vel.Add(b.vel).Scale((b.t - a.t) / 2)) // trapezoid rule
		dr.add(p.Sub(b.truth).Horizontal().Len())
	}
	fmt.Printf("velocity integrated from the first GPS fix: start error %.2f m, RMSE %.2f m, final %.2f m\n",
		samples[0].gps.Sub(samples[0].truth).Horizontal().Len(), dr.rmse(),
		p.Sub(samples[len(samples)-1].truth).Horizontal().Len())

	// Calibrating one sensor against another inherits the other's error: a
	// baro offset estimated from GPS altitude over this flight.
	const weather = 1.5 // pressure fell after take-off: the baro reads 1.5 m high
	var offset float64
	for _, s := range samples {
		offset += (s.baro + weather - s.gps.Z) / float64(len(samples))
	}
	fmt.Printf("baro offset estimated from GPS altitude: %+.2f m (true %+.2f m)\n", offset, weather)

	if err := sim.Save(); err != nil {
		log.Fatal(err)
	}
}

func must(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
Read the code

609 samples over 122 s confirm 5 Hz. GPS RMSE is 1.20 m horizontally and 1.51 m vertically, and over this one flight the mean errors are not zero (e -0.25, n +0.29 m, vertical +1.13 m): an error that wanders for about 20 s does not average out in two minutes, so it looks like bias. The barometer (0.30 m, mean +0.00 m) and velocity (0.14 m/s, means of a few mm/s) carry independent noise. In the hover, averages of 5, 25 and 100 GPS samples are still 1.09, 1.04 and 1.00 m off, where independent noise would fall to 0.57, 0.26 and 0.13 m. While moving, the 1 s average is 4.35 m off because it reports where the drone was 0.4 s earlier. Integrated velocity follows the path but stays as wrong as its first fix: the error is 1.56 m at the start, 1.81 m at the end and 1.85 m RMS. The baro offset estimated from GPS is +0.37 m instead of +1.50 m: the true offset minus GPS altitude's own +1.13 m mean error.

04

Why fusion is needed

The sensors fail in different ways. GPS position is absolute but wanders, so averaging it buys little and lags in motion. Velocity, from GNSS Doppler or an integrated IMU, follows motion precisely over seconds but only measures change, so integrating it inherits the starting error and slowly drifts. The barometer resolves small height changes but its offset moves with the weather, and calibrating it against GPS altitude imports GPS's own wander. A fusion filter predicts with the fast, smooth sensors and corrects with the absolute ones, weighting each by an error model that includes how its error evolves over time. PX4's EKF2 and ArduPilot's EKF3 predict with the IMU, correct with GNSS, barometer, magnetometer and other sensors, and estimate sensor biases as extra states. The simulator still leaves things out: it has no IMU signals and no barometer drift (the program adds the 1.5 m offset itself), and its autopilot flies on the true state, while a real vehicle holds its own estimate and wanders with it. The next unit builds complementary and Kalman filters on these measurements.

05

Fly it in GopherForge

In the app, choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go. Tap Run to print the tables, then open Output: the replay shows the climb, the 60 s hover mark, the three waypoints and the return home. Change Seed or GPSNoise in drone.Config and run again: the RMSE scales with GPSNoise, the mean errors change sign and size from flight to flight because the error wanders, and the N-sample averages stay stuck near the single-sample error.

TAKE THIS WITH YOU

Measure sensors against truth before trusting them: bias is the mean error and RMSE combines bias and noise. Averaging removes only fast, independent noise, lags in motion and leaves slow GPS wander and bias in place; fusing sensors with complementary errors, as an EKF does, is how flight controllers get estimates good enough to fly on.

Check your understanding

A barometer reads 1.5 m high because the air pressure changed after take-off. Will averaging more barometer samples remove that error?

Go to the source

Progress stays in this browser. No account needed.