← Dedicated courses

GO DRONE PROGRAMMING · FLIGHT SIMULATOR · 38 LESSONS

Drones with Go

Write the software around a drone in Go: the ground station, the telemetry pipeline, the control loops, the autonomy and the operations around it. Thirty-eight lessons in five units cover the architecture of a flight stack, MAVLink v2 frames and telemetry streams, WGS84, ENU and NED coordinates, sensor noise, PID and cascaded control, complementary and Kalman filters, fixed-rate loops, motor mixing and flight modes; waypoint missions, geofences, failsafes, path planning, fleets and scenario testing; rangefinders and lidar scans, reactive avoidance, potential fields and gap following, orbit inspection, occupancy grids and configuration-space planning, behaviour trees, beacon-guided precision landing and flying without GPS; and radio links, flight logs, energy planning, preflight checks as code, Remote ID, strategic deconfliction, a fleet backend, property-based flight tests and incident analysis. Every program is complete and flies gopherforge.app/drone, a deterministic simulator with tilt-limited thrust, drag on airspeed, wind, a battery, wandering GPS error, obstacles, landing pads, a radio link with limited range and GPS outages, and the saved flight replays as an animation in the browser Playground and in GopherForge for iPhone and iPad.

Start with “Drone software architecture: flight controller, companion computer, ground station and fleet backend” →

Who it is for

Go developers curious about robotics and drones, and drone engineers who want Go for ground stations, fleet backends and tooling. No hardware is needed, and no prior control theory.

Before you start

Basic Go: structs, methods, slices, goroutines and channels. High-school vectors help; the control and filtering maths is explained as it is used.

What you will be able to do

  • Place each piece of a drone system (flight controller, companion computer, ground station, fleet backend), and parse and check MAVLink v2 frames and telemetry streams in Go.
  • Convert between WGS84, ENU and NED, measure sensor error against truth, and explain why averaging does not remove GPS error that wanders.
  • Tune PID altitude control with anti-windup, stack position on velocity loops, and fuse sensors with complementary and Kalman filters.
  • Write fixed-rate control loops that do not allocate, mix thrust and torques for a quad X, and model flight modes as an explicit state machine.
  • Plan and fly waypoint missions, enforce geofences, budget energy for the trip home, plan around no-fly zones with A*, run fleets with goroutines and test it all with seeded scenarios.
  • Read rangefinder scans, avoid obstacles reactively with braking-distance margins, steer with potential fields and polar histograms, and orbit a structure at a constant standoff.
  • Build an occupancy grid from scans, plan in configuration space, structure autonomy as a behaviour tree, land on a pad with a beacon, and handle a GPS outage safely.
  • Operate a fleet: plan within radio range, keep and analyse flight logs, decide go/no-go on energy, check missions before take-off, model Remote ID, deconflict operations, serve a dispatch API and analyse incidents.

Unit 1. Drone software: architecture, MAVLink and telemetry

Flight controller, companion computer and ground station, MAVLink v2 frames and checksums, telemetry rates and stale data, WGS84, ENU and NED, a Go ground station and sensor noise.

  1. Drone software architecture: flight controller, companion computer, ground station and fleet backend

    Place each piece of drone software on the right computer, explain why the inner control loops stay in real-time firmware, and fly a first simulated take-off, hold and landing from Go.

    6 min · Worked lesson

  2. MAVLink v2 frames: header, truncated payload, CRC_EXTRA and signing

    Encode and decode a MAVLink v2 HEARTBEAT in pure Go with encoding/binary, compute the CRC-16/MCRF4XX checksum seeded with CRC_EXTRA, and watch corruption and mismatched definitions get rejected.

    5 min · Worked lesson

  3. Telemetry streams: message rates, GLOBAL_POSITION_INT and stale-data detection

    Decode a recorded MAVLink stream, measure per-message rates and gaps on the ground station's clock, interpret GLOBAL_POSITION_INT's scaled integers, and flag stale streams and a lost link.

    5 min · Worked lesson

  4. Coordinates for drones: WGS84, ENU and NED, haversine and local tangent planes

    Convert mission waypoints between WGS84 latitude and longitude and local metres, compute great-circle distance and bearing, and know where the flat-plane approximation and spherical formulas stop being good enough.

    5 min · Worked lesson

  5. A ground station in Go: reader goroutine, heartbeat, context and link-loss timeouts

    Structure a MAVLink ground station with a reader goroutine, a periodic heartbeat, a channel of decoded frames, a select loop with a resettable link-loss timer and a context that shuts everything down cleanly.

    6 min · Worked lesson

  6. Sensors and noise: GPS, barometer and IMU, truth against measurement, RMSE and bias

    Compare simulated telemetry with the true state over a flight, compute bias and RMSE per sensor, and explain why smoothing one sensor fails and sensor fusion is needed.

    6 min · Worked lesson

