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

Coordinates for drones: WGS84, ENU and NED, haversine and local tangent planes

Convert mission waypoints between WGS84 latitude and longitude and local metres, compute great-circle distance and bearing, and know where the flat-plane approximation and spherical formulas stop being good enough.

GPS reports latitude, longitude and altitude on the WGS84 ellipsoid; controllers work in metres in a local frame; MAVLink and the flight stacks use NED while ROS and this simulator use ENU. Every drone codebase converts between them, and a swapped axis, a wrong sign or a missing cos(latitude) produces a vehicle that flies confidently to the wrong place. The conversions are short; knowing their error budget is the real skill.

drones · A MAP OF THE IDEA

  1. Keep WGS84 on the wire
  2. Pick a reference point
  3. Wrap dlon, scale by cos
  4. Re-base for long legs

Useful when

  • A local plane turns geometry into plain vector maths.
  • degE7 integers keep centimetre resolution on the wire.

Watch out

  • Flat-plane error grows with distance and latitude.
  • Axis swaps and sign flips between ENU and NED fail silently.

Implementation & operation cost: A reference point per mission and two small conversion functions, tested at high latitude and across the antimeridian.

01

WGS84, ENU and NED

WGS84 defines the reference ellipsoid (semi-major axis 6378137 m, flattening 1/298.257223563) and the frame GPS positions are expressed in. Heights come in two kinds: GNSS receivers measure height above the ellipsoid, while GLOBAL_POSITION_INT's alt is above mean sea level (the geoid), and the two differ by up to about 100 m depending on where you are. Local frames are tangent to the Earth at a reference point. ENU has x east, y north and z up; ROS and this simulator use it. NED has x north, y east and z down; aviation, PX4, ArduPilot and MAVLink messages such as LOCAL_POSITION_NED use it. Converting is north = y, east = x, down = -z, and headings change too: NED heading runs clockwise from north, ENU yaw counter-clockwise from east, so heading = 90 degrees - yaw.

02

Haversine distance and initial bearing

The haversine formula gives the great-circle distance on a sphere and stays accurate for short distances, where the spherical law of cosines loses precision. With the mean Earth radius of 6371008.8 m its error against the WGS84 ellipsoid is a few tenths of a percent at most, and the program shows why: at 47.4 degrees north the sphere's metre per degree is 0.015% long north-south and 0.293% short east-west. The initial bearing is the direction to set off in; along a great circle it changes except on meridians and the equator. For survey-grade work use an ellipsoidal geodesic (Karney's algorithm, as in GeographicLib) or convert through Earth-centred coordinates (ECEF) to ENU.

03

Waypoints to local metres and back

Plane is a local tangent plane at home with the equirectangular approximation: x = R * dlon * cos(lat0) and y = R * dlat, with the longitude difference wrapped into [-180, 180). The program compares metres per degree on the sphere and on WGS84, converts four survey waypoints into simulator ENU and NED vectors and checks them against haversine, sends a simulator position through degE7 integers and back, compares degE7 with float32 degrees, measures how the flat-plane error grows with distance at two latitudes, and crosses the antimeridian.

go
package main

import (
	"fmt"
	"math"
)

// earthRadius is the mean Earth radius in metres. Spherical formulas with it
// are within a few tenths of a percent of the WGS84 ellipsoid.
const earthRadius = 6371008.8

// WGS84 ellipsoid: semi-major axis and flattening.
const (
	wgs84A = 6378137.0
	wgs84F = 1 / 298.257223563
)

type LatLon struct{ Lat, Lon float64 } // degrees, WGS84

func rad(d float64) float64 { return d * math.Pi / 180 }
func deg(r float64) float64 { return r * 180 / math.Pi }

// wrap180 brings a longitude difference into [-180, 180).
func wrap180(d float64) float64 { return math.Mod(math.Mod(d+180, 360)+360, 360) - 180 }

// Distance is the haversine great-circle distance in metres.
func Distance(a, b LatLon) float64 {
	p1, p2 := rad(a.Lat), rad(b.Lat)
	dp, dl := p2-p1, rad(b.Lon-a.Lon)
	h := math.Sin(dp/2)*math.Sin(dp/2) + math.Cos(p1)*math.Cos(p2)*math.Sin(dl/2)*math.Sin(dl/2)
	return 2 * earthRadius * math.Asin(math.Sqrt(h))
}

