Missions, safety and fleets · 7 MIN READ

Failsafes: battery energy budgets, link-loss timeouts and which action wins

Explain state of charge and voltage sag, estimate the charge needed to fly home against the wind with a reserve, compare that budget with fixed battery thresholds in the simulator, and design link-loss timeouts and failsafe priorities.

Failsafes are the code paths that run when something has already gone wrong: the battery is low, the link is gone, the position estimate is bad, the vehicle left its fence. Normal flights rarely exercise them, which is exactly why they hide bugs. A fixed rule such as 'at 20 percent, return home' is a good last resort and a poor plan, because whether 20 percent is enough depends on how far away home is and which way the wind blows.

drones · A MAP OF THE IDEA

  1. Fit drain from logs
  2. Budget home plus reserve
  3. Turn back at the need
  4. Keep thresholds as backup

Useful when

  • The turn-back point adapts to distance and wind.
  • Fixed thresholds remain an independent last resort.

Watch out

  • Voltage sag and cold packs distort charge estimates.
  • A reserve below the land failsafe ends in a forced landing.

Implementation & operation cost: A consumption model fitted from flight logs, a budget check in the control loop and a test for every failsafe path.

01

State of charge, voltage and sag

A lithium polymer cell rests near 4.2 V when full and falls through about 3.7 V as it empties, and under load its terminal voltage drops by the current times its internal resistance. A burst of throttle sags the pack for a moment, and cold or ageing packs sag more, so a voltage threshold fires early in a climb and late in a gentle hover. That is why ArduPilot's battery failsafe waits until the voltage has stayed low for BATT_LOW_TIMER seconds (10 by default) and BATT_FS_VOLTSRC can select a sag-compensated voltage. Counting consumed charge (the BATT_LOW_MAH style of threshold) or a smart battery's own state of charge is steadier, but needs an accurate capacity and current sensor. The simulator reports percent directly; its drain follows thrust, about 0.18 percent per second in a hover, plus a term that grows with the square of the airspeed, so holding against the wind costs energy.

02

An energy budget for the way home

The question to ask at every moment is: if I turned back now, would I land with my reserve? Answer it with the distance home, the wind and a consumption model fitted from logs. Autopilots usually fly home at a set ground speed, so a headwind first raises the airspeed, and drain grows with airspeed; once the airframe is at its top airspeed, more headwind lowers the ground speed instead, and a crosswind must be cancelled from the same airspeed. Time home is the distance over that ground speed, padded for the turn and the approach; multiply by the drain at that airspeed, add the descent and the reserve. The reserve sits above the critical level: if the land failsafe fires at 10 percent, a reserve of 8 ends in a forced landing short of home. If the wind beats the airframe there is no way home, and the budget must say so. PX4 builds this in as its distance-aware return failsafe: it compares the estimated time for the return path, padded by RTL_TIME_FACTOR and RTL_TIME_MARGIN, with the battery's remaining flight time, and once it has triggered it does not cancel when the estimate improves.

03

Thresholds against a budget

The program first prints the charge needed from 100, 300 and 500 m in calm air, against 5, 12 and 20 m/s headwinds and in a 10 m/s crosswind. Then it flies the same mission twice on a 45 percent battery: out to x=600 m with a 5 m/s wind behind it, then a hover there for an inspection; the way home is into the wind. Both flights print the autopilot's events live from sim.Events(), as a ground station receives STATUSTEXT messages. The first relies only on the simulator's fixed failsafes; the second checks the budget once per second and turns back when the charge it has reaches the charge it needs.

go
package main

import (
	"fmt"
	"log"
	"math"

	"gopherforge.app/drone"
)

// Budget estimates the charge needed to fly home and land from where the
// drone is now. The autopilot flies home at a set ground speed unless the
// airframe's top airspeed cannot make it; drain is hover plus a term that
// grows with airspeed squared, fitted from flight logs.
type Budget struct {
	Speed   float64 // ground speed the autopilot flies home, m/s
	MaxAir  float64 // top airspeed of the airframe, m/s
	Hover   float64 // drain in a hover, %/s
	Drag    float64 // extra drain per (m/s of airspeed)^2, %/s
	Factor  float64 // time margin for the turn, braking and the approach
	Descent float64 // average descent rate, m/s
	Reserve float64 // charge to keep on the ground, %: above the land failsafe
}