Unit page →

Unit 2. Flight control: PID, cascades, filters and loops

PID altitude control and anti-windup, cascaded position and velocity loops, complementary and Kalman filters, fixed-rate loops in Go, quad X motor mixing and flight modes as a state machine.

  1. PID altitude control: P, I and D on the collective thrust

    Close an altitude loop through SetThrust with a PID controller that takes its derivative from the measurement, clamps its integral and saturates its output, and judge each variant by rise time, overshoot, settling time and steady-state error.

    5 min · Worked lesson

  2. Cascaded control: a position loop on top of a velocity loop

    Build an outer position loop that sends velocity setpoints through SetVelocity, explain why inner loops must be faster and where the integrator belongs, and compare P, PI and velocity feedforward when holding a point in wind and following a moving target.

    6 min · Worked lesson

  3. Complementary filter: fusing a fast drifting signal with a slow noisy one

    Estimate altitude by integrating a biased vertical velocity at 50 Hz and correcting it with the 5 Hz barometer, choose the time constant tau and alpha = tau / (tau + dt), and measure the result as RMSE against the true altitude.

    5 min · Worked lesson

  4. A Kalman filter for altitude and climb rate

    Write a 1-D constant-velocity Kalman filter that fuses GPS altitude, barometer and a climb-rate measurement, follow its state, covariance, predict and update steps, tune process and measurement noise, and reject outliers with an innovation gate that cannot lock out the truth.

    6 min · Worked lesson

  5. Fixed-rate loops in Go: tickers, jitter, GC and allocations

    Run a supervisory control loop at a fixed rate with time.Ticker, understand dropped ticks, jitter and the monotonic clock, keep allocations out of the loop body and prove it with testing.AllocsPerRun, and decide what belongs in firmware instead.

    5 min · Worked lesson

  6. Motor mixing for a quad X: thrust and torques to four motors

    Map collective thrust and roll, pitch and yaw torque commands to four motor outputs with PX4's Quadrotor X numbering and spin directions, and handle saturation by giving up thrust and yaw before roll and pitch.

    5 min · Worked lesson

  7. 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.

    5 min · Worked lesson

Unit page →

Unit 3. Missions, safety and fleets

