Module 5/5 · Weeks 13–15 · 27 h

Failsafes and geofences

UAT 305 Autopilot and Control Technology

About 85 minDraft, awaiting reviewLast updated 2 October 2026

Lesson

By the end of this module you will be able to

  1. Configure altitude, circle and polygon geofences, both inclusion and exclusion
  2. Check with a program whether points are inside or outside the fences, or within the margin of an edge
  3. Verify from a log that the GCS failsafe acted at the configured time
  4. Design failsafe and geofence tests before real use
  5. Explain ArduPilot's position loop, velocity loop and path following, and the effect of the I term on error in wind
  6. Test position-tracking performance from logs against measurable criteria

Prerequisites: UAT 305 Modules 1–4 · UAT 304 Module 4 (failsafes in missions)

Why this matters

UAT 304 planned routes and stepped through failsafe events in missions. This module looks from the autopilot’s side: how to configure them and how to prove they work. The drone knowledge base’s unit on PX4 and ArduPilot architecture covers failsafes and geofences, and its lab on stopping and resuming a simulated link records the behaviour when telemetry drops.

Types of geofence in ArduPilot

FENCE_TYPE is a bitmask: 1 = maximum altitude, 2 = circle around home, 4 = inclusion and exclusion polygons and circles, 8 = minimum altitude. The Copter 4.7.1 default is 7. FENCE_ACTION sets what happens on a breach, for example 1 = RTL or land (the default), 2 = always land, 4 = Brake or Land (brake, or land if braking is not possible), and FENCE_MARGIN is the distance kept from the edge (default 2 m). The documentation on inclusion and exclusion fences explains that an inclusion fence is an area the vehicle must stay inside and an exclusion fence is an area it must not enter; polygons can have up to 70 points and are uploaded from the GCS over MAVLink2.

Example 1 Checking points against inclusion and exclusion fences

The inclusion fence is a 400 × 300 m rectangle with an exclusion fence around a tall building inside. Ray casting checks whether a point is inside, and the distance to the nearest edge is computed.

import math

INCLUSION = [(0, 0), (400, 0), (400, 300), (0, 300)]            # m
EXCLUSION = [(250, 120), (320, 120), (320, 200), (250, 200)]    # tall building
MARGIN = 2.0                                                    # FENCE_MARGIN

def inside(p, poly):
    x, y, c = p[0], p[1], False
    for i in range(len(poly)):
        (x1, y1), (x2, y2) = poly[i], poly[(i + 1) % len(poly)]
        if (y1 > y) != (y2 > y) and x < x1 + (y - y1) * (x2 - x1) / (y2 - y1):
            c = not c
    return c

def dist_to_edge(p, poly):
    best = math.inf
    for i in range(len(poly)):
        (ax, ay), (bx, by) = poly[i], poly[(i + 1) % len(poly)]
        dx, dy = bx - ax, by - ay
        t = max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / (dx * dx + dy * dy)))
        best = min(best, math.hypot(p[0] - (ax + t * dx), p[1] - (ay + t * dy)))
    return best

for p in [(100, 100), (398.5, 150), (300, 150), (410, 50)]:
    if not inside(p, INCLUSION):
        verdict = "BREACH: outside inclusion fence"
    elif inside(p, EXCLUSION):
        verdict = "BREACH: inside exclusion zone"
    elif min(dist_to_edge(p, INCLUSION), dist_to_edge(p, EXCLUSION)) < MARGIN:
        verdict = "within margin of a fence edge"
    else:
        verdict = "ok"
    print(f"{p}: {verdict}")
(100, 100): ok
(398.5, 150): within margin of a fence edge
(300, 150): BREACH: inside exclusion zone
(410, 50): BREACH: outside inclusion fence

The point only 1.5 m from the edge has not breached the fence but is within the margin, which ArduPilot uses to keep missions or guided flight from getting too close to the edge. Checking missions against fences with a program before upload catches misplaced waypoints before flight.

A large green rectangle for the inclusion fence and a small pink rectangle inside for the exclusion fence around a building, with four points: a blue one in the middle, a gold one near the right edge, a pink one inside the exclusion fence and a pink one outside the inclusion fence
Figure 1 Inclusion and exclusion fences with test points

Proving the GCS failsafe from a log

The GCS sends HEARTBEAT messages to the aircraft regularly. According to the MAVLink documentation, radio links typically send them at 1 Hz and consider the connection lost after about four or five missed messages, but MAVLink does not define a fixed rate or timeout. ArduPilot uses FS_GCS_TIMEOUT (default 5 seconds, range 2–120): if no heartbeat arrives for longer than this, the GCS failsafe acts according to FS_GCS_ENABLE.

