Flight control: PID, cascades, filters and loops · 5 MIN READ
Flight modes as an explicit state machine
Model flight modes as states, events and guarded transitions in a table, reject invalid requests with reasons, run pre-arm checks for battery, GPS fix and geofence, map the states onto the simulator's modes and log every transition.
Ground stations and companion computers tend to grow their flight-mode logic one if statement at a time, until nobody can say whether a go-to is allowed while the vehicle returns home. Writing it as a table of transitions with guards makes every allowed path visible, every refusal explainable and the whole logic testable without a vehicle. The autopilot keeps its own modes and checks; this machine decides what your program will ask of it.
drones · A MAP OF THE IDEA
- Snapshot vehicle state
- Match row, run guard
- Command, then commit
- Log transition or reason
Useful when
- Every allowed path is in one table you can review and test.
- Refusals carry reasons the operator can act on.
Watch out
- The autopilot can change mode itself; reconcile, do not fight.
- Guards that read clocks or I/O make the machine hard to test.
Implementation & operation cost: A table, a few pure guard functions and a monitor that turns telemetry into events.
States, events and guards
The machine has seven states: DISARMED, ARMED, TAKEOFF, HOLD, MISSION, RTL and LAND. Events come from three places: requests from an operator or mission (arm, takeoff, goto, hold, rtl, land, disarm), reports from the vehicle (reached, touchdown) and the program's own monitor (battery low). Each row of the table names a state, an event, the next state and an optional guard. Guards are pure functions of a snapshot of the vehicle and the request: preArm needs at least 40% battery, at least 6 GPS satellites and a position inside the geofence; take-off and go-to altitudes must lie between 2 m and the 60 m ceiling; a go-to target must be inside the fence and the battery well above the 30% reserve. An event without a matching row is rejected. preArm reports every failing check at once with errors.Join, so the operator can fix all of them before the next attempt instead of discovering them one by one.
The table, tested and flown
The program first runs nine table-driven cases against fresh machines, without any vehicle. Then it flies: the GPS model gains satellites over the first seconds, the program requests arm, take-off, go-tos inside and outside the fence and a disarm in flight, and a monitor turns the simulator's reports into reached events (d.Arrived()) and touchdown events and raises battery low at the 30% reserve. The simulator starts with 45% battery, so after the second leg the program only waits in HOLD until the monitor's reserve check sends the drone home. Each transition is printed with the simulated time and marked on the replay.
package main
// Flight modes as an explicit state machine: a transition table with
// guards, rejected requests with reasons, and a logged run that drives the
// simulator only through the machine's decisions.
import (
"errors"
"fmt"
"strings"
"gopherforge.app/drone"
)
type State int
const (
Disarmed State = iota
Armed
TakingOff
Holding
Mission
Returning
Landing
)
var stateNames = [...]string{"DISARMED", "ARMED", "TAKEOFF", "HOLD", "MISSION", "RTL", "LAND"}
func (s State) String() string { return stateNames[s] }
type Event int
const (
Arm Event = iota
Disarm
TakeOff
GoTo
Hold
ReturnHome
Land
Reached // from the vehicle: take-off altitude or waypoint reached
Touchdown // from the vehicle: on the ground and disarmed
BatteryLow // from our own monitor
)
var eventNames = [...]string{"arm", "disarm", "takeoff", "goto", "hold", "rtl", "land", "reached", "touchdown", "battery low"}
func (e Event) String() string { return eventNames[e] }
// Snapshot is what guards may look at.
type Snapshot struct {
Battery float64 // percent
Sats int // GPS satellites used in the fix
Pos drone.Vec3
}
// Request is an event with its argument.
type Request struct {
Event Event
Target drone.Vec3 // take-off altitude in Z, or the go-to point
}
func (r Request) String() string {
switch r.Event {
case TakeOff:
return fmt.Sprintf("takeoff %.0f m", r.Target.Z)
case GoTo:
return "goto " + r.Target.String()
}
return r.Event.String()
}
// Rules are the limits the guards enforce.
type Rules struct {
MinArmBattery float64
Reserve float64 // below this, return home
MinSats int
Fence []drone.Vec3
Ceiling float64
}
type Guard func(Rules, Snapshot, Request) error
type Transition struct {
From State
Event Event
To State
Guard Guard
}
// preArm reports every failing check at once, as a ground station should.
func preArm(r Rules, s Snapshot, _ Request) error {
var errs []error
if s.Battery < r.MinArmBattery {
errs = append(errs, fmt.Errorf("battery %.0f%% < %.0f%%", s.Battery, r.MinArmBattery))
}
if s.Sats < r.MinSats {
errs = append(errs, fmt.Errorf("GPS %d satellites < %d", s.Sats, r.MinSats))
}
if !drone.Inside(r.Fence, s.Pos) {
errs = append(errs, errors.New("outside geofence"))
}
return errors.Join(errs...)
}
func altitudeOK(r Rules, _ Snapshot, q Request) error {
if q.Target.Z <= 2 || q.Target.Z > r.Ceiling {
return fmt.Errorf("altitude %.0f m outside 2..%.0f m", q.Target.Z, r.Ceiling)
}
return nil
}
func targetOK(r Rules, s Snapshot, q Request) error {
if !drone.Inside(r.Fence, q.Target) {
return fmt.Errorf("target %v outside geofence", q.Target)
}
if s.Battery < r.Reserve+5 {
return fmt.Errorf("battery %.0f%% too close to reserve", s.Battery)
}
return altitudeOK(r, s, q)
}
var table = []Transition{
{Disarmed, Arm, Armed, preArm},
{Armed, Disarm, Disarmed, nil},
{Armed, TakeOff, TakingOff, altitudeOK},
{TakingOff, Reached, Holding, nil},
{Holding, GoTo, Mission, targetOK},
{Mission, GoTo, Mission, targetOK},
{Mission, Reached, Holding, nil},
{Mission, Hold, Holding, nil},
{Returning, Hold, Holding, nil},
{TakingOff, ReturnHome, Returning, nil},
{Holding, ReturnHome, Returning, nil},
{Mission, ReturnHome, Returning, nil},
{TakingOff, BatteryLow, Returning, nil},
{Holding, BatteryLow, Returning, nil},
{Mission, BatteryLow, Returning, nil},
{Holding, Land, Landing, nil},
{Mission, Land, Landing, nil},
{Returning, Land, Landing, nil},
{Returning, Touchdown, Disarmed, nil},
{Landing, Touchdown, Disarmed, nil},
}
// Machine holds the current state. Fire finds the transition, checks its
// guard, lets act command the vehicle and commits only if act succeeds.
type Machine struct {
State State
Rules Rules
Log func(from, to State, r Request)
}
func (m *Machine) Fire(s Snapshot, r Request, act func(Request) error) error {
for _, tr := range table {
if tr.From != m.State || tr.Event != r.Event {
continue
}
if tr.Guard != nil {
if err := tr.Guard(m.Rules, s, r); err != nil {
return fmt.Errorf("%v in %v rejected: %s", r, m.State, strings.ReplaceAll(err.Error(), "\n", "; "))
}
}
if act != nil {
if err := act(r); err != nil {
return fmt.Errorf("%v in %v: vehicle refused: %w", r, m.State, err)
}
}
from := m.State
m.State = tr.To
if m.Log != nil {
m.Log(from, m.State, r)
}
return nil
}
return fmt.Errorf("%v not allowed in %v", r, m.State)
}
func main() {
fence := []drone.Vec3{{X: -100, Y: -100}, {X: 100, Y: -100}, {X: 100, Y: 100}, {X: -100, Y: 100}}
rules := Rules{MinArmBattery: 40, Reserve: 30, MinSats: 6, Fence: fence, Ceiling: 60}
fmt.Println("table-driven checks:")
good := Snapshot{Battery: 90, Sats: 12}
cases := []struct {
from State
snap Snapshot
req Request
}{
{Disarmed, good, Request{Event: Arm}},
{Disarmed, Snapshot{Battery: 35, Sats: 4, Pos: drone.Vec3{X: 140}}, Request{Event: Arm}},
{Armed, good, Request{TakeOff, drone.Vec3{Z: 80}}},
{Holding, good, Request{GoTo, drone.Vec3{X: 150, Z: 20}}},
{Holding, Snapshot{Battery: 33, Sats: 12}, Request{GoTo, drone.Vec3{X: 50, Z: 20}}},
{Mission, good, Request{Event: Disarm}},
{Disarmed, good, Request{GoTo, drone.Vec3{X: 10, Z: 10}}},
{Mission, good, Request{Event: BatteryLow}},
{Returning, good, Request{Event: Hold}},
}
for _, c := range cases {
m := &Machine{State: c.from, Rules: rules}
if err := m.Fire(c.snap, c.req, nil); err != nil {
fmt.Println(" no: ", err)
} else {
fmt.Printf(" ok: %v + %v -> %v\n", c.from, c.req, m.State)
}
}
sim := drone.New(drone.Config{Geofence: fence, Ceiling: rules.Ceiling, Battery: 45, Seed: 7})
d := sim.Drone()
snapshot := func() Snapshot {
st := d.State()
sats := min(int(sim.Time()*1.5), 14) // the receiver needs a few seconds for a fix
return Snapshot{Battery: st.Battery, Sats: sats, Pos: st.Pos}
}
m := &Machine{State: Disarmed, Rules: rules}
m.Log = func(from, to State, r Request) {
line := fmt.Sprintf("%v -> %v (%v)", from, to, r)
fmt.Printf(" %5.1f s %s\n", sim.Time(), line)
sim.Mark(line)
}
act := func(r Request) error {
switch r.Event {
case Arm:
return d.Arm()
case TakeOff:
return d.TakeOff(r.Target.Z)
case GoTo:
return d.GoTo(r.Target)
case Hold:
return d.Hold()
case ReturnHome, BatteryLow:
return d.ReturnHome()
case Land:
return d.Land()
}
return nil // disarm on the ground, reached, touchdown: nothing to command
}
request := func(r Request) {
if err := m.Fire(snapshot(), r, act); err != nil {
fmt.Printf(" %5.1f s no: %v\n", sim.Time(), err)
}
}
// monitor turns what the vehicle reports into events, once per step.
monitor := func(float64) {
st, s := d.State(), m.State
switch {
case (s == TakingOff || s == Mission) && d.Arrived():
m.Fire(snapshot(), Request{Event: Reached}, nil)
case (s == Returning || s == Landing) && st.Landed:
m.Fire(snapshot(), Request{Event: Touchdown}, nil)
case (s == TakingOff || s == Holding || s == Mission) && st.Battery <= rules.Reserve:
request(Request{Event: BatteryLow})
}
}
settle := func(want State, limit float64) {
sim.RunUntil(limit, func(t float64) bool { monitor(t); return m.State == want || m.State == Returning })
}
fmt.Println("flight:")
request(Request{Event: Arm})
sim.Run(5, nil)
request(Request{Event: Arm})
request(Request{TakeOff, drone.Vec3{Z: 80}})
request(Request{TakeOff, drone.Vec3{Z: 20}})
settle(Holding, 30)
request(Request{GoTo, drone.Vec3{X: 150, Z: 20}})
request(Request{Event: Disarm})
request(Request{GoTo, drone.Vec3{X: 80, Y: 60, Z: 30}})
settle(Holding, 60)
request(Request{GoTo, drone.Vec3{X: -70, Y: 80, Z: 30}})
settle(Holding, 90)
sim.RunUntil(120, func(t float64) bool { monitor(t); return m.State == Disarmed })
fmt.Printf("machine %v, simulator %v\n", m.State, d.State().Mode)
sim.Save()
}The checks show one valid arm, an arm rejected for three reasons at once (battery 35% < 40%; GPS 4 satellites < 6; outside geofence), a take-off to 80 m outside 2..60 m, a target outside the fence, a go-to refused at 33% battery, disarm not allowed in MISSION and goto not allowed in DISARMED. In flight, arming at 0.0 s fails with GPS 0 satellites < 6 and succeeds at 5.0 s; the take-off reaches HOLD at 13.3 s; the go-to outside the fence and the disarm are refused; the legs end at 23.9 s and 38.8 s; battery low switches HOLD to RTL at 58.0 s; touchdown at 86.5 s ends in DISARMED while the simulator reports LANDED, with 23% battery left.
Command the vehicle, then commit
Fire finds the row, checks the guard, lets the act function command the vehicle and changes state only if the command was accepted; if the autopilot refuses, the machine stays where it was and the error explains why. The vehicle can also change mode by itself: geofence breach, low battery and lost link failsafes all act inside the autopilot. A machine that ignores them believes it is flying a mission while the vehicle returns home. So translate the vehicle's reported mode (a MAVLink HEARTBEAT's custom mode, or State().Mode here) into the machine's terms and, when the two disagree, let the vehicle win and log the reconciliation. The reason arrives separately, as STATUSTEXT messages over MAVLink; in the simulator, sim.Events() returns the autopilot's notes, such as battery 20%: return to home.
// fromVehicle maps the simulator's mode onto the machine's states, for
// reconciling after the autopilot changed mode on its own.
func fromVehicle(m drone.Mode) (State, bool) {
switch m {
case drone.Idle, drone.Landed:
return Disarmed, true
case drone.Armed:
return Armed, true
case drone.TakingOff:
return TakingOff, true
case drone.Hold:
return Holding, true
case drone.GoingTo:
return Mission, true
case drone.Returning:
return Returning, true
case drone.Landing:
return Landing, true
}
return 0, false // Velocity, Manual, Crashed: outside this machine
}Every simulator mode that the machine knows maps to exactly one state. The modes it does not model, offboard velocity, manual thrust and a crash, return false, which the program should treat as leaving the machine's authority and report rather than guess.
Logging and testing transitions
Log every transition with the time, the old and new state and the cause, and log every rejection too: rejections explain why a drone did not move. In the simulator, sim.Mark puts each line on the replay's timeline. The table-driven cases are unit tests as they stand; the table also supports structural tests, such as a graph search proving that every airborne state can reach RTL and LAND and that nothing leaves DISARMED except arm. Keep clocks and I/O out of guards so that a test can build any snapshot. Over MAVLink, arming is MAV_CMD_COMPONENT_ARM_DISARM and mode changes are MAV_CMD_DO_SET_MODE; the COMMAND_ACK the autopilot returns is where act gets its error, and the autopilot's own pre-arm checks still apply.
Fly it in GopherForge
Use New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay) and Run. The console prints the checks and the transition log; Output replays the flight with the square geofence, the waypoints and a timeline mark for every transition: the take-off, the first leg, the battery-low return and the landing. Change the battery in drone.Config, the rules or the requests and watch which transitions are refused.
TAKE THIS WITH YOU
Write flight modes as a transition table with pure guards: the allowed paths are visible, every refusal carries a reason and the logic is testable without a vehicle. Command the vehicle before committing a transition, and treat modes the autopilot reports, especially failsafes, as events that win.
Check your understanding
A ground station's state machine receives goto while in DISARMED, and no row of its transition table matches. What should happen?
Go to the source
Progress stays in this browser. No account needed.