Waypoint missions and the MAVLink mission protocol, geofences, failsafes and energy budgets, A* around no-fly zones, fleets with goroutines, and seeded scenario tests.

  1. Waypoint missions: mission items, the MAVLink upload protocol and a survey pattern

    Model a mission as numbered MAVLink-style items with acceptance radii and hold times, explain how MISSION_COUNT, MISSION_REQUEST_INT, MISSION_ITEM_INT and MISSION_ACK move it to the vehicle with retries, and generate and fly a lawnmower survey.

    6 min · Worked lesson

  2. Geofencing: inclusion and exclusion polygons, ray casting and predicting a breach

    Implement point-in-polygon with an explicit boundary rule, combine inclusion zones, exclusion zones and a ceiling, predict the time to the boundary from velocity, and compare a reactive fence with a predictive guard in the simulator.

    6 min · Worked lesson

  3. 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.

    7 min · Worked lesson

  4. Path planning around no-fly zones: A*, line-of-sight pruning and replanning

    Rasterize no-fly zones into an inflated grid, find the shortest path with A* and the admissible octile heuristic, prune it to a few waypoints by line of sight, fly it in the simulator and replan when a new restriction appears.

    5 min · Worked lesson

  5. Fleets from Go: a goroutine per vehicle, telemetry fan-in and separation

    Structure a multi-vehicle ground station with one goroutine per vehicle, fan telemetry into a supervisor over channels, stop everything with context cancellation and monitor pairwise separation with altitude layers, while keeping the simulation deterministic.

    5 min · Worked lesson

  6. Testing drone software: seeded scenarios, invariants, SITL, HIL and CI

    Build a deterministic, table-driven scenario matrix for a mission, check safety invariants and expected outcomes on every run, and place it in a test pyramid with software in the loop, hardware in the loop and continuous integration.

    6 min · Worked lesson

Unit page →

Unit 4. Autonomy: rangefinders, maps, avoidance and precision landing

Rangefinders and lidar scans, reactive avoidance and braking distance, potential fields and gap following, orbiting a structure, occupancy grids, planning in configuration space, behaviour trees, beacon landing and flying without GPS.

  1. 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.

    7 min · Worked lesson

  2. Reactive avoidance: corridors, slow-down zones and stop-and-sidestep

    Check the corridor a drone sweeps instead of a single ray, limit speed in proportion to the free distance with a gain that is provably safe for a measured reaction time and braking, and get past a building with stop-and-sidestep, without a map.

    6 min · Worked lesson

  3. Potential fields: attraction, repulsion from a scan, and the local-minimum trap

    Build an artificial potential field from a goal and rangefinder readings, fly its negative gradient as a velocity command, watch it stall inside a U-shaped obstacle, detect the stall, and escape by wall following, with an honest account of what fields cannot guarantee.

    6 min · Worked lesson

  4. 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.

    7 min · Worked lesson

  5. Inspecting a structure: a constant-standoff orbit from rangefinder feedback

    Orbit a mast at a constant distance from its surface with a radial PI loop on the rangefinder and a tangential speed, count laps, and compare per-lap standoff statistics with a GPS-only orbit around a mapped position that is a few metres off.

    6 min · Worked lesson

  6. Occupancy grids from rangefinder scans: log-odds, Bresenham rays and clamping

    Build a 2D occupancy grid in local metres from rangefinder scans: add log-odds evidence along each beam traced with Bresenham's line, mark nothing for readings without a return, clamp every cell so the map can change, and compare the built map with the true obstacles after a survey flight.

    7 min · Worked lesson

  7. Configuration space: inflating your own map, deciding about unknown cells and flying the plan

    Turn a self-built occupancy grid into a configuration space by growing occupied cells by the airframe radius, a margin and half a cell, decide whether unknown cells count as free or blocked, plan on the result with A*, fly the plan and check the clearance with the rangefinder.

    6 min · Worked lesson

  8. Behaviour trees for autonomy: sequences, fallbacks, conditions and actions ticked every step

    Build a behaviour tree from Sequence, Fallback, Condition and Action nodes that return Success, Failure or Running, tick it at 10 Hz to fly 'inspect then return; on low battery return; on obstacle hold', trace its ticks deterministically and compare it with the flight-modes lesson's state machine.

    7 min · Worked lesson

  9. Precision landing on a beacon: centring while descending, gates, aborts and retries

    Compare a GPS-only landing on a pad with a beacon-guided one in gusty wind: centre on the beacon's offset with a PI loop, descend only inside a gate that narrows with height, abort and climb back when the pad is out of view or the error jumps near the ground, and cap the retries.

    6 min · Worked lesson

  10. Flying without GPS: frozen telemetry, drift, the landing failsafe and your own policy

    Detect a GPS outage at the ground station from the fix flag and repeated positions rather than message age, measure how far a drone drifts in wind when its autopilot can only keep level, watch the 'no GPS for 3 s: landing' failsafe act, and compare hold, land and climb policies in an urban canyon with the failsafe on and off.

    6 min · Worked lesson

