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

Gap following with a polar histogram: VFH-style sectors, widening and heading choice

Bin a lidar scan into a polar histogram, threshold it with hysteresis into blocked and free sectors, widen every reading by the vehicle radius, choose the free direction with a VFH+ style cost, smooth heading and speed, and fly through a cluttered field.

Instead of adding forces, a polar histogram asks which directions are open. Borenstein and Koren's Vector Field Histogram (1991) and its successor VFH+ (Ulrich and Borenstein, 1998) reduce the surroundings to a ring of sectors, mark the ones an obstacle blocks and steer into the open sector that best serves the goal. Because it chooses among directions rather than summing pushes, an obstacle on the line to the goal cannot balance it into a standstill. It is still a local method, and the vehicle's width has to be put in explicitly.

drones · A MAP OF THE IDEA

  1. Bin scan into sectors
  2. Block with hysteresis
  3. Widen by vehicle radius
  4. Steer to best free sector

Useful when

  • Chooses among directions, so obstacles on the line do not stall it.
  • Widening makes the vehicle size and margin explicit.

Watch out

  • Still local: dead ends and long walls can trap it.
  • Coarse sectors or wide margins close gaps that are really there.

Implementation & operation cost: A 360-degree scan, a 72-sector histogram with widening each cycle, a cost function and a rate-limited heading.

01

From a scan to a polar histogram

Divide the circle into sectors, here 72 of 5 degrees centred on 0, 5, 10 degrees and so on, the resolution of the OBSTACLE_DISTANCE message from the rangefinders lesson, and give each sector the nearest reading that falls into it. The original VFH accumulates certainty values in a grid around the robot and weights each cell by its distance; with a precise lidar the nearest distance per sector carries the same information. A threshold turns the histogram into blocked and free sectors: blocked when something is closer than 8 m. With a single threshold, an obstacle hovering at 8 m makes a sector flicker and the chosen heading jump between scans. VFH+ uses two: here a sector becomes blocked under 8 m and free again only beyond 10 m, and between the two it keeps its previous state, the same hysteresis a thermostat uses.

02

Widening by the vehicle radius

The histogram describes a point. A free sector whose centre line passes 10 cm from a trunk is free for a point and a collision for a drone with a 0.3 m contact radius, and the gaps between beams only make it worse. VFH+ enlarges every obstacle by the robot's radius plus a safety distance: a reading at distance d blocks every sector within gamma = asin((radius + margin) / d) of its bearing, and half the circle when d is smaller than radius plus margin. Near obstacles block wide arcs (49 degrees at 2 m with 1.5 m), far ones narrow arcs (4.3 degrees at 20 m). Gaps narrower than twice the widened radius disappear, which is exactly the point: a 0.6 m gap between two trees must not look free to a drone that needs 0.6 m to fit through, let alone a margin. The margin also covers tracking error in gusts and the 1 degree spacing of the beams.

03

Choosing and smoothing the heading

Among the free sectors, take the one with the lowest cost: 5 times its angle from the goal, plus 2 times its angle from the current heading, plus 2 times its angle from the previous choice. The goal weight exceeds the other two together, so the goal wins whenever its direction is open; the other terms matter when two valleys cost nearly the same, where they keep the choice from hopping between them on alternate scans. In this field the goal term alone also gets through, so treat the weights as insurance, not as tuning for one map. The heading then turns towards the chosen sector at no more than 1.5 rad/s, and the speed follows the widened free distance along the current heading, 0.6 (d - 2) between 0.5 and 6 m/s, so the drone slows while it is still pointed at something and speeds up once it faces the gap.

04

A gate and a cluttered field

Two gate trees stand on the straight line 22 m out with 0.6 m between their trunks, and ten more trees fill the field up to the goal 80 m east. The program flies twice, scanning 360 beams at 10 Hz: once with no widening, where a sector is blocked only by beams that hit inside it, and once widened by 1.5 m, the 0.3 m contact radius plus a 1.2 m margin. The second flight prints a trace every 2.5 s with the goal bearing, the chosen sector, the smoothed heading and the speed, all in degrees from east, and, whenever the choice differs from the goal, the front half of the histogram as a pilot facing east would see it: north on the left, south on the right, one character per sector.

go
package main

import (
	"fmt"
	"log"
	"math"
	"strings"

	"gopherforge.app/drone"
)

const (
	sectors = 72 // 5 degrees each, centred on 0, 5, 10 ... degrees
	width   = 2 * math.Pi / sectors
	dBlock  = 8.0  // m: a sector with an obstacle closer than this is blocked
	dFree   = 10.0 // m: and it is free again only beyond this (hysteresis)
	vmax    = 6.0  // m/s
	turn    = 1.5  // rad/s: the heading turns at most this fast
)