Example 2 Did the failsafe act on time?

The times at which the aircraft received GCS heartbeats, and the time the log recorded the mode change to RTL, from a SITL test (simulated data).

TIMEOUT = 5.0                                   # FS_GCS_TIMEOUT
TOLERANCE = 0.5                                 # s, tolerance accepted by the team
heartbeats = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9.1, 10, 16.4, 17.4, 18.4]   # s
mode_change_rtl = 15.2                          # s from the log

gaps = [(heartbeats[i], heartbeats[i + 1] - heartbeats[i]) for i in range(len(heartbeats) - 1)]
for start, gap in gaps:
    if gap > TIMEOUT:
        expected = start + TIMEOUT
        diff = mode_change_rtl - expected
        print(f"link lost after t={start}s for {gap:.1f}s -> failsafe expected at {expected:.1f}s")
        print(f"logged RTL at {mode_change_rtl}s ({diff:+.1f}s) -> {'as configured' if abs(diff) <= TOLERANCE else 'CHECK SETTINGS'}")
print(f"largest gap without failsafe: {max(g for _, g in gaps if g <= TIMEOUT):.1f}s")
link lost after t=10s for 6.4s -> failsafe expected at 15.0s
logged RTL at 15.2s (+0.2s) -> as configured
largest gap without failsafe: 1.1s

The failsafe acted only slightly after the expected time, so it worked as configured. A gap of just over 1 second did not trigger it, which is the intended behaviour. If the timing differs a lot, check whether FS_GCS_ENABLE is set correctly and whether another GCS is still sending heartbeats.

A timeline from 0 to 19 seconds: blue ticks for each heartbeat, a gap from 10 to 16.4 seconds, a gold dashed line at 15 seconds where the failsafe is expected and a pink line at 15.2 seconds where the log records RTL
Figure 2 Missing heartbeats and failsafe timing

The position loop and path following

Geofences and failsafes can only stop the aircraft if the position controller works well. It is the outermost layer of the cascade from Module 2. ArduPilot’s developer page on Copter position control and navigation describes the horizontal structure as follows.

  1. The position loop. A P controller turns position error into a target velocity (PSC_NE_POS_P, default 1.0 in Copter 4.7.1; named PSC_POSXY_P in 4.6.3 and earlier)
  2. The velocity loop. A PID controller turns velocity error into a target acceleration (PSC_NE_VEL_P 2.0, PSC_NE_VEL_I 1.0, PSC_NE_VEL_D 0.25 in the 4.7.1 source code; PSC_VELXY_P, _I and _D with the same defaults in 4.6.3 and earlier). The I term removes errors that persist, such as those caused by a steady wind
  3. Acceleration to lean angle using from the flight dynamics in Module 2, which is then passed to the attitude controller. The acceleration is limited by the maximum lean angle ATC_ANGLE_MAX (or PSC_ANGLE_MAX if it is set; ANGLE_MAX in 4.6.3 and earlier)

The position controller does not always wait for an error to appear: the source code adds the desired velocity and acceleration (feedforward) to the P and PID outputs. Path following is done by the AC_WPNav library, which tries to fly a straight line to the target waypoint. WPNav itself does not use PIDs directly; it moves the target position and velocity along the path and lets the position controller keep up. The perpendicular distance from the actual position to the planned path is the cross-track error, which can be computed with this module’s point-to-segment distance formula. PX4 uses a similar structure, a position P followed by a velocity PID, as shown in the PX4 controller diagrams.

Example 3 A crosswind and cross-track error

Only the axis perpendicular to the path is simulated. The aircraft is flying along the line when, at t = 5 s, a 4 m/s crosswind starts. The position gain 1.0 and velocity P 2.0 match the defaults; the cases without and with the velocity I term are compared (a teaching model: the attitude loop is a 0.15 s time constant and wind drag is linear).

import math

G, DT, T_END = 9.81, 0.01, 20.0
ANGLE_MAX = 30                                  # degrees, the ATC_ANGLE_MAX default
A_MAX = G * math.tan(math.radians(ANGLE_MAX))   # maximum horizontal acceleration from lean angle

def cross_track(kp_pos, kp_vel, ki_vel, tau_att=0.15, drag=0.3, wind=4.0):
    """Single cross-track axis: a crosswind starts at t = 5 s (teaching model)"""
    y = v = a = integ = 0.0
    errs = []
    for k in range(int(T_END / DT)):
        t = k * DT
        v_air = wind if t >= 5 else 0.0         # crosswind speed m/s
        v_cmd = kp_pos * (0.0 - y)              # position P loop: error -> target velocity
        e_v = v_cmd - v
        integ += e_v * DT
        a_cmd = max(-A_MAX, min(A_MAX, kp_vel * e_v + ki_vel * integ))   # velocity PI loop
        a += (a_cmd - a) * DT / tau_att         # attitude loop follows the lean command with a lag
        v += (a + drag * (v_air - v)) * DT      # wind drag pushes the aircraft off the line
        y += v * DT
        errs.append(abs(y))
    after = errs[int(5 / DT):]
    rms = math.sqrt(sum(e * e for e in after) / len(after))
    return max(after), rms, errs[-1], math.degrees(math.atan(abs(a) / G))