Unit page →

Unit 5. Operations: links, logs, rules and fleets in service

Radio range and link loss, flight logs and anomaly rules, energy planning, preflight checks as code, Remote ID, strategic deconfliction, a fleet backend, property-based flight tests and incident analysis.

  1. Radio links in operations: tested range, what the station sees, the failsafe timeline and margins

    Treat the radio link as a measured range around home, show what a ground station sees while reports stop arriving, follow the link-loss failsafe second by second, predict where the vehicle reappears, and plan and fly missions that stay inside the link with margin.

    7 min · Worked lesson

  2. Flight logs: fixed-rate records, events, CSV export, per-flight metrics and anomaly rules

    Record state and telemetry at a fixed rate and mode changes as events, export the log as CSV without flooding the console, compute distance, maximum altitude, time per mode and battery per kilometre, and run anomaly rules for sudden battery drops, GPS divergence and mode flapping on a flight that has problems.

    6 min · Worked lesson

  3. Energy planning before take-off: calibrating consumption, predicting a mission and go/no-go

    Calibrate a drain model from short test legs at known airspeeds, fit it by least squares, predict a planned route leg by leg in several wind cases including the airspeed limit, decide go or no-go with a landing reserve and a model margin, then fly the mission and compare prediction with use.

    6 min · Worked lesson

  4. Preflight checks as code: fence legs, height limits, obstacle clearance, link and energy with errors.Join

    Validate a mission before take-off against a concave geofence leg by leg, the legal height limit with a margin, obstacle clearance, the planned link range and the energy reserve; collect every problem as a typed error with errors.Join, repair what is safe with errors.As, and fly the corrected plan.

    7 min · Worked lesson

  5. Remote ID: the broadcast message set, a binary teaching format and a validating receiver

    State what standard Remote ID broadcasts and how often according to the FAA, and what EASA says the European broadcast carries; encode a simplified message set (identity, position and altitude, velocity, control station, time mark, emergency status) with encoding/binary; and build a receiver that checks freshness, plausibility and missing fields on simulator telemetry.

    7 min · Worked lesson

  6. Strategic deconfliction: 4D volumes, reservations and flying the accepted plans

    Describe each operation as segmented 4D volumes (footprint, altitude band, time window), detect conflicts by overlap in time, altitude and buffered footprint, reserve intents first come, first served by moving or rejecting newcomers, then fly the accepted plans with several drones and verify conformance and separation.

    7 min · Worked lesson

  7. A fleet backend in Go: a mission API, idempotent POST and a dispatch state machine

    Build a mission API with Go 1.22 ServeMux method and wildcard patterns, make POST safe to retry with an Idempotency-Key, dispatch missions to drones through an explicit queued, assigned, flying, done or failed state machine driven by the autopilot, and exercise it all through httptest without opening a socket.

    7 min · Worked lesson

  8. Property-based testing of flight software: generated worlds, shrinking and fuzz targets

    Generate scenarios from seeds, state invariants that must hold in every world, find a failing seed for a deliberately weak obstacle planner, shrink it to a minimal counterexample, verify the fixed planner across every seed, and express the same property as a Go fuzz target.

    7 min · Worked lesson

  9. Post-flight incident analysis: timeline, contributing factors and a verified change

    Reconstruct an incident from the autopilot's event timeline and recorded telemetry, separate what the ground station saw from what happened, compute contributing factors such as time without a fix and drift against the planned stand-off, write a blameless summary, change one thing and re-fly the same fault to verify it.

    6 min · Worked lesson

Unit page →

Related: Concurrency · Standard library patterns · Worlds, AI and multiplayer