// Need returns the charge to get home, the ground speed and airspeed it
// assumes, and the time it takes. A headwind raises the airspeed for the
// same ground speed; once the airspeed limit is reached it lowers the
// ground speed instead. If the wind beats the airframe, the need is infinite.
func (b Budget) Need(p, home, wind drone.Vec3) (need, groundSpeed, airspeed, seconds float64) {
	toHome := home.Sub(p).Horizontal()
	dist := toHome.Len()
	u := drone.Vec3{X: 1}
	if dist > 0 {
		u = toHome.Scale(1 / dist)
	}
	along := wind.X*u.X + wind.Y*u.Y  // tailwind on the way home
	across := wind.X*u.Y - wind.Y*u.X // crosswind the airframe must cancel
	inf := math.Inf(1)
	if across*across >= b.MaxAir*b.MaxAir {
		return inf, 0, b.MaxAir, inf
	}
	groundSpeed = math.Min(b.Speed, along+math.Sqrt(b.MaxAir*b.MaxAir-across*across))
	if groundSpeed <= 0.5 {
		return inf, groundSpeed, b.MaxAir, inf
	}
	airspeed = u.Scale(groundSpeed).Sub(wind.Horizontal()).Len()
	cruise, descend := b.Factor*dist/groundSpeed, p.Z/b.Descent
	need = cruise*(b.Hover+b.Drag*airspeed*airspeed) + descend*b.Hover + b.Reserve
	return need, groundSpeed, airspeed, cruise + descend
}

var (
	wind   = drone.Vec3{X: 5} // blowing east: a tailwind out, a headwind home
	target = drone.Vec3{X: 600, Z: 20}
	budget = Budget{Speed: 10, MaxAir: 18, Hover: 0.18, Drag: 0.0016, Factor: 1.1, Descent: 1.5, Reserve: 15}
)

// fly sends the drone out to the target, where it holds for an inspection,
// and prints the autopilot's events as a ground station receives them.
func fly(useBudget bool) *drone.Sim {
	sim := drone.New(drone.Config{Wind: wind, Gust: 0.5, Battery: 45, MaxSpeed: 10, Seed: 9})
	d := sim.Drone()
	if err := d.Arm(); err != nil {
		log.Fatal(err)
	}
	d.TakeOff(20)
	sim.RunUntil(30, func(float64) bool { return d.Arrived() })
	seen := len(sim.Events())
	d.GoTo(target)
	turned, atTurn := false, 0.0
	sim.RunUntil(400, func(t float64) bool {
		st := d.State()
		events := sim.Events()
		for _, e := range events[seen:] {
			fmt.Printf("  %5.1f s  %-35s battery %4.1f%%  %5.1f m out\n", e.T, e.Text, st.Battery, st.Pos.Horizontal().Len())
		}
		seen = len(events)
		onSecond := math.Abs(t-math.Round(t)) < sim.Dt()/2
		if useBudget && !turned && onSecond && (st.Mode == drone.GoingTo || st.Mode == drone.Hold) {
			need, gs, air, secs := budget.Need(st.Pos, d.Home(), wind)
			if st.Battery <= need {
				turned, atTurn = true, st.Battery
				fmt.Printf("  %5.1f s  budget: need %.1f%% (%.0f s home at %.1f m/s, airspeed %.1f), have %.1f%%\n",
					t, need, secs, gs, air, st.Battery)
				d.ReturnHome()
			}
		}
		return st.Landed
	})
	st := d.State()
	if turned {
		fmt.Printf("  used %.1f%% to get home, budgeted %.1f%% plus the %.0f%% reserve\n",
			atTurn-st.Battery, atTurn-budget.Reserve, budget.Reserve)
	}
	fmt.Printf("  %s %.1f m from home with %.1f%%\n", st.Mode, st.Pos.Horizontal().Len(), st.Battery)
	return sim
}

func main() {
	fmt.Println("charge to get home from x m east at 20 m (10 m/s home, 18 m/s top airspeed, 15% reserve)")
	fmt.Printf("  %-5s%13s%13s%13s%13s%13s\n", "x", "calm", "5 m/s head", "12 m/s head", "20 m/s head", "10 m/s cross")
	for _, dist := range []float64{100, 300, 500} {
		fmt.Printf("  %3.0f m ", dist)
		for _, w := range []drone.Vec3{{}, {X: 5}, {X: 12}, {X: 20}, {Y: 10}} {
			need, _, _, _ := budget.Need(drone.Vec3{X: dist, Z: 20}, drone.Vec3{}, w)
			cell := fmt.Sprintf("%.1f%%", need)
			if math.IsInf(need, 1) {
				cell = "no way home"
			}
			fmt.Printf("%13s", cell)
		}
		fmt.Println()
	}

	fmt.Println("\nfixed thresholds only: out to x=600 m on 45%, hold there")
	fixed := fly(false)
	if err := fixed.SaveAs("thresholds"); err != nil {
		log.Fatal(err)
	}

	fmt.Println("\nenergy budget checked every second, same mission")
	sim := fly(true)
	if err := sim.Save(); err != nil {
		log.Fatal(err)
	}
}
Read the code

