Autonomy: rangefinders, maps, avoidance and precision landing · 7 MIN READ

Rangefinders and lidar scans: rays, maximum range, noise and what a horizontal scan misses

Model a rangefinder as a ray with a maximum range and noise, turn a lidar scan into clustered obstacle points in local coordinates, reject dropouts and spurious returns with a median, pack the result as MAVLink OBSTACLE_DISTANCE, and name what a horizontal scan cannot see.

GPS tells a drone where it is; a rangefinder tells it how far away things are. Single-beam rangefinders and spinning lidars time a light pulse along a narrow beam, so every reading is a distance along one direction, valid between a minimum and a maximum range. Turning readings into obstacles is where the subtle bugs live: the maximum reading means that nothing was seen, beams leave gaps between them, a horizontal scan sees one thin slice of the world, and a few bad returns in every scan are normal.

drones · A MAP OF THE IDEA

  1. Scan n beams
  2. Cluster hits by gap
  3. Median per beam
  4. Points via position

Useful when

  • Ranges are good to centimetres, independent of GPS error.
  • Clustering and OBSTACLE_DISTANCE packing are cheap every scan.

Watch out

  • One horizontal plane: lower obstacles and wires are invisible.
  • Gaps between beams can hide a thin mast entirely.

Implementation & operation cost: A scanner and its driver, a clustering and filtering pass per scan, and a second sensor for what the scan plane misses.

01

Rays, beams and maximum range

A lidar measures the round-trip time of a laser pulse, so the distance is c t / 2; sonar does the same with sound and radar with radio. A single-point rangefinder looks down for height above ground or forward for obstacles; a 360-degree scanner spins one beam or combines several fixed sensors, and ArduPilot accepts such scanners as proximity sensors. Every reading is valid between a minimum and a maximum range. Closer than the minimum, further than the maximum, off a black, wet or glancing surface, or into bright sunlight, no echo returns. Real beams also diverge, so the footprint grows with distance and a beam that half-hits an edge can report a distance in between. The simulator's Range is an ideal ray at the drone's altitude with about 3 cm of noise that reads drone.RangeMax, 40 m, when nothing is hit; Scan(n) takes n readings counter-clockwise from east, aligned with the world. MAVLink carries one reading in DISTANCE_SENSOR (min_distance, max_distance, current_distance in cm and the orientation) and a whole scan in OBSTACLE_DISTANCE: 72 distances in cm, index 0 at north by default, increments clockwise, 0 for touching, max_distance + 1 for no obstacle and UINT16_MAX for unknown.

02

What a horizontal scan cannot see

A 2D lidar measures one plane at the drone's altitude. Anything lower than the drone, a tree, a roof, a person, is invisible until the drone descends into its height, so descent and landing need a downward rangefinder, a map or a camera. Wires, branches and overhangs above or below the plane escape it too, and glass or black surfaces may return nothing. Between beams there are gaps: with spacing d theta the beams are r d theta apart at range r, 0.35 m at 20 m for 1 degree and 1.75 m for 5 degrees, wide enough to miss a mast. On a real vehicle the scanner is fixed to the body, so a beam's world heading is the yaw plus the beam angle, and when the drone pitches 15 degrees to accelerate, the plane tilts with it: from 10 m up its beams meet the ground about 37 m ahead, and the ground looks like a wall. ArduPilot offers PRX_IGN_GND to drop such returns with the help of a downward rangefinder, and exclusion sectors (PRXx_IGN_ANGx, PRXx_IGN_WIDx) for legs or masts that block the scanner's view.

03

Scan, cluster, filter, pack

The world holds a 30 m tower of radius 3 m, a mast of radius 0.3 m, a 7 m tree and a hangar. From home at 10 m the program scans 360 beams and groups the hits into clusters: a new cluster starts after a miss, or where neighbouring points are further apart than 0.5 m plus 10 percent of the range, because points spread out with distance and jump where a beam grazes an edge. Each cluster's nearest point is converted into local coordinates twice, from the true position and from GPS, as the coordinates lesson's local frame would hold it. Then it counts hits at five resolutions, flies east scanning every 4 s, hovers for five 72-beam scans with dropouts (6 percent) and spurious short returns (3 percent) added from a seeded math/rand/v2 source, because the simulator's rangefinder is cleaner than a real one, compares a single scan, the mean and the median of five against the clean readings, packs the median scan as OBSTACLE_DISTANCE, and finally descends beside the tree.