var (
	goal  = drone.Vec3{X: 80, Z: 10}
	world = []drone.Obstacle{
		{Name: "gate north", X: 22, Y: 1.1, Radius: 0.8, Height: 15}, // 0.6 m between them
		{Name: "gate south", X: 22, Y: -1.1, Radius: 0.8, Height: 15},
		{Name: "tree 1", X: 32, Y: 6, Radius: 1.5, Height: 15},
		{Name: "tree 2", X: 35, Y: -5, Radius: 2, Height: 15},
		{Name: "tree 3", X: 40, Y: 1, Radius: 1.2, Height: 15},
		{Name: "tree 4", X: 44, Y: 9, Radius: 1.5, Height: 15},
		{Name: "tree 5", X: 46, Y: -8, Radius: 1.5, Height: 15},
		{Name: "tree 6", X: 50, Y: 3, Radius: 2, Height: 15},
		{Name: "tree 7", X: 53, Y: -3, Radius: 1, Height: 15},
		{Name: "tree 8", X: 57, Y: 8, Radius: 1.5, Height: 15},
		{Name: "tree 9", X: 60, Y: -6, Radius: 2, Height: 15},
		{Name: "tree 10", X: 63, Y: 1, Radius: 1.5, Height: 15},
	}
)

func wrap(a float64) float64 { return math.Remainder(a, 2*math.Pi) }
func sector(a float64) int   { return (int(math.Round(a/width))%sectors + sectors) % sectors }

// Histogram returns, for each sector, the nearest reading that blocks it.
// Every reading at distance r blocks its own sector and, widened by the
// angle asin(rs/r), every sector a body of radius rs would touch.
func Histogram(scan []float64, rs float64) []float64 {
	near := make([]float64, sectors)
	for k := range near {
		near[k] = drone.RangeMax
	}
	for i, r := range scan {
		if r >= drone.RangeMax {
			continue
		}
		a, g := 2*math.Pi*float64(i)/float64(len(scan)), 0.0
		if rs > 0 {
			g = math.Asin(math.Min(1, rs/r))
		}
		for k := range near {
			if math.Abs(wrap(a-float64(k)*width)) <= g+width/2 {
				near[k] = math.Min(near[k], r)
			}
		}
	}
	return near
}

// Choose returns the free sector with the lowest VFH+ style cost: 5 x the
// angle to the goal, 2 x the turn from the current heading and 2 x the change
// from the previous choice. -1 means every sector is blocked.
func Choose(blocked []bool, goal, heading float64, prevK int) int {
	best, cost := -1, math.Inf(1)
	for k, b := range blocked {
		a := float64(k) * width
		c := 5*math.Abs(wrap(a-goal)) + 2*math.Abs(wrap(a-heading)) + 2*math.Abs(wrap(a-float64(prevK)*width))
		if !b && c < cost {
			best, cost = k, c
		}
	}
	return best
}

// draw shows the front half, as a pilot facing east sees it: north on the
// left, south on the right, one character per 5 degree sector.
func draw(blocked []bool, goalK, chosen int) string {
	var b strings.Builder
	for deg := 90; deg >= -90; deg -= 5 {
		switch k := sector(float64(deg) * math.Pi / 180); {
		case k == chosen:
			b.WriteByte('^')
		case k == goalK:
			b.WriteByte('G')
		case blocked[k]:
			b.WriteByte('#')
		default:
			b.WriteByte('.')
		}
	}
	return b.String()
}