Wind, not distance alone, decides: from 300 m the need is 28.6 percent in calm air, 35.2 against 5 m/s, where the ground speed stays 10 m/s but the airspeed rises to 15, and 55.8 against 12 m/s, where the 18 m/s airspeed limit leaves 6 m/s over the ground; against 20 m/s there is no way home. With thresholds only, the drone arrives at x=600 m with 29.2 percent and hovers until the event 'battery 20%: return to home' at 112.4 s, 600.0 m out; 'battery 10%: forced landing' follows at 131.3 s, 422.4 m out, and it lands 422.7 m from home with 7.0. With the budget, at 40.0 s and 310.0 m out the need of 35.8 percent meets the charge; the return used 20.9 points against 20.8 budgeted and lands at home with 14.9, the 15 percent reserve.

04

Link loss is a timeout

A vehicle cannot tell a dead ground station from a radio fade, so link loss is a timeout on heartbeats. ArduPilot's GCS failsafe fires when no ground-station HEARTBEAT has arrived for FS_GCS_TIMEOUT seconds (5 by default); PX4 uses COM_DL_LOSS_T with the action in NAV_DLL_ACT. Loss of manual control has its own short timeout (COM_RC_LOSS_T in PX4), because the vehicle keeps flying on the last stick input until it fires. Too short and every fade triggers a return; too long and a runaway keeps going. The ground station needs the mirror image: notice a silent vehicle, warn the operator, and never queue commands during an outage to replay them later. In Go, a watchdog is a timer that every heartbeat resets.

go
func Watch(ctx context.Context, beats <-chan struct{}, timeout time.Duration, lost func(bool)) {
	t := time.NewTimer(timeout)
	defer t.Stop()
	down := false
	for {
		select {
		case <-ctx.Done():
			return
		case <-beats:
			if down {
				down = false
				lost(false)
			}
			t.Reset(timeout)
		case <-t.C:
			down = true
			lost(true)
		}
	}
}
Read the code

Every heartbeat pushes the deadline back with Reset; since Go 1.23, Reset and Stop never leave a stale tick in the channel, so no draining is needed. The timer fires once per outage and is re-armed only by the next heartbeat, which also reports recovery. Wrapped in testing/synctest, a test drives this with a fake clock, so a 5 s timeout is checked instantly and deterministically.

05

Priorities, and testing every failsafe

Several failsafes can fire together: a low battery during link loss outside the fence. PX4 orders actions by severity (warning, hold, return, land, disarm, flight termination) and takes the most severe one, by default after holding for COM_FAIL_ACT_T seconds so an operator can intervene. Land beats return when the battery cannot reach home, when the position estimate is bad (ArduPilot's battery RTL falls back to Land without a good position) or when the return path is unsafe; return beats land over water, roads or people. Write the table down and test each row: in a simulator, in SITL with the flight stack's own failsafe code, and on a field with a pilot ready to take over. A failsafe that has never fired in a test has unknown behaviour, and one that fires in every flight teaches operators to ignore it.

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 two recordings: thresholds.gfflight hovers at x=600 m and ends in a field 423 m east of home, and flight.gfflight turns back 310 m out and lands at home; the HUD's battery shows where each decision was taken. Raise the wind to 8 m/s, or lower the reserve to 8 percent, below the 10 percent land failsafe, and watch where the drone lands.

TAKE THIS WITH YOU

A fixed battery threshold ignores distance and wind; a budget compares the charge you have with the charge needed to fly home against the wind, descend and keep a reserve above the land failsafe, and turns back in time. Treat link loss as a heartbeat timeout, decide which action wins when several failsafes fire, and test every one of them.

Check your understanding

A drone with an 'at 20 percent, return home' failsafe is forced to land far from home with 10 percent left. What did the rule miss?

Go to the source

Progress stays in this browser. No account needed.