// Bearing is the initial great-circle bearing, degrees clockwise from north.
func Bearing(a, b LatLon) float64 {
	p1, p2, dl := rad(a.Lat), rad(b.Lat), rad(b.Lon-a.Lon)
	y := math.Sin(dl) * math.Cos(p2)
	x := math.Cos(p1)*math.Sin(p2) - math.Sin(p1)*math.Cos(p2)*math.Cos(dl)
	return math.Mod(deg(math.Atan2(y, x))+360, 360)
}

// Destination walks dist metres from a along an initial bearing on the sphere.
func Destination(a LatLon, bearing, dist float64) LatLon {
	p1, l1, th, d := rad(a.Lat), rad(a.Lon), rad(bearing), dist/earthRadius
	p2 := math.Asin(math.Sin(p1)*math.Cos(d) + math.Cos(p1)*math.Sin(d)*math.Cos(th))
	l2 := l1 + math.Atan2(math.Sin(th)*math.Sin(d)*math.Cos(p1), math.Cos(d)-math.Sin(p1)*math.Sin(p2))
	return LatLon{deg(p2), wrap180(deg(l2))}
}

// Plane is a local tangent plane at Ref with the equirectangular
// approximation: X east and Y north in metres, like the simulator's ENU.
type Plane struct{ Ref LatLon }

func (pl Plane) ToLocal(p LatLon) (x, y float64) {
	x = earthRadius * rad(wrap180(p.Lon-pl.Ref.Lon)) * math.Cos(rad(pl.Ref.Lat))
	y = earthRadius * rad(p.Lat-pl.Ref.Lat)
	return x, y
}

func (pl Plane) ToLatLon(x, y float64) LatLon {
	lat := pl.Ref.Lat + deg(y/earthRadius)
	lon := pl.Ref.Lon + deg(x/(earthRadius*math.Cos(rad(pl.Ref.Lat))))
	return LatLon{lat, wrap180(lon)}
}

func main() {
	home := LatLon{47.397742, 8.545594}
	plane := Plane{Ref: home}

	// Metres per degree at home: sphere against the WGS84 ellipsoid.
	e2 := wgs84F * (2 - wgs84F)
	s2 := math.Pow(math.Sin(rad(home.Lat)), 2)
	m := wgs84A * (1 - e2) / math.Pow(1-e2*s2, 1.5) // meridian radius of curvature
	n := wgs84A / math.Sqrt(1-e2*s2)                // prime vertical radius
	northS, northE := rad(earthRadius), rad(m)
	eastS, eastE := rad(earthRadius)*math.Cos(rad(home.Lat)), rad(n)*math.Cos(rad(home.Lat))
	fmt.Printf("1 deg north: sphere %.1f m, WGS84 %.1f m (%+.3f%%)\n", northS, northE, (northS-northE)/northE*100)
	fmt.Printf("1 deg east:  sphere %.1f m, WGS84 %.1f m (%+.3f%%)\n", eastS, eastE, (eastS-eastE)/eastE*100)

	fmt.Println("mission waypoints, 15 m above home:")
	wps := []LatLon{{47.398200, 8.546300}, {47.398200, 8.547400}, {47.397300, 8.547400}, {47.397300, 8.546300}}
	for i, wp := range wps {
		x, y := plane.ToLocal(wp)
		dist, brg := Distance(home, wp), Bearing(home, wp)
		flatDist := math.Hypot(x, y)
		flatBrg := math.Mod(deg(math.Atan2(x, y))+360, 360) // atan2(east, north): clockwise from north
		fmt.Printf("  wp%d ENU (%.2f, %.2f, 15)  NED (%.2f, %.2f, -15)  %.2f m at %.2f deg  flat %+.1f mm %+.4f deg\n",
			i+1, x, y, y, x, dist, brg, (flatDist-dist)*1000, flatBrg-brg)
	}

	// Back: a simulator position to GLOBAL_POSITION_INT integers and back.
	simX, simY := 61.37, -40.21
	p := plane.ToLatLon(simX, simY)
	latE7, lonE7 := int32(math.Round(p.Lat*1e7)), int32(math.Round(p.Lon*1e7))
	bx, by := plane.ToLocal(LatLon{float64(latE7) / 1e7, float64(lonE7) / 1e7})
	fmt.Printf("sim (%.2f, %.2f) -> lat %d lon %d (degE7) -> (%.4f, %.4f): error %.1f mm\n",
		simX, simY, latE7, lonE7, bx, by, math.Hypot(bx-simX, by-simY)*1000)
	ulp := func(v float64) float64 { f := float32(v); return float64(math.Nextafter32(f, 1e9) - f) }
	fmt.Printf("resolution here: degE7 %.2f cm north, %.2f cm east; float32 degrees %.2f cm north, %.2f cm east\n",
		rad(1e-7)*earthRadius*100, rad(1e-7)*earthRadius*math.Cos(rad(p.Lat))*100,
		rad(ulp(p.Lat))*earthRadius*100, rad(ulp(p.Lon))*earthRadius*math.Cos(rad(p.Lat))*100)

	fmt.Println("flat-plane range error against haversine, bearing 45 deg:")
	for _, site := range []struct {
		name string
		at   LatLon
	}{{"lat 47.4", home}, {"lat 78.2", LatLon{78.2, 15.6}}} {
		line := "  " + site.name + ":"
		for _, d := range []float64{100, 1000, 10000, 100000} {
			q := Destination(site.at, 45, d)
			x, y := Plane{Ref: site.at}.ToLocal(q)
			line += fmt.Sprintf("  %gkm %+.3f%%", d/1000, (math.Hypot(x, y)-d)/d*100)
		}
		fmt.Println(line)
	}

	a, b := LatLon{-16.5, 179.9995}, LatLon{-16.5, -179.9995}
	raw := earthRadius * rad(b.Lon-a.Lon) * math.Cos(rad(a.Lat))
	x, _ := Plane{Ref: a}.ToLocal(b)
	fmt.Printf("across the antimeridian: east %.1f km without wrapping, %.1f m wrapped; haversine %.1f m\n",
		raw/1000, x, Distance(a, b))
}
Read the code