for label, gains in (("velocity P only", (1.0, 2.0, 0.0)), ("velocity PI", (1.0, 2.0, 1.0))):
    mx, rms, final, tilt = cross_track(*gains)
    print(f"{label:<20} max {mx:.2f} m, RMS {rms:.2f} m, after 15 s {final:.2f} m, lean {tilt:.1f} deg")
velocity P only      max 0.60 m, RMS 0.57 m, after 15 s 0.60 m, lean 7.0 deg
velocity PI          max 0.40 m, RMS 0.14 m, after 15 s 0.00 m, lean 7.0 deg

Without the I term, the aircraft must stay 0.60 m off the line so that the P loops can produce enough acceleration to fight the wind, and this error never goes away. The I term accumulates the error until it holds a lean of about 7° against the wind with no error left, so the error returns to zero and the peak error is smaller too. Both cases lean the same amount in steady state because the wind force is the same. If the wind needed more lean than ATC_ANGLE_MAX, the acceleration would be limited and the error would grow until the controller could no longer keep up. These numbers come from the model and must be confirmed with real logs.

The test plan

Test every failsafe and geofence type in SITL first, then test some for real in a safe area, such as a low altitude ceiling and cutting the GCS link while hovering. Every test needs a measurable pass criterion, for example acting within 0.5 seconds of the expected time and breaching the fence by no more than 2 m, and results must be recorded with the firmware version and parameter file.

Flight performance testing

A failsafe test asks “does it work?”; a performance test asks “how well?”. A common autopilot measure is position-tracking accuracy, tested in four steps.

  1. Set the metric and pass criteria before flying, for example the RMS cross-track error (root mean square, which weights large errors more than a plain average) and the maximum error, together with the wind conditions and flight speed of the test.
  2. Fly a repeatable standard pattern, such as a 200 m straight line out and back, or a square, at the same speed every time, so that results before and after tuning can be compared.
  3. Extract data from the log. The ArduPilot log message list includes PSCN and PSCE, which record the target position (TPN, TPE), the actual position (PN, PE), and the target and actual velocities on the north and east axes.
  4. Choose the error that fits the question. Error to the moving target includes lag along the path, which does not make the images or the path wrong; cross-track error shows how far the aircraft leaves the line, which matters for corridor surveys and for staying inside fences.

A caution: the “actual” position in the log is the EKF’s estimate, not external truth. If the GNSS is 2 m off, both the log and the controller will see a perfectly straight flight while the whole aircraft is in the wrong place. Accuracy against the real ground needs an external measurement, such as RTK GNSS or a motion capture system.

Example 4 Assessing accuracy from PSCN and PSCE

A 200 m straight line north is flown at 8 m/s, with values taken every 2 seconds (simulated data). The team’s pass criteria are an RMS of at most 0.8 m and a maximum of at most 1.5 m (assumed criteria).

import math

A, B = (0.0, 0.0), (0.0, 200.0)                 # straight path to the north (E, N) m
log = [   # (TPE, TPN, PE, PN) m from PSCE/PSCN every 2 seconds (simulated data)
    (0, 20, 0.1, 18.9), (0, 36, 0.3, 34.8), (0, 52, 0.6, 50.7), (0, 68, 0.8, 66.9),
    (0, 84, 0.7, 82.8), (0, 100, 0.9, 98.7), (0, 116, 1.2, 114.9), (0, 132, 0.8, 130.8),
    (0, 148, 0.5, 146.9), (0, 164, 0.4, 162.7), (0, 180, 0.3, 178.8), (0, 196, 0.2, 194.9),
]
RMS_LIMIT, MAX_LIMIT = 0.8, 1.5                 # team pass criteria m (assumed)

def xtrack(p):
    (ax, ay), (bx, by) = A, B
    dx, dy = bx - ax, by - ay
    t = max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / (dx * dx + dy * dy)))
    return math.hypot(p[0] - (ax + t * dx), p[1] - (ay + t * dy))

def stats(errs):
    rms = math.sqrt(sum(e * e for e in errs) / len(errs))
    return rms, max(errs)