go
package main

import (
	"fmt"
	"log"
	"math"
	"math/rand/v2"
	"slices"

	"gopherforge.app/drone"
)

var world = []drone.Obstacle{
	{Name: "tower", X: 30, Y: 14, Radius: 3, Height: 30},
	{Name: "mast", X: 16, Y: -12, Radius: 0.3, Height: 25},
	{Name: "tree", X: 22, Y: -6, Radius: 2.5, Height: 7},
	{Name: "hangar", X: 62, Y: -15, Radius: 7, Height: 12},
}

// heading of beam i of an n-beam scan: counter-clockwise from east.
func heading(i, n int) float64 { return 2 * math.Pi * float64(i%n) / float64(n) }

// Point turns one reading into an obstacle point relative to the drone, on
// the local east-north axes. Scan is world-aligned, so no yaw is added.
func Point(r, h float64) drone.Vec3 { return drone.Vec3{X: r * math.Cos(h), Y: r * math.Sin(h)} }

// A Cluster is a run of neighbouring beams whose points lie close together.
type Cluster struct {
	First, Last int        // beam indices (Last may pass n: it wraps)
	Near        float64    // shortest range, m
	Bearing     float64    // heading of the shortest range, degrees
	At          drone.Vec3 // nearest point, relative to the drone
}

// Clusters groups hits (readings under RangeMax) into objects. A new one starts
// after a miss, or where neighbouring points lie over 0.5 m + 10% of r apart.
func Clusters(scan []float64) []Cluster {
	n := len(scan)
	hit := func(i int) bool { return scan[i%n] < drone.RangeMax }
	pt := func(i int) drone.Vec3 { return Point(scan[i%n], heading(i, n)) }
	start := 0
	for start < n && hit(start) {
		start++
	}
	var out []Cluster
	for i := start; i < start+n; i++ {
		if !hit(i) {
			continue
		}
		r, deg := scan[i%n], 360*float64(i%n)/float64(n)
		if k := len(out) - 1; k >= 0 && out[k].Last == i-1 && pt(i-1).Sub(pt(i)).Len() < 0.5+0.1*r {
			c := &out[k]
			if c.Last = i; r < c.Near {
				c.Near, c.Bearing, c.At = r, deg, pt(i)
			}
			continue
		}
		out = append(out, Cluster{First: i, Last: i, Near: r, Bearing: deg, At: pt(i)})
	}
	return out
}

// name is a truth check only: the obstacle whose surface passes near p.
func name(p drone.Vec3) string {
	for _, o := range world {
		if math.Abs(math.Hypot(p.X-o.X, p.Y-o.Y)-o.Radius) < 0.5 {
			return o.Name
		}
	}
	return "?"
}

// ObstacleDistance packs a 72-beam scan as MAVLink OBSTACLE_DISTANCE does:
// cm, sector 0 north, 5 degrees clockwise, max_distance+1 for "no obstacle".
func ObstacleDistance(scan []float64) (out [72]uint16) {
	for j := range out {
		r := scan[(18-j+72)%72] // north is beam 18 counter-clockwise from east
		if r >= drone.RangeMax {
			r = drone.RangeMax + 0.01
		}
		out[j] = uint16(math.Round(r * 100))
	}
	return out
}

func median(v []float64) float64 { s := slices.Sorted(slices.Values(v)); return s[len(s)/2] }
func mean(v []float64) float64 {
	sum := 0.0
	for _, x := range v {
		sum += x
	}
	return sum / float64(len(v))
}
func xy(v drone.Vec3) string { return fmt.Sprintf("(%.1f, %.1f)", v.X, v.Y) }