The first two lines put the sphere at +0.015% north-south and -0.293% east-west against WGS84, so on wp2's 136 m eastward offset the spherical model is about 0.4 m short: at field scale that, not the flat plane, is the larger error. wp2 becomes ENU (135.93, 50.93, 15) and NED (50.93, 135.93, -15), and every flat range and bearing differs from haversine by under a millimetre and 0.001 degree. The simulator position (61.37, -40.21) survives degE7 with a 4.0 mm error; degE7 resolves 1.11 cm north and 0.75 cm east, float32 degrees only 42.42 cm and 7.18 cm. The flat plane is 0.003% off at 1 km and 0.308% at 100 km at latitude 47.4, but already 0.134% at 10 km at latitude 78.2. Without wrapping, two points 106.6 m apart across the antimeridian appear 38381.7 km apart.

04

Where the flat plane breaks

The equirectangular plane uses cos(lat0) for every point, so its error grows with distance from the reference and faster at high latitude, where the cosine changes quickly; it is undefined at the poles. It also ignores curvature in height: 10 km away the ground lies about 7.8 m below the tangent plane. For a field, a farm or a city block it is excellent; for long routes, re-base the plane per leg or use an exact ECEF-to-ENU rotation. Flight stacks do the same thing at mission scale: ArduPilot scales longitude differences by the cosine of the two points' mean latitude, and PX4 projects around a reference point with an azimuthal equidistant projection. Send waypoints to the autopilot as latitude and longitude (MISSION_ITEM_INT carries them as degE7) and let it project them; use local metres only inside your own planning and display code.

05

Fly it in GopherForge

The program uses only the standard library: in the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To fly the mission, copy the four ENU vectors into a GoTo loop like the one the template's main.go runs over Square (keep mission.go), call sim.Save at the end and open Output for the replay; inside the loop, convert d.State().Pos back with ToLatLon to print latitude and longitude as the drone flies.

TAKE THIS WITH YOU

Keep WGS84 latitude and longitude (as degE7 integers) on the wire and in missions, and use a local ENU or NED plane in metres for control, with the longitude difference wrapped and scaled by cos(latitude). The flat plane is excellent for a field and wrong for a country.

Check your understanding

The simulator reports a position in ENU as (x, y, z). How do you express it in NED for a MAVLink LOCAL_POSITION_NED message?

Go to the source

Progress stays in this browser. No account needed.