to_target = [math.hypot(pe - tpe, pn - tpn) for tpe, tpn, pe, pn in log]
cross = [xtrack((pe, pn)) for _, _, pe, pn in log]
for name, errs in (("error to moving target", to_target), ("cross-track error", cross)):
    rms, mx = stats(errs)
    verdict = "PASS" if rms <= RMS_LIMIT and mx <= MAX_LIMIT else "FAIL"
    print(f"{name:<23} RMS {rms:.2f} m, max {mx:.2f} m -> {verdict}")
error to moving target  RMS 1.35 m, max 1.63 m -> FAIL
cross-track error       RMS 0.65 m, max 1.20 m -> PASS

The same data can give opposite verdicts. The error to the target fails because the aircraft trails the target along the path by about 1.1–1.3 m the whole way, while the cross-track error passes. The test plan must therefore state clearly which error is measured. A steady lag like this is a cue to check the feedforward or the position-loop gain, while cross-track error that rises and falls mid-leg usually comes from the wind. Record results with the firmware version, parameter file, wind speed and flight speed, just as for failsafe tests.

Module lab

Lab: testing failsafes and geofences in SITL

  1. Draw inclusion and exclusion fences in the GCS, upload them to SITL and set FENCE_TYPE and FENCE_ACTION
  2. Export the fence and mission points and check them with Example 1
  3. Fly towards the fence in SITL and observe the stopping distance and action
  4. Cut the GCS link in SITL, collect heartbeat and mode-change times from the log and check them with Example 2
  5. Fly a 200 m straight line out and back in SITL with a simulated crosswind, extract PSCN and PSCE from the log and assess the error with Example 4, before and after changing PSC_NE_VEL_I
  6. Write a test report with the firmware version and parameter values

Common mistakes

Watch out

  • Enabling the fence with FENCE_ACTION set to report only
  • Drawing an exclusion fence over the take-off point, so the vehicle cannot arm or behaves wrongly
  • Not testing failsafes for real because the settings look right
  • Confusing log time with the time shown on the GCS
  • Changing values in the field without retesting
  • Measuring error to the moving target and concluding the aircraft left the line, or treating the logged position as external truth

Summary

  • FENCE_TYPE combines ceiling, circle, polygons and minimum altitude; FENCE_ACTION sets the action and FENCE_MARGIN the distance from edges
  • An inclusion fence is where the vehicle must stay and an exclusion fence where it must not go; both can be checked with ray casting and edge distance
  • The GCS failsafe acts when heartbeats are missing for longer than FS_GCS_TIMEOUT (default 5 seconds), which can be verified from the log
  • Test every type in SITL with measurable pass criteria before real use
  • The position P loop makes a target velocity and the velocity PID loop an acceleration, which becomes a lean angle; WPNav moves the target along a straight line, and the I term removes steady error from wind
  • Test performance with the RMS and maximum cross-track error from PSCN/PSCE, stating clearly the error type and wind conditions

Check your understanding

  1. Which fences does FENCE_TYPE = 5 enable?
  2. Four cross-track errors are 0.2, 0.4, 0.4 and 0.8 m. What is the RMS?
  3. The last heartbeat arrives at t = 20 s with FS_GCS_TIMEOUT = 5 s. When should the failsafe act?
  4. What is an exclusion fence for?
  5. Why record the firmware version with test results?
Answers
  1. Bits 1 and 4: the altitude ceiling and polygons or circles
  2. m
  3. At about t = 25 s
  4. To mark no-go areas inside the flying area, such as around tall buildings or crowds
  5. Names, defaults and behaviour change between versions, so results apply only to the version tested

Key formulas

Distance from a point to a segment
Horizontal position loop
RMS error

Key references

  1. ArduPilot Dev Team. Inclusion and exclusion fences. ArduPilot Copter documentation. link
  2. ArduPilot Dev Team. Parameter list (Copter stable V4.7.1). ArduPilot Copter documentation. link
  3. ArduPilot Dev Team. (2026). ArduPilot source code, tag Copter-4.7.1 [Computer software]. GitHub. link
  4. ArduPilot Dev Team. GCS failsafe. ArduPilot Copter documentation. link
  5. MAVLink Development Team. Heartbeat/connection protocol. MAVLink developer guide. link
  6. ArduPilot Dev Team. Copter position control and navigation. ArduPilot developer documentation. link
  7. PX4 Autopilot. Controller diagrams. PX4 user guide (main). link
  8. ArduPilot Dev Team. Onboard message log messages. ArduPilot Copter documentation. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lecture, case discussion and in-class problem solving

Learning evidence: Quiz results and submitted exercises

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Control, autopilot and navigation · Mission planning, flight and simulation · Communications, networks and IoT · Aircraft, structures and design