// Fly navigates to the goal with a vehicle radius rs (0: no widening).
func Fly(rs float64, show bool) *drone.Sim {
	sim := drone.New(drone.Config{Wind: drone.Vec3{Y: -1.5}, Gust: 0.8, Obstacles: world, Seed: 4})
	d := sim.Drone()
	if err := d.Arm(); err != nil {
		log.Fatal(err)
	}
	d.TakeOff(10)
	sim.RunUntil(30, func(float64) bool { return d.Arrived() })
	sim.Waypoint(goal)
	start, heading, prev, next := sim.Time(), 0.0, 0, sim.Time()
	blocked, minC, path, last := make([]bool, sectors), math.Inf(1), 0.0, d.State().Pos
	watch := func(st drone.State) { // truth: path flown and closest approach to a trunk
		path, last = path+st.Pos.Sub(last).Horizontal().Len(), st.Pos
		for _, o := range world {
			minC = math.Min(minC, math.Hypot(st.Pos.X-o.X, st.Pos.Y-o.Y)-o.Radius)
		}
	}
	sim.RunUntil(90, func(t float64) bool {
		st := d.State()
		watch(st)
		toGoal := goal.Sub(st.Pos).Horizontal()
		if toGoal.Len() < 2 || st.Mode == drone.Crashed {
			return true
		}
		if math.Mod(math.Round(t/sim.Dt()), 5) != 0 {
			return false
		}
		near := Histogram(d.Scan(360), rs)
		for k, r := range near {
			if r < dBlock {
				blocked[k] = true
			} else if r > dFree {
				blocked[k] = false
			}
		}
		goalA := math.Atan2(toGoal.Y, toGoal.X)
		goalK, k := sector(goalA), Choose(blocked, goalA, heading, prev)
		if k < 0 {
			d.SetVelocity(drone.Vec3{}, 0)
			return false
		}
		prev = k
		heading += math.Max(-turn*0.1, math.Min(turn*0.1, wrap(float64(k)*width-heading)))
		speed := math.Max(0.5, math.Min(vmax, 0.6*(near[sector(heading)]-2)))
		d.SetVelocity(drone.Vec3{X: speed * math.Cos(heading), Y: speed * math.Sin(heading)}, 0)
		if show && t >= next {
			next += 2.5
			deg := func(a float64) float64 { return math.Round(wrap(a)*180/math.Pi) + 0 } // + 0: no "-0"
			fmt.Printf("  t=%4.1f s %v goal %4.0f  chosen %4.0f  heading %4.0f deg  %.1f m/s\n", t-start, st.Pos,
				deg(goalA), deg(float64(k)*width), deg(heading), speed)
			if goalK != k {
				fmt.Printf("    N %s S\n", draw(blocked, goalK, k))
			}
		}
		return false
	})
	if st := d.State(); st.Mode == drone.Crashed {
		ev := sim.Events()
		fmt.Printf("  %s at %v after %.1f s\n", ev[len(ev)-1].Text, st.Pos, sim.Time()-start)
		sim.Run(2, nil)
		return sim
	}
	d.GoTo(goal)
	sim.RunUntil(10, func(float64) bool { watch(d.State()); return d.Arrived() })
	fmt.Printf("  arrived after %.1f s, path %.1f m for %.0f m straight, closest surface %.2f m\n",
		sim.Time()-start, path, goal.Horizontal().Len(), minC)
	d.Land()
	sim.RunUntil(30, func(float64) bool { return d.State().Landed })
	return sim
}

func main() {
	fmt.Println("no widening: sectors are blocked only where a beam hit")
	naive := Fly(0, false)
	rs := 1.5 // contact radius 0.3 m plus a margin
	fmt.Printf("widened by %.1f m (0.3 m contact radius + %.1f m margin):\n", rs, rs-0.3)
	fmt.Println("  histogram ahead, 90 deg left to 90 deg right: # blocked, G goal, ^ chosen")
	sim := Fly(rs, true)
	if err := naive.SaveAs("naive"); err != nil {
		log.Fatal(err)
	}
	if err := sim.Save(); err != nil {
		log.Fatal(err)
	}
}
Read the code

Without widening the gate's sector stays free, because from 8 m the central beams still pass between the trunks, so the drone flies straight into the gap: 'hit gate south at (21.8, 0.0, 9.9) after 4.4 s'. With widening the gate blocks the line long before; at t=5.1 s the drone is past it at (24.1, -4.3). At t=7.6 s the widened trees block everything from 35 degrees left to 30 degrees right, goal included, and of the two valleys it stays with the left one it is already turning into, 40 degrees. At t=10.1 s that valley has shrunk to 30 to 40 degrees while everything beyond 45 degrees right is open, and it switches to -45; at t=12.6 s only the right side is open, from 30 degrees right, and it takes -30. At t=15.1 s, at (66.5, -7.7), the goal sector is free and chosen. It arrives after 18.2 s with 93.5 m of path for 80 m straight, never closer than 1.79 m to a trunk.

05

Where histograms still fail

VFH looks only at the current surroundings. A dead end, or a goal behind a wall longer than the sensor range, can lead it into a pocket it has to back out of, and two valleys of equal cost can still make it hesitate. VFH* (Ulrich and Borenstein, 2000) checks each candidate direction with an A* look-ahead over the projected positions before committing. The flight stacks use the same ideas: ArduPilot's BendyRuler probes directions around the vehicle up to OA_BR_LOOKAHEAD, typically 5 m, and picks one that is open enough while moving towards the destination, keeping OA_MARGIN_MAX from obstacles; PX4's collision prevention keeps its obstacle map in angular bins and may turn the commanded direction by up to CP_GUIDE_ANG towards a freer bin. Too few sectors or too much widening close real gaps, too little lets the vehicle scrape past trunks, so tune the margin against the vehicle's measured tracking error.

06

Fly it in GopherForge

In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output lists naive.gfflight, which ends at the gate, and flight.gfflight, which weaves south of the gate and through the trees to the goal marker. Change rs from 1.5 to 0.8 m and the path straightens while the closest approach shrinks to about 1 m; set turn to 0.5 rad/s and the drone swings wide and slows while its heading lags the choice.

TAKE THIS WITH YOU

Reduce the scan to a ring of sectors, block a sector with hysteresis, widen every reading by asin((radius + margin) / d) so gaps narrower than the vehicle close, choose the free sector with a cost dominated by the goal direction, and limit the turn rate and the speed. It is fast and decisive, and still local.

Check your understanding

A VFH-style planner flies a drone into a gap between two trees that is narrower than the drone. Which step was missing?

Go to the source

Progress stays in this browser. No account needed.