func main() {
	sim := drone.New(drone.Config{Wind: drone.Vec3{X: 1.5, Y: 0.5}, Gust: 0.5, Obstacles: world, Seed: 11})
	d := sim.Drone()
	if err := d.Arm(); err != nil {
		log.Fatal(err)
	}
	d.TakeOff(10)
	sim.RunUntil(30, func(float64) bool { return d.Arrived() })
	fly := func(p drone.Vec3) { d.GoTo(p); sim.RunUntil(30, func(float64) bool { return d.Arrived() }) }

	fmt.Println("from home at 10 m, 360 beams:")
	hits := 0
	for _, c := range Clusters(d.Scan(360)) {
		pos, gps := d.State().Pos, d.Telemetry().GPS
		hits += c.Last - c.First + 1
		fmt.Printf("  %-6s %2d beams  %4.1f m at %3.0f deg  point %v, via GPS %v\n",
			name(pos.Add(c.At)), c.Last-c.First+1, c.Near, c.Bearing, xy(pos.Add(c.At)), xy(gps.Add(c.At)))
	}
	fmt.Printf("  the other %d beams read %.0f m: no echo, nothing within range\n", 360-hits, drone.RangeMax)

	fmt.Println("beams that hit, by scan resolution:")
	for _, n := range []int{8, 16, 36, 72, 360} {
		count := map[string]int{}
		for i, r := range d.Scan(n) {
			if r < drone.RangeMax {
				count[name(d.State().Pos.Add(Point(r, heading(i, n))))]++
			}
		}
		fmt.Printf("  %3d beams %4.1f deg apart, %5.2f m apart at 20 m: tower %2d, mast %d\n",
			n, 360/float64(n), 20*2*math.Pi/float64(n), count["tower"], count["mast"])
	}

	fmt.Println("flying east at 4 m/s along y = 0, a scan every 4 s:")
	d.SetVelocity(drone.Vec3{X: 4}, 0)
	for range 5 {
		p := d.State().Pos
		line := fmt.Sprintf("  x=%4.1f", p.X)
		for _, c := range Clusters(d.Scan(360)) {
			line += fmt.Sprintf("  %s %.1f m at %.0f", name(p.Add(c.At)), c.Near, c.Bearing)
		}
		fmt.Println(line)
		sim.Run(4, nil)
	}

	fly(drone.Vec3{X: 45, Z: 10})
	fmt.Println("hover at (45, 0): 5 scans of 72 beams, with dropouts and spurious returns added")
	rng := rand.New(rand.NewPCG(1, 2))
	clean, noisy := make([][]float64, 72), make([][]float64, 72)
	for range 5 {
		for i, r := range d.Scan(72) {
			clean[i] = append(clean[i], r)
			switch u := rng.Float64(); {
			case u < 0.06:
				r = drone.RangeMax // no return: a dark or glancing surface
			case u < 0.09:
				r = 0.5 + 2.5*rng.Float64() // dust, rain, a bird
			}
			noisy[i] = append(noisy[i], r)
		}
		sim.Run(0.1, nil)
	}
	shown, filtered := map[bool]bool{}, make([]float64, 72)
	for i := range noisy {
		truth, onObstacle := median(clean[i]), median(clean[i]) < drone.RangeMax
		filtered[i] = median(noisy[i])
		if !shown[onObstacle] && (onObstacle && slices.Max(noisy[i]) == drone.RangeMax || !onObstacle && slices.Min(noisy[i]) < 5) {
			shown[onObstacle] = true
			fmt.Printf("  beam %2d truth %4.1f  raw %4.1f  mean %4.1f  median %4.1f\n", i, truth, noisy[i], mean(noisy[i]), median(noisy[i]))
		}
	}
	names := []string{"single scan", "mean of 5", "median of 5"}
	for k, reduce := range []func([]float64) float64{func(v []float64) float64 { return v[0] }, mean, median} {
		short, long := 0, 0
		for i := range noisy {
			switch truth, got := median(clean[i]), reduce(noisy[i]); {
			case got < truth-0.5:
				short++
			case got > truth+0.5:
				long++
			}
		}
		fmt.Printf("  %-11s  phantom obstacles %2d  obstacles too far or gone %d\n", names[k], short, long)
	}
	line := "  OBSTACLE_DISTANCE, sectors with an obstacle (cm):"
	for j, v := range ObstacleDistance(filtered) {
		if v <= drone.RangeMax*100 {
			line += fmt.Sprintf(" %d:%d", j, v)
		}
	}
	fmt.Println(line)

	fly(drone.Vec3{X: 22, Y: -1.5, Z: 10})
	south := -math.Pi / 2
	fmt.Printf("beside the 7 m tree at 10 m: range south %.1f m; descend at 1 m/s\n", d.Range(south))
	d.SetVelocity(drone.Vec3{Z: -1}, 0)
	sim.RunUntil(8, func(float64) bool { return d.Range(south) < drone.RangeMax })
	fmt.Printf("  first echo at z=%.1f m: the tree is %.1f m away\n", d.State().Pos.Z, d.Range(south))
	d.Land()
	sim.RunUntil(30, func(float64) bool { return d.State().Landed })
	if err := sim.Save(); err != nil {
		log.Fatal(err)
	}
}
Read the code

From home the tower is 11 beams wide, 30.1 m away at 25 degrees, and its nearest point is (27.2, 12.7) from the true position but (28.1, 12.9) via GPS: the range is good to centimetres, the map point only to the position estimate. The mast shows in a single beam at 19.7 m, and the other 348 beams read 40 m. The table explains it: with 72 beams 1.75 m apart at 20 m the mast gets no hit, and with 8 beams even the tower gets none. On the way east the tree never appears: at 7 m it is below the 10 m scan plane, although the track passes 3.5 m from its edge. The hangar first shows at x=31.3, 27.2 m away. Beam 10 sees nothing; one spurious 1.3 m return drags the mean of 40.0, 40.0, 40.0, 1.3, 40.0 to 32.3 m, a phantom obstacle, while the median stays 40.0. Beam 26 sees the hangar at 17.8 m and one dropout pushes its mean to 22.3 m. Over 72 beams the single scan has 2 phantom obstacles, the mean 10 phantoms and 2 obstacles too far, the median none. OBSTACLE_DISTANCE fills sectors 23 to 29 (the hangar, south-east) and 62 to 64 (the tower, north-west), counted clockwise from north. Beside the tree the reading is 40.0 m at 10 m; the first echo comes at z=7.0 m, 2.2 m away.

04

Median filters and the meaning of 40 m

Real rangefinders produce outliers in both directions: dropouts that read as the maximum or as an invalid code, and spurious short returns from dust, rain, insects or the vehicle's own legs. Treat the maximum as 'no echo within range', never as an obstacle at 40 m, and never average it with real distances: one dropout in five moved the hangar 4.5 m further away, one spurious return in five invented an obstacle at 32 m. A median of the last 3 or 5 readings per beam rejects isolated outliers either way, at the price of a delay: a median of 5 follows a real change only when 3 samples are new, two periods late, 0.2 s at 10 Hz or 1.6 m at 8 m/s. A median across neighbouring beams has no delay but erases anything one beam wide, which is exactly what the mast was. Keep 'unknown' separate from 'free': OBSTACLE_DISTANCE has UINT16_MAX for it, and PX4's collision prevention by default will not move towards directions without data. ArduPilot also low-pass filters proximity readings (PRX_FILT), which smooths noise but bends towards outliers instead of rejecting them.

05

Fly it in GopherForge

In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go (its Square helper is unused here) and tap Run. Open Output: the replay of flight.gfflight draws the four obstacles as grey discs with their heights, the trail east past the tower and the hangar, the hover at (45, 0) and the descent beside the 7 m tree, which the altitude strip shows passing the tree's height where the first echo came. Change the fly-past scan to 72 beams and watch the mast vanish, or move the spurious band's upper limit from 0.09 to 0.3 and see when a median of five stops coping.

TAKE THIS WITH YOU

A rangefinder reading is a distance along one ray between a minimum and a maximum range. Treat the maximum as no echo, group hits into clusters with a range-dependent gap, place points with the position estimate, reject outliers with a median per beam, and remember what the scan plane and the gaps between beams cannot see.

Check your understanding

A 360-degree lidar with a 40 m maximum range reads exactly 40 m on most beams. How should avoidance code treat those readings?

Go to the source

Progress stays in this browser. No account needed.