{"guides":[],"hints":[{"hint":"Ask what happens to the aircraft if that loop misses its deadlines for 50 ms, or if the companion computer reboots in flight.","lessonID":"drones.architecture","nuance":"Companions send setpoints; the flight controller closes the rate, attitude and position loops on an RTOS and keeps flying, with a failsafe, if the companion stops. PX4 Offboard requires a steady 2 Hz setpoint stream for that reason."},{"hint":"In steady following the outer loop must command 3 m/s. With only P, what error produces that command?","lessonID":"drones.cascaded-control","nuance":"Steady wind is different: the velocity loop's integral cancels it, and the P hold stayed within 0.12 m. An outer integral also removes the lag, after a 4.29 m transient; feedforward stayed within 0.77 m."},{"hint":"Each second the velocity path pushes the estimate by b, and the barometer path pulls it back by the error divided by tau. Where do they balance?","lessonID":"drones.complementary-filter","nuance":"The program's tau 1 s row has a mean error of 0.12 m and tau 3 s has 0.30 m, close to 0.10 m/s times tau. Estimating the bias as a third state removes the offset."},{"hint":"ENU is x east, y north, z up; NED is x north, y east, z down. Swap the horizontal axes and flip one sign.","lessonID":"drones.coordinates","nuance":"Swapping x and y and negating z keeps both frames right-handed. Headings change too: NED heading runs clockwise from north and ENU yaw counter-clockwise from east, so heading = 90 degrees - yaw."},{"hint":"Ask what a single percentage threshold knows about where the vehicle is and which way the wind blows on the way back.","lessonID":"drones.failsafes","nuance":"The charge needed to get home grows with distance and headwind. A budget checked every second turns back earlier when the vehicle is far away or downwind, and later when it is close to home."},{"hint":"Layered routes cross directly above each other. Which of the two distances still protects them at the crossing point?","lessonID":"drones.fleets","nuance":"Either distance is enough. At a crossing the horizontal distance falls to zero and the layer spacing carries the separation, so it must exceed the vertical minimum plus altitude error."},{"hint":"A table lists every allowed path. What does that imply for an event with no matching row, and what should the operator see?","lessonID":"drones.flight-modes","nuance":"Rejections matter as much as transitions in the log: they explain why the drone did not move. Guards add reasons to rows that exist; a missing row means the request is never valid in that state."},{"hint":"Compare where the fence check triggers with how far a vehicle at 8 m/s travels while braking at about 4 m/s squared.","lessonID":"drones.geofencing","nuance":"Most fence actions trigger once the position is outside. At 8 m/s braking at 4 m/s2 the vehicle still covers about 8 m, so use a contingency boundary inside the fence or predict the breach from velocity."},{"hint":"Read is a blocking call on the connection itself. Does it know about any context.Context?","lessonID":"drones.ground-station","nuance":"net.Conn.Read never looks at a context. Close the connection, or set a read deadline in the past, and it returns an error. Cancel first so the other goroutines stop, then close, then wait."},{"hint":"Write K = P00 / (P00 + R). Which quantity shrinks as the filter converges, and which one comes from the sensor?","lessonID":"drones.kalman-filter","nuance":"With constant Q, R and sample rate the gain converges to a fixed value, 0.384 for altitude here, and the filter behaves like an alpha-beta filter. The covariance still drives gates and resets."},{"hint":"The time package says a ticker adjusts the interval or drops ticks to make up for slow receivers. How many ticks can be waiting at once?","lessonID":"drones.loop-timing","nuance":"Since Go 1.23 timer channels are unbuffered and Stop or Reset discard stale ticks, but a late receiver still gets one tick at once. Measure dt with the monotonic clock instead of assuming the period."},{"hint":"The CRC_EXTRA byte is never transmitted. Where does each side get it from, and what would make the two values differ?","lessonID":"drones.mavlink-frames","nuance":"CRC_EXTRA comes from the message name and its fields' types and names, so a receiver generated from other XML computes another CRC and drops the frame. It cannot detect forgery: anyone can compute a CRC; only signing helps."},{"hint":"Ask what happens to the vehicle if each one is lost: a slow heading drift, a small change of height, or a tilt it cannot correct.","lessonID":"drones.motor-mixing","nuance":"Clipping each motor separately is the worst option: in the program's last case it cut roll to +0.20 and added a pitch of +0.10 nobody asked for, coupling the axes."},{"hint":"Compare the Manhattan distance of one diagonal step with what that step actually costs on the grid.","lessonID":"drones.path-planning","nuance":"With diagonals allowed, Manhattan counts a diagonal step as 2 instead of 1.41. That overestimate makes A* trust a wrong ordering, so the first path to reach the goal is no longer guaranteed shortest."},{"hint":"Write error = setpoint - measurement and differentiate it. Which part changes instantly when a new altitude is commanded?","lessonID":"drones.pid-altitude","nuance":"While the setpoint is constant both forms give the same D term. They differ only at setpoint changes, where d(error)/dt contains the step divided by dt; noise still needs a low-pass filter either way."},{"hint":"Ask which properties must hold in every world whatever the tuning: the fence, the landing, the speed, the reserve.","lessonID":"drones.simulation-testing","nuance":"Golden logs change with every harmless tweak. Invariants such as never leaving the fence and landing near home must always hold, and each row adds its expected outcome, such as a safe abort on low battery."},{"hint":"Split the error into a constant part and a random part. Which of the two does averaging shrink?","lessonID":"drones.telemetry-noise","nuance":"Averaging shrinks independent noise by the square root of N but leaves the mean error untouched. Another sensor can estimate the offset only as well as its own error allows, and GPS altitude wanders by about a metre; EKFs model both."},{"hint":"time_boot_ms starts when the vehicle boots. How is it related to your clock, and what does it say about radio buffering?","lessonID":"drones.telemetry-streams","nuance":"time_boot_ms says when the estimate was made, on another clock that restarts at reboot and drifts. Ages, rates and gaps belong on your monotonic clock at receipt; keep time_boot_ms for ordering and reboot detection."},{"hint":"Think about how a lost item gets repaired: whoever asks for items by number can simply ask again.","lessonID":"drones.waypoint-missions","nuance":"The ground station sends only MISSION_COUNT unprompted; the vehicle then pulls items by sequence number, so a loss is fixed by asking again. MISSION_ACK comes once, at the end, with the result."}],"id":"drones","labs":[],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"drones.architecture","designGuide":{"cautions":["Latency and jitter grow with every layer above the firmware.","Disabling a failsafe in shipped software moves risk to people on the ground."],"cost":"A clear contract per layer: which messages cross each link, at what rate, and what happens when they stop.","family":"drones","flow":["Firmware closes loops","Companion sends setpoints","GCS monitors and commands","Backend plans and stores"],"ratings":[],"strengths":["Each layer can fail without taking down the one below it.","Go fits the networked layers with one static binary per target."]},"hint":"Ask what happens to the aircraft if that loop misses its deadlines for 50 ms, or if the companion computer reboots in flight.","id":"drones.architecture","introduction":"A drone that flies itself is several computers that trust each other only so far. A microcontroller runs the flight controller firmware and keeps the aircraft upright hundreds of times a second; a Linux computer on board may run mission logic, cameras and networking; a ground control station shows the operator what is happening; and a backend may coordinate many vehicles. Go is a strong fit for the last three and a poor fit for the first, and the reasons explain most design choices in this course.","nuance":"Companions send setpoints; the flight controller closes the rate, attitude and position loops on an RTOS and keeps flying, with a failsafe, if the companion stops. PX4 Offboard requires a steady 2 Hz setpoint stream for that reason.","objective":"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.","question":"A team wants to move the multicopter attitude and rate controllers from PX4 into a Go service on the Linux companion computer. Where should those loops run?","references":["https://docs.px4.io/main/en/companion_computer/","https://ardupilot.org/dev/docs/companion-computers.html","https://www.faa.gov/uas/getting_started/remote_id","https://www.easa.europa.eu/en/domains/drones-air-mobility/operating-drone/open-category-low-risk-civil-drones"],"reviewAnswer":"On the flight controller, in real-time firmware","reviewPrompt":"Where does the attitude loop run?","sections":[{"body":"The flight controller is a microcontroller board, such as a Pixhawk-class STM32, running PX4 on the NuttX RTOS or ArduPilot (on ChibiOS for most boards), written in C and C++. It samples the IMU at hundreds of hertz to kilohertz, runs the state estimator (an EKF), the rate, attitude and position controllers and the motor mixer, and owns the failsafes. The companion computer is a Linux single-board computer, such as a Raspberry Pi or an NVIDIA Jetson, wired to the flight controller by a fast serial or Ethernet link and speaking MAVLink (or uXRCE-DDS for ROS 2 with PX4); it runs vision, mission logic, video and the connection to the outside world, often through a MAVLink router. The ground control station, such as QGroundControl or Mission Planner, talks MAVLink over a telemetry radio or IP. A fleet backend collects telemetry and logs from many vehicles and plans their work. Deadlines go from microseconds in the firmware to minutes in the backend.","title":"Four computers, four time scales"},{"body":"A multicopter is unstable: if the rate loop misses its deadlines for a few tens of milliseconds, the aircraft can tip over. Flight firmware runs on an RTOS with fixed priorities, no paging and no garbage collector, with the IMU on a short SPI bus next to the processor. A Go process on Linux adds scheduler jitter, garbage-collection pauses that are usually short but have no hard bound, and milliseconds of serial or USB latency; and if the companion crashes or reboots, something must still be flying the aircraft. So companions send setpoints (a position, a velocity, an attitude) and let the flight controller close the loops. PX4 makes the contract explicit: Offboard mode requires a continuous proof-of-life stream of at least 2 Hz and triggers the configured failsafe when it stops for longer than COM_OF_LOSS_T. Every layer should survive the failure of the layer above it.","title":"Why the inner loops stay in firmware"},{"body":"The program plays the companion computer: it sends high-level commands and watches the mode, while the simulator plays the flight controller that runs the loops and decides when a manoeuvre is complete. It first asks for a take-off before arming, then arms, climbs to 10 m, holds for five seconds in a 5 m/s wind with 2 m/s gusts and lands. A watch function prints every mode change with the simulated time, the altitude and the armed flag, and sim.Save writes the recording for the replay.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// A first flight. This program plays the companion computer: it sends\n// high-level commands (arm, take off, land) and watches the mode. The\n// simulator plays the flight controller: it runs the control loops, decides\n// when a manoeuvre is finished and changes the mode itself.\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 5}, Gust: 2, Seed: 1})\n\td := sim.Drone()\n\n\tlast := d.State().Mode\n\tfmt.Printf(\"t=%6.2f s  mode %s\\n\", sim.Time(), last)\n\twatch := func() {\n\t\tst := d.State()\n\t\tif st.Mode != last {\n\t\t\tfmt.Printf(\"t=%6.2f s  mode %-7s -> %-7s alt %5.2f m  armed=%t\\n\",\n\t\t\t\tsim.Time(), last, st.Mode, st.Pos.Z, st.Armed)\n\t\t\tlast = st.Mode\n\t\t}\n\t}\n\n\t// The flight controller is the authority: it refuses unsafe commands.\n\tif err := d.TakeOff(10); errors.Is(err, drone.ErrNotArmed) {\n\t\tfmt.Println(\"take-off before arming refused:\", err)\n\t}\n\n\tmust(d.Arm())\n\twatch()\n\tmust(d.TakeOff(10))\n\twatch()\n\tclimbed := sim.RunUntil(30, func(float64) bool {\n\t\twatch()\n\t\treturn d.State().Mode == drone.Hold\n\t})\n\tif !climbed {\n\t\tlog.Fatalf(\"did not reach 10 m: %+v\", d.State())\n\t}\n\n\t// Hold for five seconds in a 5 m/s wind with 2 m/s gusts: the position\n\t// loop tilts into the wind and pulls the drone back after each gust.\n\tdrift := 0.0\n\tsim.Run(5, func(float64) {\n\t\twatch()\n\t\tdrift = max(drift, d.State().Pos.Horizontal().Len())\n\t})\n\tfmt.Printf(\"held 5 s at %.2f m, largest drift %.2f m\\n\", d.State().Pos.Z, drift)\n\n\tmust(d.Land())\n\twatch()\n\tlanded := sim.RunUntil(60, func(float64) bool {\n\t\twatch()\n\t\treturn d.State().Landed\n\t})\n\tif !landed {\n\t\tlog.Fatalf(\"did not land: %+v\", d.State())\n\t}\n\n\tst := d.State()\n\tfmt.Printf(\"flight %.2f s, battery %.1f%%, %.2f m from home\\n\",\n\t\tsim.Time(), st.Battery, st.Pos.Horizontal().Len())\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A first flight from Go","walkthrough":"The early TakeOff returns \"drone: not armed\": the autopilot, not the caller, enforces preconditions. Arm and TakeOff change the mode at t=0.00 s; the autopilot itself switches TAKEOFF -> HOLD at t=4.64 s with the altitude at 9.72 m, because it ends the climb within 0.3 m of the target, and the hold settles at 10.00 m; the gusts never push it more than 0.16 m from home, because the position loop tilts into the wind and pulls it back. LAND starts at 9.64 s and LANDED follows at 19.18 s with armed=false, because the autopilot disarms on touchdown. The flight used 4.4% of the battery and touched down 0.27 m from home, and the last line is sim.Save reporting flight.gfflight."},{"body":"This is not legal advice; rules differ by country and change, so check your national aviation authority before flying. The common principles: keep the aircraft in visual line of sight (VLOS) unless you hold an authorisation for more; stay below the altitude limit, 120 m above the ground in the EU open category and 400 ft under the US Part 107 rules; register where required; and broadcast Remote ID where required. In the US, drones that must be registered have to comply with the Remote ID rule through built-in broadcast, a broadcast module, or by flying at an FAA-recognized identification area; in the EU many class-marked drones must broadcast direct remote identification. Controlled airspace near airports and published geographical zones need permission or are closed. For software this means geofences, altitude ceilings, link-loss and low-battery failsafes are requirements, not options: never ship code that disables them, and test in simulation, then with propellers removed, then in an open field.","title":"Safety and the rules, as principles"},{"body":"Go suits the layers that are mostly networking and concurrency. On the companion computer a single static binary, cross-compiled with GOOS=linux GOARCH=arm64, can read MAVLink from the flight controller, forward telemetry, run mission logic and talk to the cloud, with a goroutine per link. github.com/bluenviron/gomavlib implements MAVLink in Go and powers the mavp2p router; Gobot drives small drones such as the Tello. Ground-station services, telemetry pipelines and fleet backends are ordinary Go servers. The flight controller is the exception: TinyGo can run on microcontrollers, but the flight stacks people actually fly are C and C++ with years of flight testing, and your Go code should treat them as the authority.","title":"Where Go fits"},{"body":"In the app, choose New project > Robotics and simulation > Drone flight. Replace main.go with this lesson's program and keep mission.go: this program does not call Square, and the file still compiles next to it. Tap Run to see the mode changes in the console, then open Output: the replay of flight.gfflight shows the climb, the hold and the landing on the altitude strip, the wind arrow and the HUD with mode and battery.","title":"Fly it in GopherForge"}],"takeaway":"Keep the loops that hold the aircraft in the air on the flight controller, where an RTOS meets every deadline. Put Go where it is strong: companion computers, ground stations and fleet backends that send setpoints and missions, watch modes and telemetry, and survive being disconnected.","title":"Drone software architecture: flight controller, companion computer, ground station and fleet backend","unitID":"drones-foundations","wrongAnswers":["In the Go service, with GOGC tuned to avoid pauses","On the ground station, which has the most CPU"]},{"conceptTag":"drones.mavlink-frames","designGuide":{"cautions":["A CRC detects accidents, not attackers; sign links that matter.","Without a definition a receiver cannot validate a message."],"cost":"A generated dialect or a small hand-written codec per message, plus key management if you enable signing.","family":"drones","flow":["Order fields by size","Trim trailing zeros","CRC with CRC_EXTRA","Validate, zero-extend"],"ratings":[],"strengths":["Small fixed headers suit slow, lossy serial radios.","CRC_EXTRA catches mismatched message definitions."]},"hint":"The CRC_EXTRA byte is never transmitted. Where does each side get it from, and what would make the two values differ?","id":"drones.mavlink-frames","introduction":"MAVLink is the protocol PX4, ArduPilot, QGroundControl and most drone tooling speak. It is deliberately small: a 10-byte header, a payload of fixed-size little-endian fields and a 2-byte checksum, designed for slow and lossy serial radios. Building a frame by hand once is the best way to understand what every library does for you, and why one wrong byte or a mismatched message definition makes frames silently disappear.","nuance":"CRC_EXTRA comes from the message name and its fields' types and names, so a receiver generated from other XML computes another CRC and drops the frame. It cannot detect forgery: anyone can compute a CRC; only signing helps.","objective":"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.","question":"Intact frames of one message type fail the CRC at a receiver while every other message passes. What does the CRC_EXTRA seed reveal here?","references":["https://mavlink.io/en/guide/serialization.html","https://mavlink.io/en/guide/message_signing.html","https://mavlink.io/en/messages/common.html","https://pkg.go.dev/encoding/binary"],"reviewAnswer":"Sender and receiver using different message definitions","reviewPrompt":"What does CRC_EXTRA detect?","sections":[{"body":"A MAVLink v2 frame starts with the magic byte 0xFD, then len (the payload length after truncation), incompat_flags (flags a receiver must understand or drop the frame; 0x01 means signed), compat_flags (flags it may ignore), seq (a per-sender counter that wraps at 255 and reveals lost frames), sysid (the system, such as vehicle 1 or a ground station, often 255), compid (the component: 1 is the autopilot, 190 the mission planner), and a 24-bit message id, little-endian. The payload follows, up to 255 bytes, then the checksum low byte first, then an optional 13-byte signature. A frame is 12 to 280 bytes. MAVLink 1 frames start with 0xFE and have an 8-bit message id; most stacks still accept them, but new code should send v2.","title":"The frame, byte by byte"},{"body":"The XML definition lists fields in a readable order, but on the wire they are sorted by type size, largest first, keeping the declared order among equal sizes; extension fields come last in declared order. That is why HEARTBEAT's uint32 custom_mode comes before type and autopilot although it is declared after them. Everything is little-endian. MAVLink 2 then removes trailing zero bytes from the payload (the first byte is always kept) and the receiver zero-extends to the full size. Truncation is byte-wise, not field-wise: the high zero bytes of a small int32 go too. A Go struct whose fields follow the wire order maps straight onto the payload with binary.Append and binary.Decode, which never insert padding.","title":"Payload: reordered, little-endian, truncated"},{"body":"The checksum is CRC-16/MCRF4XX, which MAVLink's documentation and code call X.25: the reflected polynomial 0x1021, an initial value of 0xFFFF and no final XOR. It covers every byte after the magic byte through the end of the payload, and then one more byte that is never sent: CRC_EXTRA, an 8-bit value the code generator derives from the message name and the types and names of its base fields. If the receiver was generated from a different definition (a renamed field, a changed type or array length), its CRC differs and the frame is dropped rather than misread. It also means a receiver cannot validate a message it has no definition for: a router that forwards such messages has to pass them on unchecked.","title":"CRC-16/MCRF4XX and CRC_EXTRA"},{"body":"The program checks the CRC function against the published check value, encodes the HEARTBEAT of an armed ArduPilot quadrotor in GUIDED mode (custom mode 4 in ArduCopter's numbering) as system 1, component 1, decodes it back, flips the armed bit to show the CRC rejecting it, recomputes the checksum with a wrong CRC_EXTRA, and encodes a hovering GLOBAL_POSITION_INT to show truncation.","code":"package main\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n)\n\n// MAVLink v2 frame layout:\n//\n//\t0xFD len incompat compat seq sysid compid msgid(3, LE) payload crc(2, LE) [signature(13)]\nconst (\n\tmagicV2    = 0xFD\n\theaderLen  = 10\n\tflagSigned = 0x01 // incompat flag: a 13-byte signature follows the CRC\n)\n\n// Message ids and their CRC_EXTRA seeds, generated from the XML definitions.\nconst (\n\tmsgHeartbeat         = 0\n\tmsgGlobalPositionInt = 33\n)\n\nvar crcExtra = map[uint32]byte{msgHeartbeat: 50, msgGlobalPositionInt: 104}\n\n// Heartbeat is HEARTBEAT (#0). Fields are in wire order: larger types first.\ntype Heartbeat struct {\n\tCustomMode     uint32\n\tType           uint8 // MAV_TYPE: 2 = quadrotor, 6 = GCS\n\tAutopilot      uint8 // MAV_AUTOPILOT: 3 = ArduPilot, 12 = PX4, 8 = invalid\n\tBaseMode       uint8 // MAV_MODE_FLAG bits: 0x80 = safety armed, 0x01 = custom mode\n\tSystemStatus   uint8 // MAV_STATE: 3 = standby, 4 = active\n\tMavlinkVersion uint8\n}\n\n// GlobalPositionInt is GLOBAL_POSITION_INT (#33), 28 bytes on the wire.\ntype GlobalPositionInt struct {\n\tTimeBootMs       uint32\n\tLat, Lon         int32 // degE7\n\tAlt, RelativeAlt int32 // mm\n\tVx, Vy, Vz       int16 // cm/s, north, east, down\n\tHdg              uint16\n}\n\ntype Frame struct {\n\tSeq, SysID, CompID uint8\n\tMsgID              uint32\n\tPayload            []byte // as received: possibly truncated\n}\n\n// crcAccumulate adds one byte to a CRC-16/MCRF4XX checksum (MAVLink calls it X.25).\nfunc crcAccumulate(crc uint16, b byte) uint16 {\n\ttmp := b ^ byte(crc)\n\ttmp ^= tmp << 4\n\treturn crc>>8 ^ uint16(tmp)<<8 ^ uint16(tmp)<<3 ^ uint16(tmp)>>4\n}\n\n// crc16 starts at 0xFFFF and has no final XOR.\nfunc crc16(data []byte) uint16 {\n\tcrc := uint16(0xFFFF)\n\tfor _, b := range data {\n\t\tcrc = crcAccumulate(crc, b)\n\t}\n\treturn crc\n}\n\n// frameCRC covers every byte after the magic byte, then the message's CRC_EXTRA.\nfunc frameCRC(data []byte, extra byte) uint16 {\n\treturn crcAccumulate(crc16(data), extra)\n}\n\n// Encode serializes a message into a MAVLink v2 frame.\nfunc Encode(seq, sysID, compID uint8, msgID uint32, msg any) ([]byte, error) {\n\tpayload, err := binary.Append(nil, binary.LittleEndian, msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(payload) > 1 && payload[len(payload)-1] == 0 {\n\t\tpayload = payload[:len(payload)-1] // trailing zeros are not sent; the first byte always is\n\t}\n\tbuf := []byte{magicV2, byte(len(payload)), 0, 0, seq, sysID, compID,\n\t\tbyte(msgID), byte(msgID >> 8), byte(msgID >> 16)}\n\tbuf = append(buf, payload...)\n\tcrc := frameCRC(buf[1:], crcExtra[msgID])\n\treturn binary.LittleEndian.AppendUint16(buf, crc), nil\n}\n\nvar errBadCRC = errors.New(\"bad CRC\")\n\n// Decode parses one frame from the start of buf and validates its checksum.\nfunc Decode(buf []byte) (Frame, error) {\n\tif len(buf) < headerLen+2 || buf[0] != magicV2 {\n\t\treturn Frame{}, errors.New(\"not a MAVLink v2 frame\")\n\t}\n\tn := int(buf[1])\n\tif buf[2]&^flagSigned != 0 {\n\t\treturn Frame{}, fmt.Errorf(\"unknown incompat flags %#x\", buf[2])\n\t}\n\tsize := headerLen + n + 2\n\tif buf[2]&flagSigned != 0 {\n\t\tsize += 13\n\t}\n\tif len(buf) < size {\n\t\treturn Frame{}, errors.New(\"short frame\")\n\t}\n\tf := Frame{Seq: buf[4], SysID: buf[5], CompID: buf[6],\n\t\tMsgID: uint32(buf[7]) | uint32(buf[8])<<8 | uint32(buf[9])<<16}\n\textra, ok := crcExtra[f.MsgID]\n\tif !ok {\n\t\treturn Frame{}, fmt.Errorf(\"message %d: no CRC_EXTRA, cannot validate\", f.MsgID)\n\t}\n\tgot := binary.LittleEndian.Uint16(buf[headerLen+n:])\n\tif want := frameCRC(buf[1:headerLen+n], extra); got != want {\n\t\treturn Frame{}, fmt.Errorf(\"%w: got %#04x, want %#04x\", errBadCRC, got, want)\n\t}\n\tf.Payload = buf[headerLen : headerLen+n]\n\treturn f, nil\n}\n\n// Unmarshal zero-extends a truncated payload and decodes it into msg.\nfunc Unmarshal(payload []byte, msg any) error {\n\tfull := make([]byte, binary.Size(msg))\n\tcopy(full, payload)\n\t_, err := binary.Decode(full, binary.LittleEndian, msg)\n\treturn err\n}\n\nfunc main() {\n\tfmt.Printf(\"CRC-16/MCRF4XX check value: %#04x\\n\", crc16([]byte(\"123456789\")))\n\n\thb := Heartbeat{CustomMode: 4, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}\n\tframe, err := Encode(0, 1, 1, msgHeartbeat, hb)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"HEARTBEAT frame (%d bytes): % x\\n\", len(frame), frame)\n\n\tf, err := Decode(frame)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar got Heartbeat\n\tif err := Unmarshal(f.Payload, &got); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"decoded: seq %d sys %d comp %d msg %d %+v\\n\", f.Seq, f.SysID, f.CompID, f.MsgID, got)\n\n\t// One bit flips in transit: base_mode 0x81 (armed) becomes 0x01 (disarmed).\n\tbad := append([]byte(nil), frame...)\n\tbad[headerLen+6] ^= 0x80\n\t_, err = Decode(bad)\n\tfmt.Println(\"flipped bit:\", err, \"| rejected:\", errors.Is(err, errBadCRC))\n\n\t// A receiver generated from a different HEARTBEAT definition has another\n\t// CRC_EXTRA, so the same intact bytes fail its check.\n\tsent := binary.LittleEndian.Uint16(frame[len(frame)-2:])\n\tfmt.Printf(\"receiver with CRC_EXTRA 51 computes %#04x, frame carries %#04x\\n\",\n\t\tframeCRC(frame[1:len(frame)-2], 51), sent)\n\n\t// Hovering, heading north: the last 8 bytes (vx, vy, vz, hdg) are zero.\n\tpos := GlobalPositionInt{TimeBootMs: 125000, Lat: 473977419, Lon: 85455938, Alt: 498300, RelativeAlt: 10000}\n\tframe, err = Encode(1, 1, 1, msgGlobalPositionInt, pos)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tf, err = Decode(frame)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar back GlobalPositionInt\n\tif err := Unmarshal(f.Payload, &back); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"GLOBAL_POSITION_INT: payload %d bytes, sent %d, frame %d bytes, round trip equal: %t\\n\",\n\t\tbinary.Size(pos), len(f.Payload), len(frame), back == pos)\n}","language":"go","title":"Encode, decode and corrupt a HEARTBEAT","walkthrough":"0x6f91 is the catalogued check value of CRC-16/MCRF4XX for \"123456789\". The frame is 21 bytes: fd, len 09, two zero flag bytes, seq 00, sysid 01, compid 01, msgid 00 00 00, the payload with custom_mode 04 00 00 00 first, then type 02, autopilot 03, base_mode 81, system_status 04 and version 03, and the CRC 0x5603 sent as 03 56. Flipping the armed bit makes the receiver compute 0x7b6d instead, so the frame is dropped rather than reported as disarmed. A receiver with CRC_EXTRA 51 computes 0x478a and rejects even the intact frame. The hovering GLOBAL_POSITION_INT sends 18 of its 28 payload bytes: the zero velocities and heading and the two zero high bytes of relative_alt (10000 mm) are trimmed, and zero-extension restores an identical struct."},{"body":"A CRC detects accidental corruption, not tampering: anyone can compute a valid checksum. MAVLink 2 signing sets incompat flag 0x01 and appends 13 bytes: a link id, a 48-bit timestamp in 10-microsecond units since 1 January 2015 that must increase on each link, and a 48-bit signature, the first six bytes of SHA-256 over a 32-byte secret key followed by the header, payload, CRC, link id and timestamp. Receivers reject bad signatures and stale timestamps, which blocks forged and replayed commands. The key is shared out of band, typically over a wired connection, and signing does not encrypt: telemetry remains readable to anyone listening on the link.","title":"What the CRC does not protect"},{"body":"This program uses only the standard library. In the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it (mission.go can stay), and tap Run; there is no replay because it never calls sim.Save. To feed it simulator data, fly a drone in a sim.Run loop and, each time d.Telemetry().Time changes, build a GLOBAL_POSITION_INT from the report (latitude and longitude from the position as in the coordinates lesson, velocity in cm/s north, east and down) and encode one frame per report.","title":"Fly it in GopherForge"}],"takeaway":"A MAVLink v2 frame is a 10-byte header, a payload of size-ordered little-endian fields with trailing zeros removed, and a CRC-16/MCRF4XX that ends with the message's CRC_EXTRA. Corrupted bytes and mismatched definitions both fail the CRC; only signing protects against forgery.","title":"MAVLink v2 frames: header, truncated payload, CRC_EXTRA and signing","unitID":"drones-foundations","wrongAnswers":["A forged frame from an attacker on the link","A payload whose trailing zeros were truncated"]},{"conceptTag":"drones.telemetry-streams","designGuide":{"cautions":["A heartbeat-only monitor misses a stalled data stream.","Vehicle timestamps reset on reboot and drift from yours."],"cost":"A small record per message type (count, last receipt, expected interval) and a periodic check that turns ages into alarms.","family":"drones","flow":["Stamp frames on receipt","Rate and gap per message","Timeout per stream","Heartbeat for link loss"],"ratings":[],"strengths":["Stale data is flagged even while heartbeats still arrive.","Receipt timestamps expose radio buffering and bursts."]},"hint":"time_boot_ms starts when the vehicle boots. How is it related to your clock, and what does it say about radio buffering?","id":"drones.telemetry-streams","introduction":"A vehicle does not answer questions about its position; it streams messages at configured rates and the ground station keeps the latest value of each. That design is efficient on a narrow radio link, but it means the newest value you hold may be seconds old. A ground station that shows a position without knowing its age, or calls a link healthy because heartbeats still arrive, is behind many confusing incidents.","nuance":"time_boot_ms says when the estimate was made, on another clock that restarts at reboot and drifts. Ages, rates and gaps belong on your monotonic clock at receipt; keep time_boot_ms for ordering and reboot detection.","objective":"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.","question":"A ground station shows how old the vehicle position is. Which clock should it use to measure that age?","references":["https://mavlink.io/en/messages/common.html","https://mavlink.io/en/mavgen_python/howto_requestmessages.html","https://mavlink.io/en/guide/packet_loss.html","https://ardupilot.org/dev/docs/mavlink-requesting-data.html"],"reviewAnswer":"The ground station's own clock, stamped on receipt","reviewPrompt":"Which clock measures staleness?","sections":[{"body":"An autopilot streams a default set of messages on each link. To change a rate, send MAV_CMD_SET_MESSAGE_INTERVAL in a COMMAND_LONG with param1 the message id and param2 the interval in microseconds (-1 disables the stream, 0 restores the default) and wait for its COMMAND_ACK. To ask for the current rate, send MAV_CMD_REQUEST_MESSAGE with param1 244 and param2 the message id; the reply is MESSAGE_INTERVAL with message_id and interval_us, where -1 means disabled and 0 not available. ArduPilot also has per-port stream-rate parameters such as SR1_POSITION, and PX4 sets default rate profiles per MAVLink instance. Rates compete for bandwidth: a 57600-baud telemetry radio moves only a few kilobytes per second, so ask for what each consumer needs, not everything at 50 Hz.","title":"Streams and their rates"},{"body":"GLOBAL_POSITION_INT (#33) is the flight controller's fused position estimate, not raw GPS (GPS_RAW_INT carries the receiver's own solution). time_boot_ms is the vehicle's clock since boot; lat and lon are int32 in degE7, 1e-7 degree or about 1.1 cm; alt is millimetres above mean sea level and relative_alt millimetres above home; vx, vy and vz are int16 centimetres per second north, east and down, so a climb is a negative vz; hdg is centidegrees from 0 to 35999, with 65535 meaning unknown. Scaled integers keep full resolution in few bytes, and they are where bugs hide: millimetres treated as metres, vz read as climb, or lat and lon swapped.","title":"GLOBAL_POSITION_INT, field by field"},{"body":"time_boot_ms says when the vehicle made the estimate, on a clock that starts at boot, restarts after a reboot and drifts against yours. It cannot tell you how old the value is now, because radios buffer, retry and deliver in bursts. Stamp every frame with your own monotonic clock when it is complete (in Go, time.Now carries a monotonic reading and time.Since uses it) and compute ages, rates and gaps from those stamps. Keep time_boot_ms for ordering samples and for spotting a reboot, when it jumps backwards. The seq byte, counted per sender, shows frames lost on the link.","title":"Timestamp on receipt"},{"body":"vehicleLink builds what a radio delivers over 8.45 s: a MESSAGE_INTERVAL reply confirming GLOBAL_POSITION_INT at 200000 microseconds, HEARTBEAT at 1 Hz, ATTITUDE at 10 Hz and GLOBAL_POSITION_INT at 5 Hz, with three noise bytes, a radio that holds 0.6 s of frames and delivers them in a burst, one corrupted ATTITUDE frame, a position stream that stops at 6 s and silence after 8.45 s. The parser resynchronises on 0xFD, each stream records its count, receipt times and largest gaps, and five checks compare ages with per-stream timeouts: three expected intervals for data, five seconds of missing heartbeats for the link.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"time\"\n)\n\nconst (\n\tmagicV2   = 0xFD\n\theaderLen = 10\n\n\tmsgHeartbeat         = 0\n\tmsgAttitude          = 30\n\tmsgGlobalPositionInt = 33\n\tmsgMessageInterval   = 244\n)\n\nvar crcExtra = map[uint32]byte{msgHeartbeat: 50, msgAttitude: 39, msgGlobalPositionInt: 104, msgMessageInterval: 95}\n\ntype Heartbeat struct {\n\tCustomMode                                              uint32\n\tType, Autopilot, BaseMode, SystemStatus, MavlinkVersion uint8\n}\n\ntype Attitude struct {\n\tTimeBootMs                                        uint32\n\tRoll, Pitch, Yaw, RollSpeed, PitchSpeed, YawSpeed float32\n}\n\ntype GlobalPositionInt struct {\n\tTimeBootMs       uint32\n\tLat, Lon         int32  // degE7\n\tAlt, RelativeAlt int32  // mm (MSL, above home)\n\tVx, Vy, Vz       int16  // cm/s north, east, down\n\tHdg              uint16 // cdeg, 65535 = unknown\n}\n\ntype MessageInterval struct {\n\tIntervalUs int32 // wire order: the int32 comes before the uint16\n\tMessageID  uint16\n}\n\ntype Frame struct {\n\tSeq     uint8\n\tMsgID   uint32\n\tPayload []byte\n\tRx      time.Duration // ground-station clock when the frame was complete\n}\n\nfunc crcAccumulate(crc uint16, b byte) uint16 {\n\ttmp := b ^ byte(crc)\n\ttmp ^= tmp << 4\n\treturn crc>>8 ^ uint16(tmp)<<8 ^ uint16(tmp)<<3 ^ uint16(tmp)>>4\n}\n\nfunc frameCRC(data []byte, extra byte) uint16 {\n\tcrc := uint16(0xFFFF)\n\tfor _, b := range data {\n\t\tcrc = crcAccumulate(crc, b)\n\t}\n\treturn crcAccumulate(crc, extra)\n}\n\nfunc encode(seq uint8, msgID uint32, msg any) []byte {\n\tpayload, err := binary.Append(nil, binary.LittleEndian, msg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor len(payload) > 1 && payload[len(payload)-1] == 0 {\n\t\tpayload = payload[:len(payload)-1]\n\t}\n\tbuf := append([]byte{magicV2, byte(len(payload)), 0, 0, seq, 1, 1,\n\t\tbyte(msgID), byte(msgID >> 8), byte(msgID >> 16)}, payload...)\n\treturn binary.LittleEndian.AppendUint16(buf, frameCRC(buf[1:], crcExtra[msgID]))\n}\n\nfunc unmarshal(payload []byte, msg any) {\n\tfull := make([]byte, binary.Size(msg))\n\tcopy(full, payload)\n\tif _, err := binary.Decode(full, binary.LittleEndian, msg); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n// Parser cuts a byte stream into valid frames and resynchronises on the next\n// 0xFD after junk or a frame that fails its CRC.\ntype Parser struct {\n\tbuf             []byte\n\tBadCRC, Skipped int\n}\n\nfunc (p *Parser) Feed(data []byte, rx time.Duration) []Frame {\n\tp.buf = append(p.buf, data...)\n\tvar out []Frame\n\tfor {\n\t\ti := bytes.IndexByte(p.buf, magicV2)\n\t\tif i < 0 {\n\t\t\ti = len(p.buf)\n\t\t}\n\t\tp.Skipped += i\n\t\tp.buf = p.buf[i:]\n\t\tif len(p.buf) < headerLen {\n\t\t\treturn out\n\t\t}\n\t\tn := int(p.buf[1])\n\t\tif len(p.buf) < headerLen+n+2 {\n\t\t\treturn out\n\t\t}\n\t\tid := uint32(p.buf[7]) | uint32(p.buf[8])<<8 | uint32(p.buf[9])<<16\n\t\textra, known := crcExtra[id]\n\t\tgot := binary.LittleEndian.Uint16(p.buf[headerLen+n:])\n\t\tif !known || got != frameCRC(p.buf[1:headerLen+n], extra) {\n\t\t\tp.BadCRC++\n\t\t\tp.Skipped++\n\t\t\tp.buf = p.buf[1:] // not a frame after all: hunt for the next 0xFD\n\t\t\tcontinue\n\t\t}\n\t\tpayload := append([]byte(nil), p.buf[headerLen:headerLen+n]...)\n\t\tout = append(out, Frame{Seq: p.buf[4], MsgID: id, Payload: payload, Rx: rx})\n\t\tp.buf = p.buf[headerLen+n+2:]\n\t}\n}\n\n// Stream is what the ground station knows about one message type.\ntype Stream struct {\n\tName         string\n\tID           uint32\n\tTimeout      time.Duration\n\tCount        int\n\tFirst, Last  time.Duration\n\tMaxGap       time.Duration\n\tlastBoot     uint32\n\tMaxBootGap   time.Duration\n\thasBootStamp bool\n}\n\nfunc (s *Stream) Add(f Frame, boot uint32, hasBoot bool) {\n\tif s.Count == 0 {\n\t\ts.First = f.Rx\n\t} else {\n\t\ts.MaxGap = max(s.MaxGap, f.Rx-s.Last)\n\t\tif hasBoot {\n\t\t\ts.MaxBootGap = max(s.MaxBootGap, time.Duration(boot-s.lastBoot)*time.Millisecond)\n\t\t}\n\t}\n\ts.Count++\n\ts.Last, s.lastBoot, s.hasBootStamp = f.Rx, boot, hasBoot\n}\n\nfunc (s *Stream) Rate() float64 {\n\tif s.Count < 2 {\n\t\treturn 0\n\t}\n\treturn float64(s.Count-1) / (s.Last - s.First).Seconds()\n}\n\ntype chunk struct {\n\trx   time.Duration\n\tdata []byte\n}\n\n// vehicleLink builds what a radio delivers: HEARTBEAT at 1 Hz, ATTITUDE at\n// 10 Hz and GLOBAL_POSITION_INT at 5 Hz. The radio holds frames sent between\n// 3.0 and 3.6 s and delivers them at 3.65 s; GLOBAL_POSITION_INT stops at\n// 6 s; one ATTITUDE frame is corrupted; the link dies after 8.45 s.\nfunc vehicleLink() []chunk {\n\tconst bootAtStart = 125000 // the vehicle booted 125 s before we started listening\n\tvar out []chunk\n\tvar seq uint8\n\trx := time.Duration(0)\n\tsend := func(sent int, data []byte) {\n\t\tseq++\n\t\tarrive := time.Duration(sent+8+sent%7) * time.Millisecond // a few ms of latency\n\t\tif sent >= 3000 && sent < 3600 {\n\t\t\tarrive = 3650 * time.Millisecond\n\t\t}\n\t\trx = max(rx, arrive) // a serial link is first in, first out\n\t\tout = append(out, chunk{rx, data})\n\t}\n\tout = append(out, chunk{0, []byte{0x55, 0x00, 0xAA}}) // noise before the first frame\n\tsend(0, encode(seq, msgMessageInterval, MessageInterval{IntervalUs: 200000, MessageID: msgGlobalPositionInt}))\n\tlon := int32(85455938)\n\tfor ms := 0; ms <= 8450; ms += 50 {\n\t\tboot := uint32(bootAtStart + ms)\n\t\tif ms%1000 == 0 {\n\t\t\tsend(ms, encode(seq, msgHeartbeat, Heartbeat{CustomMode: 3, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}))\n\t\t}\n\t\tif ms%100 == 0 {\n\t\t\tf := encode(seq, msgAttitude, Attitude{TimeBootMs: boot, Yaw: math.Pi / 2})\n\t\t\tif ms == 5000 {\n\t\t\t\tf[12] ^= 0x10 // a bit error the radio's own checks missed\n\t\t\t}\n\t\t\tsend(ms, f)\n\t\t}\n\t\tif ms%200 == 0 && ms < 6000 {\n\t\t\tlon += 106 // 4 m/s east is about 106e-7 degrees of longitude per 0.2 s here\n\t\t\tsend(ms, encode(seq, msgGlobalPositionInt, GlobalPositionInt{TimeBootMs: boot, Lat: 473977419,\n\t\t\t\tLon: lon, Alt: 508300, RelativeAlt: 20150, Vy: 400, Hdg: 9000}))\n\t\t}\n\t}\n\treturn out\n}\n\nfunc main() {\n\tstreams := []*Stream{\n\t\t{Name: \"HEARTBEAT\", ID: msgHeartbeat, Timeout: 5 * time.Second}, // five missed heartbeats\n\t\t{Name: \"ATTITUDE\", ID: msgAttitude, Timeout: 300 * time.Millisecond},\n\t\t{Name: \"GLOBAL_POSITION_INT\", ID: msgGlobalPositionInt},\n\t}\n\tbyID := map[uint32]*Stream{}\n\tfor _, s := range streams {\n\t\tbyID[s.ID] = s\n\t}\n\tvar p Parser\n\tvar lastPos GlobalPositionInt\n\tvar nextSeq uint8\n\tframes, lost := 0, 0\n\n\tcheck := func(at time.Duration) {\n\t\thb := streams[0]\n\t\tstate := \"link up  \"\n\t\tif hb.Count == 0 || at-hb.Last > hb.Timeout {\n\t\t\tstate = \"LINK LOST\"\n\t\t}\n\t\tline := fmt.Sprintf(\"t=%5.1fs  HEARTBEAT %.2fs %s\", at.Seconds(), (at - hb.Last).Seconds(), state)\n\t\tfor _, s := range streams[1:] {\n\t\t\tage := at - s.Last\n\t\t\tmark := \"ok\"\n\t\t\tif age > s.Timeout {\n\t\t\t\tmark = \"STALE\"\n\t\t\t}\n\t\t\tline += fmt.Sprintf(\"  %s %.2fs %s\", s.Name, age.Seconds(), mark)\n\t\t}\n\t\tfmt.Println(line)\n\t}\n\tchecks := []time.Duration{2 * time.Second, 3500 * time.Millisecond, 7 * time.Second, 11 * time.Second, 14 * time.Second}\n\n\tfor _, c := range vehicleLink() {\n\t\tfor len(checks) > 0 && checks[0] < c.rx {\n\t\t\tcheck(checks[0])\n\t\t\tchecks = checks[1:]\n\t\t}\n\t\tfor _, f := range p.Feed(c.data, c.rx) {\n\t\t\tif frames > 0 {\n\t\t\t\tlost += int(f.Seq - nextSeq) // uint8 arithmetic wraps at 256\n\t\t\t}\n\t\t\tframes, nextSeq = frames+1, f.Seq+1\n\t\t\tswitch f.MsgID {\n\t\t\tcase msgMessageInterval:\n\t\t\t\tvar mi MessageInterval\n\t\t\t\tunmarshal(f.Payload, &mi)\n\t\t\t\tfmt.Printf(\"MESSAGE_INTERVAL: message %d every %d us (%.1f Hz)\\n\", mi.MessageID, mi.IntervalUs, 1e6/float64(mi.IntervalUs))\n\t\t\t\tif s := byID[uint32(mi.MessageID)]; s != nil && mi.IntervalUs > 0 {\n\t\t\t\t\ts.Timeout = 3 * time.Duration(mi.IntervalUs) * time.Microsecond\n\t\t\t\t}\n\t\t\tcase msgHeartbeat:\n\t\t\t\tbyID[f.MsgID].Add(f, 0, false)\n\t\t\tcase msgAttitude:\n\t\t\t\tvar a Attitude\n\t\t\t\tunmarshal(f.Payload, &a)\n\t\t\t\tbyID[f.MsgID].Add(f, a.TimeBootMs, true)\n\t\t\tcase msgGlobalPositionInt:\n\t\t\t\tunmarshal(f.Payload, &lastPos)\n\t\t\t\tbyID[f.MsgID].Add(f, lastPos.TimeBootMs, true)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, at := range checks {\n\t\tcheck(at)\n\t}\n\n\tfmt.Printf(\"frames %d, failed CRC %d, bytes skipped %d, lost by sequence %d\\n\", frames, p.BadCRC, p.Skipped, lost)\n\tfmt.Println(\"message              count  rx rate  max gap (rx)  max gap (vehicle clock)\")\n\tfor _, s := range streams {\n\t\tvehicle := \"-\"\n\t\tif s.hasBootStamp {\n\t\t\tvehicle = s.MaxBootGap.String()\n\t\t}\n\t\tfmt.Printf(\"%-19s  %5d  %4.1f Hz  %12s  %s\\n\", s.Name, s.Count, s.Rate(), s.MaxGap, vehicle)\n\t}\n\tg := lastPos\n\tfmt.Printf(\"last position: %.7f, %.7f  alt %.2f m MSL, %.2f m above home\\n\",\n\t\tfloat64(g.Lat)/1e7, float64(g.Lon)/1e7, float64(g.Alt)/1000, float64(g.RelativeAlt)/1000)\n\tfmt.Printf(\"velocity: north %.2f, east %.2f, climb %.2f m/s, heading %.2f deg\\n\",\n\t\tfloat64(g.Vx)/100, float64(g.Vy)/100, float64(-g.Vz)/100, float64(g.Hdg)/100)\n}","language":"go","title":"Rates, gaps and staleness from a recorded stream","walkthrough":"At 2.0 s everything is fresh. At 3.5 s, inside the radio hold, the heartbeat is 1.49 s old and the link is up, yet ATTITUDE (0.59s) and GLOBAL_POSITION_INT (0.69s) are STALE. At 7.0 s only GLOBAL_POSITION_INT is stale (1.19s) while heartbeats arrive: the case a heartbeat-only monitor misses. At 11.0 s the link has been dead for 2.5 s but the heartbeat is 2.99 s old, so it still says link up; at 14.0 s it reaches 5.99s and reports LINK LOST. The summary shows 124 frames, 1 failed CRC, 31 skipped bytes (3 noise bytes and the 28-byte corrupted frame) and 1 frame lost by sequence. Receipt gaps of 740ms and 842ms reveal the burst that the vehicle clock (200ms) hides. The last position decodes to 47.3977419, 8.5459118 at 20.15 m above home, 4.00 m/s east on heading 90.00 deg."},{"body":"Give every consumer a maximum age it tolerates: a map can show a 2 s old position with a warning, a geofence monitor may need data younger than half a second, and a command that depends on the vehicle's mode should check that the mode is fresh. Show the age next to each value and grey out stale ones. Declare link loss from missed heartbeats (on radio links the MAVLink documentation describes 1 Hz heartbeats and four or five missed before disconnecting), but alarm on stale data first, because a heartbeat comes from a different code path than the estimator and can keep arriving while position does not. When a link returns, the first frames may be old ones from a buffer: check that time_boot_ms moves forward before trusting them.","title":"Decide per stream, not per link"},{"body":"The program uses only the standard library: in the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To feed it simulator data, fly in a sim.Run loop and, each time d.Telemetry().Time changes, encode a GLOBAL_POSITION_INT from the report (GPS position converted to degE7 around a home point, BaroAlt in millimetres as relative_alt, velocity in cm/s north, east and down) and pass the frame to Parser.Feed with the simulated time as the receipt time. Stop encoding for a few seconds and watch the checks turn STALE; add sim.Save for a replay.","title":"Fly it in GopherForge"}],"takeaway":"Treat every telemetry value as a sample with an age. Stamp frames on receipt with your own clock, measure rates and gaps per message, keep time_boot_ms for ordering and reboot detection, and alarm on stale data streams before the heartbeat timeout declares the link lost.","title":"Telemetry streams: message rates, GLOBAL_POSITION_INT and stale-data detection","unitID":"drones-foundations","wrongAnswers":["time_boot_ms in the message, since the vehicle stamps it","The heartbeat timer, since heartbeats prove the link is up"]},{"conceptTag":"drones.coordinates","designGuide":{"cautions":["Flat-plane error grows with distance and latitude.","Axis swaps and sign flips between ENU and NED fail silently."],"cost":"A reference point per mission and two small conversion functions, tested at high latitude and across the antimeridian.","family":"drones","flow":["Keep WGS84 on the wire","Pick a reference point","Wrap dlon, scale by cos","Re-base for long legs"],"ratings":[],"strengths":["A local plane turns geometry into plain vector maths.","degE7 integers keep centimetre resolution on the wire."]},"hint":"ENU is x east, y north, z up; NED is x north, y east, z down. Swap the horizontal axes and flip one sign.","id":"drones.coordinates","introduction":"GPS reports latitude, longitude and altitude on the WGS84 ellipsoid; controllers work in metres in a local frame; MAVLink and the flight stacks use NED while ROS and this simulator use ENU. Every drone codebase converts between them, and a swapped axis, a wrong sign or a missing cos(latitude) produces a vehicle that flies confidently to the wrong place. The conversions are short; knowing their error budget is the real skill.","nuance":"Swapping x and y and negating z keeps both frames right-handed. Headings change too: NED heading runs clockwise from north and ENU yaw counter-clockwise from east, so heading = 90 degrees - yaw.","objective":"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.","question":"The simulator reports a position in ENU as (x, y, z). How do you express it in NED for a MAVLink LOCAL_POSITION_NED message?","references":["https://en.wikipedia.org/wiki/World_Geodetic_System","https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates","https://en.wikipedia.org/wiki/Haversine_formula","https://en.wikipedia.org/wiki/Equirectangular_projection"],"reviewAnswer":"North = y, east = x, down = -z","reviewPrompt":"ENU (x, y, z) to NED?","sections":[{"body":"WGS84 defines the reference ellipsoid (semi-major axis 6378137 m, flattening 1/298.257223563) and the frame GPS positions are expressed in. Heights come in two kinds: GNSS receivers measure height above the ellipsoid, while GLOBAL_POSITION_INT's alt is above mean sea level (the geoid), and the two differ by up to about 100 m depending on where you are. Local frames are tangent to the Earth at a reference point. ENU has x east, y north and z up; ROS and this simulator use it. NED has x north, y east and z down; aviation, PX4, ArduPilot and MAVLink messages such as LOCAL_POSITION_NED use it. Converting is north = y, east = x, down = -z, and headings change too: NED heading runs clockwise from north, ENU yaw counter-clockwise from east, so heading = 90 degrees - yaw.","title":"WGS84, ENU and NED"},{"body":"The haversine formula gives the great-circle distance on a sphere and stays accurate for short distances, where the spherical law of cosines loses precision. With the mean Earth radius of 6371008.8 m its error against the WGS84 ellipsoid is a few tenths of a percent at most, and the program shows why: at 47.4 degrees north the sphere's metre per degree is 0.015% long north-south and 0.293% short east-west. The initial bearing is the direction to set off in; along a great circle it changes except on meridians and the equator. For survey-grade work use an ellipsoidal geodesic (Karney's algorithm, as in GeographicLib) or convert through Earth-centred coordinates (ECEF) to ENU.","title":"Haversine distance and initial bearing"},{"body":"Plane is a local tangent plane at home with the equirectangular approximation: x = R * dlon * cos(lat0) and y = R * dlat, with the longitude difference wrapped into [-180, 180). The program compares metres per degree on the sphere and on WGS84, converts four survey waypoints into simulator ENU and NED vectors and checks them against haversine, sends a simulator position through degE7 integers and back, compares degE7 with float32 degrees, measures how the flat-plane error grows with distance at two latitudes, and crosses the antimeridian.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// earthRadius is the mean Earth radius in metres. Spherical formulas with it\n// are within a few tenths of a percent of the WGS84 ellipsoid.\nconst earthRadius = 6371008.8\n\n// WGS84 ellipsoid: semi-major axis and flattening.\nconst (\n\twgs84A = 6378137.0\n\twgs84F = 1 / 298.257223563\n)\n\ntype LatLon struct{ Lat, Lon float64 } // degrees, WGS84\n\nfunc rad(d float64) float64 { return d * math.Pi / 180 }\nfunc deg(r float64) float64 { return r * 180 / math.Pi }\n\n// wrap180 brings a longitude difference into [-180, 180).\nfunc wrap180(d float64) float64 { return math.Mod(math.Mod(d+180, 360)+360, 360) - 180 }\n\n// Distance is the haversine great-circle distance in metres.\nfunc Distance(a, b LatLon) float64 {\n\tp1, p2 := rad(a.Lat), rad(b.Lat)\n\tdp, dl := p2-p1, rad(b.Lon-a.Lon)\n\th := math.Sin(dp/2)*math.Sin(dp/2) + math.Cos(p1)*math.Cos(p2)*math.Sin(dl/2)*math.Sin(dl/2)\n\treturn 2 * earthRadius * math.Asin(math.Sqrt(h))\n}\n\n// Bearing is the initial great-circle bearing, degrees clockwise from north.\nfunc Bearing(a, b LatLon) float64 {\n\tp1, p2, dl := rad(a.Lat), rad(b.Lat), rad(b.Lon-a.Lon)\n\ty := math.Sin(dl) * math.Cos(p2)\n\tx := math.Cos(p1)*math.Sin(p2) - math.Sin(p1)*math.Cos(p2)*math.Cos(dl)\n\treturn math.Mod(deg(math.Atan2(y, x))+360, 360)\n}\n\n// Destination walks dist metres from a along an initial bearing on the sphere.\nfunc Destination(a LatLon, bearing, dist float64) LatLon {\n\tp1, l1, th, d := rad(a.Lat), rad(a.Lon), rad(bearing), dist/earthRadius\n\tp2 := math.Asin(math.Sin(p1)*math.Cos(d) + math.Cos(p1)*math.Sin(d)*math.Cos(th))\n\tl2 := l1 + math.Atan2(math.Sin(th)*math.Sin(d)*math.Cos(p1), math.Cos(d)-math.Sin(p1)*math.Sin(p2))\n\treturn LatLon{deg(p2), wrap180(deg(l2))}\n}\n\n// Plane is a local tangent plane at Ref with the equirectangular\n// approximation: X east and Y north in metres, like the simulator's ENU.\ntype Plane struct{ Ref LatLon }\n\nfunc (pl Plane) ToLocal(p LatLon) (x, y float64) {\n\tx = earthRadius * rad(wrap180(p.Lon-pl.Ref.Lon)) * math.Cos(rad(pl.Ref.Lat))\n\ty = earthRadius * rad(p.Lat-pl.Ref.Lat)\n\treturn x, y\n}\n\nfunc (pl Plane) ToLatLon(x, y float64) LatLon {\n\tlat := pl.Ref.Lat + deg(y/earthRadius)\n\tlon := pl.Ref.Lon + deg(x/(earthRadius*math.Cos(rad(pl.Ref.Lat))))\n\treturn LatLon{lat, wrap180(lon)}\n}\n\nfunc main() {\n\thome := LatLon{47.397742, 8.545594}\n\tplane := Plane{Ref: home}\n\n\t// Metres per degree at home: sphere against the WGS84 ellipsoid.\n\te2 := wgs84F * (2 - wgs84F)\n\ts2 := math.Pow(math.Sin(rad(home.Lat)), 2)\n\tm := wgs84A * (1 - e2) / math.Pow(1-e2*s2, 1.5) // meridian radius of curvature\n\tn := wgs84A / math.Sqrt(1-e2*s2)                // prime vertical radius\n\tnorthS, northE := rad(earthRadius), rad(m)\n\teastS, eastE := rad(earthRadius)*math.Cos(rad(home.Lat)), rad(n)*math.Cos(rad(home.Lat))\n\tfmt.Printf(\"1 deg north: sphere %.1f m, WGS84 %.1f m (%+.3f%%)\\n\", northS, northE, (northS-northE)/northE*100)\n\tfmt.Printf(\"1 deg east:  sphere %.1f m, WGS84 %.1f m (%+.3f%%)\\n\", eastS, eastE, (eastS-eastE)/eastE*100)\n\n\tfmt.Println(\"mission waypoints, 15 m above home:\")\n\twps := []LatLon{{47.398200, 8.546300}, {47.398200, 8.547400}, {47.397300, 8.547400}, {47.397300, 8.546300}}\n\tfor i, wp := range wps {\n\t\tx, y := plane.ToLocal(wp)\n\t\tdist, brg := Distance(home, wp), Bearing(home, wp)\n\t\tflatDist := math.Hypot(x, y)\n\t\tflatBrg := math.Mod(deg(math.Atan2(x, y))+360, 360) // atan2(east, north): clockwise from north\n\t\tfmt.Printf(\"  wp%d ENU (%.2f, %.2f, 15)  NED (%.2f, %.2f, -15)  %.2f m at %.2f deg  flat %+.1f mm %+.4f deg\\n\",\n\t\t\ti+1, x, y, y, x, dist, brg, (flatDist-dist)*1000, flatBrg-brg)\n\t}\n\n\t// Back: a simulator position to GLOBAL_POSITION_INT integers and back.\n\tsimX, simY := 61.37, -40.21\n\tp := plane.ToLatLon(simX, simY)\n\tlatE7, lonE7 := int32(math.Round(p.Lat*1e7)), int32(math.Round(p.Lon*1e7))\n\tbx, by := plane.ToLocal(LatLon{float64(latE7) / 1e7, float64(lonE7) / 1e7})\n\tfmt.Printf(\"sim (%.2f, %.2f) -> lat %d lon %d (degE7) -> (%.4f, %.4f): error %.1f mm\\n\",\n\t\tsimX, simY, latE7, lonE7, bx, by, math.Hypot(bx-simX, by-simY)*1000)\n\tulp := func(v float64) float64 { f := float32(v); return float64(math.Nextafter32(f, 1e9) - f) }\n\tfmt.Printf(\"resolution here: degE7 %.2f cm north, %.2f cm east; float32 degrees %.2f cm north, %.2f cm east\\n\",\n\t\trad(1e-7)*earthRadius*100, rad(1e-7)*earthRadius*math.Cos(rad(p.Lat))*100,\n\t\trad(ulp(p.Lat))*earthRadius*100, rad(ulp(p.Lon))*earthRadius*math.Cos(rad(p.Lat))*100)\n\n\tfmt.Println(\"flat-plane range error against haversine, bearing 45 deg:\")\n\tfor _, site := range []struct {\n\t\tname string\n\t\tat   LatLon\n\t}{{\"lat 47.4\", home}, {\"lat 78.2\", LatLon{78.2, 15.6}}} {\n\t\tline := \"  \" + site.name + \":\"\n\t\tfor _, d := range []float64{100, 1000, 10000, 100000} {\n\t\t\tq := Destination(site.at, 45, d)\n\t\t\tx, y := Plane{Ref: site.at}.ToLocal(q)\n\t\t\tline += fmt.Sprintf(\"  %gkm %+.3f%%\", d/1000, (math.Hypot(x, y)-d)/d*100)\n\t\t}\n\t\tfmt.Println(line)\n\t}\n\n\ta, b := LatLon{-16.5, 179.9995}, LatLon{-16.5, -179.9995}\n\traw := earthRadius * rad(b.Lon-a.Lon) * math.Cos(rad(a.Lat))\n\tx, _ := Plane{Ref: a}.ToLocal(b)\n\tfmt.Printf(\"across the antimeridian: east %.1f km without wrapping, %.1f m wrapped; haversine %.1f m\\n\",\n\t\traw/1000, x, Distance(a, b))\n}","language":"go","title":"Waypoints to local metres and back","walkthrough":"The first two lines put the sphere at +0.015% north-south and -0.293% east-west against WGS84, so on wp2's 136 m eastward offset the spherical model is about 0.4 m short: at field scale that, not the flat plane, is the larger error. wp2 becomes ENU (135.93, 50.93, 15) and NED (50.93, 135.93, -15), and every flat range and bearing differs from haversine by under a millimetre and 0.001 degree. The simulator position (61.37, -40.21) survives degE7 with a 4.0 mm error; degE7 resolves 1.11 cm north and 0.75 cm east, float32 degrees only 42.42 cm and 7.18 cm. The flat plane is 0.003% off at 1 km and 0.308% at 100 km at latitude 47.4, but already 0.134% at 10 km at latitude 78.2. Without wrapping, two points 106.6 m apart across the antimeridian appear 38381.7 km apart."},{"body":"The equirectangular plane uses cos(lat0) for every point, so its error grows with distance from the reference and faster at high latitude, where the cosine changes quickly; it is undefined at the poles. It also ignores curvature in height: 10 km away the ground lies about 7.8 m below the tangent plane. For a field, a farm or a city block it is excellent; for long routes, re-base the plane per leg or use an exact ECEF-to-ENU rotation. Flight stacks do the same thing at mission scale: ArduPilot scales longitude differences by the cosine of the two points' mean latitude, and PX4 projects around a reference point with an azimuthal equidistant projection. Send waypoints to the autopilot as latitude and longitude (MISSION_ITEM_INT carries them as degE7) and let it project them; use local metres only inside your own planning and display code.","title":"Where the flat plane breaks"},{"body":"The program uses only the standard library: in the app, choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To fly the mission, copy the four ENU vectors into a GoTo loop like the one the template's main.go runs over Square (keep mission.go), call sim.Save at the end and open Output for the replay; inside the loop, convert d.State().Pos back with ToLatLon to print latitude and longitude as the drone flies.","title":"Fly it in GopherForge"}],"takeaway":"Keep WGS84 latitude and longitude (as degE7 integers) on the wire and in missions, and use a local ENU or NED plane in metres for control, with the longitude difference wrapped and scaled by cos(latitude). The flat plane is excellent for a field and wrong for a country.","title":"Coordinates for drones: WGS84, ENU and NED, haversine and local tangent planes","unitID":"drones-foundations","wrongAnswers":["North = x, east = y, down = z","North = y, east = -x, down = z"]},{"conceptTag":"drones.ground-station","designGuide":{"cautions":["Read ignores contexts; only Close or a deadline unblocks it.","A heartbeat that outlives the station misleads the vehicle."],"cost":"Two goroutines and a WaitGroup per link, plus a timeout chosen for the radio you actually fly.","family":"drones","flow":["Reader goroutine decodes","Heartbeat tied to ctx","Select frames and timer","Cancel, close, wait"],"ratings":[],"strengths":["One owner per piece of state needs no locks.","A resettable timer turns silence into a typed error."]},"hint":"Read is a blocking call on the connection itself. Does it know about any context.Context?","id":"drones.ground-station","introduction":"A ground station is a small concurrent system: bytes arrive whenever the radio delivers them, heartbeats must go out on time whether or not anything arrives, operator commands interleave with both, and the link can vanish at any moment. Goroutines, channels, select and context map onto that shape directly. The hard parts are deciding who owns what and making sure every goroutine stops when the link or the program ends.","nuance":"net.Conn.Read never looks at a context. Close the connection, or set a read deadline in the past, and it returns an error. Cancel first so the other goroutines stop, then close, then wait.","objective":"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.","question":"A ground station cancels its context on shutdown, but the reader goroutine never exits: it is blocked in conn.Read. What makes Read return?","references":["https://github.com/bluenviron/gomavlib","https://pkg.go.dev/github.com/bluenviron/gomavlib/v4","https://mavlink.io/en/services/heartbeat.html","https://pkg.go.dev/net#Pipe"],"reviewAnswer":"Closing the connection or setting a read deadline","reviewPrompt":"What unblocks a stuck conn.Read?","sections":[{"body":"The reader goroutine owns conn.Read and the parser, and sends decoded frames on a small buffered channel. The heartbeat goroutine owns periodic writes and the sequence counter. Run's loop owns the state (latest values, the log) and is the only goroutine that touches it, so no mutex is needed. net.Conn allows concurrent calls, but keep a single writer per link anyway, so sequence numbers stay ordered and frames never interleave on transports that split large writes; operator commands would go through that writer too. The reader reports its final error on a channel with a buffer of one, so it can always exit even if nobody is listening any more.","title":"One owner per job"},{"body":"On radio links components usually send HEARTBEAT at 1 Hz and treat four or five missing ones as a disconnection. A ground station identifies itself with type MAV_TYPE_GCS (6), autopilot MAV_AUTOPILOT_INVALID (8) and usually system id 255; the vehicle uses those heartbeats for its own ground-station failsafe (FS_GCS_ENABLE in ArduPilot, the data-link-loss action NAV_DLL_ACT in PX4). Link loss on the station side is a time.Timer reset on every valid frame; since Go 1.23, with a go.mod that says go 1.23 or later, Reset and Stop guarantee that no stale value is received afterwards, so the old drain-before-reset idiom is unnecessary. The MAVLink documentation also warns against sending heartbeats from a thread that does not know the state of the rest of the component: tie the heartbeat to the same context so it stops when the station stops.","title":"Heartbeats and link loss"},{"body":"main connects the GroundStation to a simulated vehicle through net.Pipe, an in-memory, synchronous, full-duplex connection where each Write waits for the other side to read. The vehicle streams four HEARTBEAT and GLOBAL_POSITION_INT pairs 20 ms apart, then its radio goes quiet while its reader keeps draining heartbeats. The station sends a heartbeat every 100 ms and declares link loss after 500 ms without a valid frame, both scaled down from flight values so the program finishes in under a second. It prints only what the protocol orders: the station's log in stream order, the error Run returned and the first heartbeat the vehicle saw, never how many heartbeats were sent, which depends on scheduling.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tmagicV2              = 0xFD\n\theaderLen            = 10\n\tmsgHeartbeat         = 0\n\tmsgGlobalPositionInt = 33\n)\n\nvar crcExtra = map[uint32]byte{msgHeartbeat: 50, msgGlobalPositionInt: 104}\n\ntype Heartbeat struct {\n\tCustomMode                                              uint32\n\tType, Autopilot, BaseMode, SystemStatus, MavlinkVersion uint8\n}\n\ntype GlobalPositionInt struct {\n\tTimeBootMs       uint32\n\tLat, Lon         int32\n\tAlt, RelativeAlt int32\n\tVx, Vy, Vz       int16\n\tHdg              uint16\n}\n\ntype Frame struct {\n\tSeq, SysID, CompID uint8\n\tMsgID              uint32\n\tPayload            []byte\n}\n\nfunc crcAccumulate(crc uint16, b byte) uint16 {\n\ttmp := b ^ byte(crc)\n\ttmp ^= tmp << 4\n\treturn crc>>8 ^ uint16(tmp)<<8 ^ uint16(tmp)<<3 ^ uint16(tmp)>>4\n}\n\nfunc frameCRC(data []byte, extra byte) uint16 {\n\tcrc := uint16(0xFFFF)\n\tfor _, b := range data {\n\t\tcrc = crcAccumulate(crc, b)\n\t}\n\treturn crcAccumulate(crc, extra)\n}\n\nfunc Encode(seq, sysID, compID uint8, msgID uint32, msg any) []byte {\n\tpayload, err := binary.Append(nil, binary.LittleEndian, msg)\n\tif err != nil {\n\t\tpanic(err) // only fixed-size structs are passed in\n\t}\n\tfor len(payload) > 1 && payload[len(payload)-1] == 0 {\n\t\tpayload = payload[:len(payload)-1]\n\t}\n\tbuf := append([]byte{magicV2, byte(len(payload)), 0, 0, seq, sysID, compID,\n\t\tbyte(msgID), byte(msgID >> 8), byte(msgID >> 16)}, payload...)\n\treturn binary.LittleEndian.AppendUint16(buf, frameCRC(buf[1:], crcExtra[msgID]))\n}\n\nfunc Unmarshal(payload []byte, msg any) error {\n\tfull := make([]byte, binary.Size(msg))\n\tcopy(full, payload)\n\t_, err := binary.Decode(full, binary.LittleEndian, msg)\n\treturn err\n}\n\n// Parser cuts a byte stream into frames that pass their CRC (lesson 3).\ntype Parser struct{ buf []byte }\n\nfunc (p *Parser) Feed(data []byte) []Frame {\n\tp.buf = append(p.buf, data...)\n\tvar out []Frame\n\tfor {\n\t\ti := bytes.IndexByte(p.buf, magicV2)\n\t\tif i < 0 {\n\t\t\ti = len(p.buf)\n\t\t}\n\t\tp.buf = p.buf[i:]\n\t\tif len(p.buf) < headerLen || len(p.buf) < headerLen+int(p.buf[1])+2 {\n\t\t\treturn out\n\t\t}\n\t\tn := int(p.buf[1])\n\t\tid := uint32(p.buf[7]) | uint32(p.buf[8])<<8 | uint32(p.buf[9])<<16\n\t\textra, known := crcExtra[id]\n\t\tif !known || binary.LittleEndian.Uint16(p.buf[headerLen+n:]) != frameCRC(p.buf[1:headerLen+n], extra) {\n\t\t\tp.buf = p.buf[1:]\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, Frame{Seq: p.buf[4], SysID: p.buf[5], CompID: p.buf[6], MsgID: id,\n\t\t\tPayload: append([]byte(nil), p.buf[headerLen:headerLen+n]...)})\n\t\tp.buf = p.buf[headerLen+n+2:]\n\t}\n}\n\nvar ErrLinkLost = errors.New(\"link lost\")\n\n// GroundStation owns one link. Run starts a reader and a heartbeat goroutine\n// and handles decoded frames in its own loop until the link or ctx ends.\ntype GroundStation struct {\n\tConn        net.Conn\n\tHeartbeat   time.Duration // 1 s on a real link\n\tLinkTimeout time.Duration // several missed heartbeats on a real link\n\tLog         []string      // written only by Run's goroutine\n\tseq         uint8\n}\n\nfunc (g *GroundStation) Run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tframes := make(chan Frame, 16)\n\treadErr := make(chan error, 1)\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tgo func() { defer wg.Done(); readErr <- g.readLoop(ctx, frames) }()\n\tgo func() { defer wg.Done(); g.heartbeatLoop(ctx) }()\n\tdefer func() {\n\t\tcancel()       // stops the heartbeat: never advertise a dead ground station\n\t\tg.Conn.Close() // unblocks a Read or Write in progress\n\t\twg.Wait()\n\t}()\n\n\ttimer := time.NewTimer(g.LinkTimeout)\n\tdefer timer.Stop()\n\tfor {\n\t\tselect {\n\t\tcase f := <-frames:\n\t\t\tg.handle(f)\n\t\t\ttimer.Reset(g.LinkTimeout)\n\t\tcase <-timer.C:\n\t\t\treturn fmt.Errorf(\"%w: no frame for %v\", ErrLinkLost, g.LinkTimeout)\n\t\tcase err := <-readErr:\n\t\t\treturn err\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n}\n\nfunc (g *GroundStation) readLoop(ctx context.Context, out chan<- Frame) error {\n\tvar p Parser\n\tbuf := make([]byte, 512)\n\tfor {\n\t\tn, err := g.Conn.Read(buf)\n\t\tfor _, f := range p.Feed(buf[:n]) {\n\t\t\tselect {\n\t\t\tcase out <- f:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (g *GroundStation) heartbeatLoop(ctx context.Context) {\n\ttick := time.NewTicker(g.Heartbeat)\n\tdefer tick.Stop()\n\tfor {\n\t\t// MAV_TYPE_GCS (6), MAV_AUTOPILOT_INVALID (8), MAV_STATE_ACTIVE (4)\n\t\thb := Heartbeat{Type: 6, Autopilot: 8, SystemStatus: 4, MavlinkVersion: 3}\n\t\tif _, err := g.Conn.Write(Encode(g.seq, 255, 190, msgHeartbeat, hb)); err != nil {\n\t\t\treturn\n\t\t}\n\t\tg.seq++\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-tick.C:\n\t\t}\n\t}\n}\n\nfunc (g *GroundStation) handle(f Frame) {\n\tswitch f.MsgID {\n\tcase msgHeartbeat:\n\t\tvar hb Heartbeat\n\t\tif Unmarshal(f.Payload, &hb) == nil {\n\t\t\tg.Log = append(g.Log, fmt.Sprintf(\"seq %d  HEARTBEAT from %d/%d: type %d, autopilot %d, armed %t, custom mode %d\",\n\t\t\t\tf.Seq, f.SysID, f.CompID, hb.Type, hb.Autopilot, hb.BaseMode&0x80 != 0, hb.CustomMode))\n\t\t}\n\tcase msgGlobalPositionInt:\n\t\tvar p GlobalPositionInt\n\t\tif Unmarshal(f.Payload, &p) == nil {\n\t\t\tg.Log = append(g.Log, fmt.Sprintf(\"seq %d  GLOBAL_POSITION_INT: %.7f, %.7f, %.2f m above home\",\n\t\t\t\tf.Seq, float64(p.Lat)/1e7, float64(p.Lon)/1e7, float64(p.RelativeAlt)/1000))\n\t\t}\n\t}\n}\n\n// vehicle plays the autopilot at the other end of the link: it streams four\n// rounds of telemetry, then its radio goes quiet. Its reader keeps draining\n// the ground station's heartbeats until the link closes.\nfunc vehicle(conn net.Conn, wg *sync.WaitGroup, firstGCS *string) {\n\twg.Add(2)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar p Parser\n\t\tbuf := make([]byte, 512)\n\t\tfor {\n\t\t\tn, err := conn.Read(buf)\n\t\t\tfor _, f := range p.Feed(buf[:n]) {\n\t\t\t\tvar hb Heartbeat\n\t\t\t\tif *firstGCS == \"\" && f.MsgID == msgHeartbeat && Unmarshal(f.Payload, &hb) == nil {\n\t\t\t\t\t*firstGCS = fmt.Sprintf(\"seq %d HEARTBEAT from %d/%d, type %d, autopilot %d\", f.Seq, f.SysID, f.CompID, hb.Type, hb.Autopilot)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar seq uint8\n\t\tfor i := range 4 {\n\t\t\thb := Heartbeat{CustomMode: 4, Type: 2, Autopilot: 3, BaseMode: 0x81, SystemStatus: 4, MavlinkVersion: 3}\n\t\t\tpos := GlobalPositionInt{TimeBootMs: uint32(60000 + 20*i), Lat: 473977419, Lon: 85455938 + 27*int32(i),\n\t\t\t\tAlt: 498300, RelativeAlt: 10000 + 50*int32(i), Vy: 100, Hdg: 9000}\n\t\t\tfor _, frame := range [][]byte{Encode(seq, 1, 1, msgHeartbeat, hb), Encode(seq+1, 1, 1, msgGlobalPositionInt, pos)} {\n\t\t\t\tif _, err := conn.Write(frame); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tseq += 2\n\t\t\ttime.Sleep(20 * time.Millisecond)\n\t\t}\n\t}()\n}\n\nfunc main() {\n\tgcsEnd, vehicleEnd := net.Pipe() // in memory, synchronous, like a socket pair\n\tvar vehicleWG sync.WaitGroup\n\tvar firstGCS string\n\tvehicle(vehicleEnd, &vehicleWG, &firstGCS)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tgcs := &GroundStation{Conn: gcsEnd, Heartbeat: 100 * time.Millisecond, LinkTimeout: 500 * time.Millisecond}\n\terr := gcs.Run(ctx)\n\tvehicleWG.Wait() // Run closed the link, so both vehicle goroutines have returned\n\n\tfor _, line := range gcs.Log {\n\t\tfmt.Println(\"gcs:\", line)\n\t}\n\tfmt.Println(\"gcs stopped:\", err, \"| link lost:\", errors.Is(err, ErrLinkLost))\n\tfmt.Println(\"vehicle saw:\", firstGCS)\n}","language":"go","title":"A ground station over net.Pipe","walkthrough":"The eight gcs lines arrive in sequence order 0 to 7: HEARTBEATs from 1/1 with type 2, autopilot 3, armed true and custom mode 4, interleaved with GLOBAL_POSITION_INT reports whose longitude moves from 8.5455938 to 8.5456019 and whose altitude rises from 10.00 to 10.15 m above home. Then the timer fires and Run returns \"link lost: no frame for 500ms\"; errors.Is finds the wrapped ErrLinkLost, so the caller can tell a lost link from a cancelled context. The vehicle saw \"seq 0 HEARTBEAT from 255/190, type 6, autopilot 8\", the station's first heartbeat, sent before any telemetry arrived. Run's deferred function cancels the context, closes the connection to unblock the reader and waits for both goroutines."},{"body":"Order matters. cancel() makes the heartbeat loop return at its next select and lets a reader blocked on the frames channel give up. Close on the connection is what unblocks a goroutine sitting in Read or Write, because neither looks at a context; on network sockets SetReadDeadline is the other way to wake a reader. Only then does wg.Wait() return. Cancelling without closing leaves the reader blocked in Read for ever, and closing without cancelling leaves the heartbeat loop waiting for its next tick to discover the closed link. Run the program under go run -race and in tests that start and stop many stations: a leaked goroutine per reconnect is a slow memory leak on a companion computer that stays up for months.","title":"Shutdown without leaks"},{"body":"In production, github.com/bluenviron/gomavlib (v4) supplies the codec, dialects generated from the official XML such as common and ardupilotmega, endpoints for serial ports, UDP (server, client, broadcast), TCP and custom transports, automatic heartbeats, signing and routing; the mavp2p router is built on it. A Node takes Endpoints, a Dialect, OutVersion and OutSystemID; Initialize starts it, and Events delivers frames, channel openings and parse errors on one channel. EndpointUDPServer on :14550 receives what most vehicles and simulators send to the conventional ground-station port.","code":"import (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/bluenviron/gomavlib/v4\"\n\t\"github.com/bluenviron/gomavlib/v4/pkg/dialects/common\"\n)\n\nfunc listen() {\n\tnode := &gomavlib.Node{\n\t\tEndpoints: []gomavlib.Endpoint{\n\t\t\t&gomavlib.EndpointUDPServer{Address: \":14550\"},\n\t\t},\n\t\tDialect:         common.Dialect,\n\t\tOutVersion:      gomavlib.V2,\n\t\tOutSystemID:     255,\n\t\tHeartbeatPeriod: time.Second, // the library default is 5 s\n\t}\n\tif err := node.Initialize(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer node.Close()\n\n\tfor evt := range node.Events() {\n\t\tfrm, ok := evt.(*gomavlib.EventFrame)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch msg := frm.Message().(type) {\n\t\tcase *common.MessageHeartbeat:\n\t\t\tlog.Printf(\"system %d: type %d, custom mode %d\", frm.SystemID(), msg.Type, msg.CustomMode)\n\t\tcase *common.MessageGlobalPositionInt:\n\t\t\tlog.Printf(\"%.7f, %.7f, %.2f m above home\",\n\t\t\t\tfloat64(msg.Lat)/1e7, float64(msg.Lon)/1e7, float64(msg.RelativeAlt)/1000)\n\t\t}\n\t}\n}","language":"go","title":"The same with gomavlib","walkthrough":"The node owns the sockets, the codec and its own heartbeat goroutine, and hands frames to one loop, which stays the single owner of state as in the program above. HeartbeatPeriod is set because gomavlib sends one every 5 s by default, slower than the 1 Hz most radio links expect. Staleness checks and a link-loss timer still belong around this loop: the library tells you what arrived, not what stopped arriving."},{"body":"The program uses only the standard library, and net.Pipe needs no network, so it runs in the app's sandbox: choose New project > Robotics and simulation > Drone flight, replace main.go with it and tap Run. To put the simulator behind the link, replace the vehicle's four fixed rounds with a sim.Run loop that encodes a GLOBAL_POSITION_INT from d.Telemetry() each time its Time changes and writes it to vehicleEnd, then call sim.Save at the end so Output shows the flight the ground station watched.","title":"Fly it in GopherForge"}],"takeaway":"Give each job one goroutine and each piece of state one owner: a reader that decodes into a channel, a heartbeat tied to the same context, and a loop that selects on frames, a resettable link-loss timer and cancellation. Shut down by cancelling, closing the connection and waiting.","title":"A ground station in Go: reader goroutine, heartbeat, context and link-loss timeouts","unitID":"drones-foundations","wrongAnswers":["Cancelling the context passed to the reader goroutine","Draining the frames channel the reader sends on"]},{"conceptTag":"drones.telemetry-noise","designGuide":{"cautions":["Slowly wandering GPS error survives averaging and looks like bias.","Pairing a report with truth from another instant inflates the error."],"cost":"A recording loop that pairs each report with the true state, and three running sums per axis.","family":"drones","flow":["Pair report with truth","Error = measured - true","Bias, RMSE, max per axis","Fuse complementary sensors"],"ratings":[],"strengths":["Simulation gives exact truth to grade every sensor against.","Bias and RMSE separate systematic from random error."]},"hint":"Split the error into a constant part and a random part. Which of the two does averaging shrink?","id":"drones.telemetry-noise","introduction":"Every number a drone reports is an estimate built from imperfect sensors. GPS wanders by metres, a barometer measures altitude changes finely but drifts with the weather, and an IMU measures motion hundreds of times a second but drifts when integrated. Simulation gives you what real flights never do, the truth, so you can measure exactly how wrong each sensor is and in which way.","nuance":"Averaging shrinks independent noise by the square root of N but leaves the mean error untouched. Another sensor can estimate the offset only as well as its own error allows, and GPS altitude wanders by about a metre; EKFs model both.","objective":"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.","question":"A barometer reads 1.5 m high because the air pressure changed after take-off. Will averaging more barometer samples remove that error?","references":["https://docs.px4.io/main/en/advanced_config/tuning_the_ecl_ekf","https://ardupilot.org/copter/docs/common-apm-navigation-extended-kalman-filter-overview.html","https://en.wikipedia.org/wiki/Root_mean_square_deviation","https://en.wikipedia.org/wiki/Sensor_fusion"],"reviewAnswer":"No: it cuts noise only; bias needs another reference","reviewPrompt":"Can averaging remove a bias?","sections":[{"body":"GNSS gives absolute position and velocity at 5 to 10 Hz; a standalone receiver is good to a metre or a few horizontally and worse vertically, and its errors are correlated over seconds to minutes because they come from multipath, the atmosphere and satellite geometry. RTK with a base station brings that to centimetres. Receivers also measure velocity from Doppler shifts, often to better than 0.1 m/s, with errors that do not wander like position. A barometer turns pressure into altitude with fine resolution, but drifts as the weather and temperature change and is disturbed by propeller wash, ground effect and airspeed. The IMU's accelerometers and gyroscopes run at hundreds of hertz to kilohertz and are excellent over short times, but their biases integrate: velocity error grows with time and position error with its square, and vibration makes it worse. The magnetometer gives heading and is disturbed by motor currents and nearby steel. Each sensor is good where another is weak.","title":"What each sensor gives you"},{"body":"Define error as measured minus true. The bias is the mean error, the systematic part; the RMSE is the square root of the mean squared error and includes both parts, since RMSE squared equals bias squared plus the variance. The maximum error matters for safety margins such as the buffer between a geofence and the boundary it protects. Horizontal error is the length of a 2D vector: with independent noise of sigma per axis its RMSE is sigma times the square root of 2. An error that wanders more slowly than your measurement window looks like bias: over one short flight its mean is not zero, even though it averages out over hours. Datasheets quote CEP, 2DRMS or 95% figures; know which one you are reading before comparing receivers.","title":"Bias, RMSE and maximum error"},{"body":"The program takes off to 20 m, hovers for 60 s, flies three legs (one climbing to 30 m) in a wind of about 3 m/s with 1.5 m/s gusts, and returns home. Before every step, record pairs the telemetry report with State() when the report is stamped with the current time, the only moment when truth and measurement describe the same instant. It prints the mean error, RMSE and maximum error of GPS position, barometer and velocity; averages N GPS samples in the hover and compares the result with what independent noise would give; measures a 1 s average while moving; integrates velocity from the first GPS fix; and estimates a 1.5 m weather offset added to the baro from GPS altitude.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// errStats accumulates measurement errors (measured minus true).\ntype errStats struct {\n\tn               int\n\tsum, sumSq, max float64\n}\n\nfunc (s *errStats) add(e float64) {\n\ts.n++\n\ts.sum += e\n\ts.sumSq += e * e\n\ts.max = max(s.max, math.Abs(e))\n}\n\nfunc (s *errStats) bias() float64 { return s.sum / float64(s.n) }\nfunc (s *errStats) rmse() float64 { return math.Sqrt(s.sumSq / float64(s.n)) }\n\n// sample is one telemetry report next to the truth at the same instant.\ntype sample struct {\n\tt          float64\n\ttruth, gps drone.Vec3\n\tvel, trueV drone.Vec3\n\tbaro       float64\n\tmoving     bool\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 3, Y: -1}, Gust: 1.5, Seed: 7})\n\td := sim.Drone()\n\n\tvar samples []sample\n\tlastTel := -1.0\n\t// record runs before every step. Telemetry is refreshed at 5 Hz inside\n\t// Step, so a report stamped with the current time pairs with State().\n\trecord := func() {\n\t\ttel, st := d.Telemetry(), d.State()\n\t\tif tel.Time != lastTel && tel.Time == sim.Time() && !st.Landed {\n\t\t\tlastTel = tel.Time\n\t\t\tsamples = append(samples, sample{tel.Time, st.Pos, tel.GPS, tel.Velocity, st.Vel,\n\t\t\t\ttel.BaroAlt, st.Vel.Horizontal().Len() > 1})\n\t\t}\n\t}\n\tfly := func(limit float64, done func() bool) {\n\t\tif !sim.RunUntil(limit, func(float64) bool { record(); return done() }) {\n\t\t\tlog.Fatalf(\"leg not finished: %+v\", d.State())\n\t\t}\n\t}\n\n\tmust(d.Arm())\n\tmust(d.TakeOff(20))\n\tfly(30, func() bool { return d.State().Mode == drone.Hold })\n\tsim.Mark(\"hover 60 s\")\n\tfirst := len(samples)\n\tsim.Run(60, func(float64) { record() })\n\thover := samples[first:]\n\tfor _, wp := range []drone.Vec3{{X: 80, Y: 0, Z: 20}, {X: 80, Y: 80, Z: 30}, {X: 0, Y: 80, Z: 30}} {\n\t\tmust(d.GoTo(wp))\n\t\tfly(90, d.Arrived)\n\t}\n\tmust(d.ReturnHome())\n\tfly(120, func() bool { return d.State().Landed })\n\n\tvar gpsH, gpsE, gpsN, gpsV, baro, velH, velE, velN errStats\n\tfor _, s := range samples {\n\t\te := s.gps.Sub(s.truth)\n\t\tgpsH.add(e.Horizontal().Len())\n\t\tgpsE.add(e.X)\n\t\tgpsN.add(e.Y)\n\t\tgpsV.add(e.Z)\n\t\tbaro.add(s.baro - s.truth.Z)\n\t\tv := s.vel.Sub(s.trueV)\n\t\tvelH.add(v.Horizontal().Len())\n\t\tvelE.add(v.X)\n\t\tvelN.add(v.Y)\n\t}\n\tfmt.Printf(\"%d telemetry samples at 5 Hz over %.0f s of flight\\n\", len(samples), samples[len(samples)-1].t-samples[0].t)\n\tfmt.Println(\"sensor               mean error              RMSE       max |err|\")\n\trow := func(name, bias, unit string, s errStats) {\n\t\tfmt.Printf(\"%-20s %-22s %5.2f %-4s %5.2f %s\\n\", name, bias, s.rmse(), unit, s.max, unit)\n\t}\n\trow(\"GPS horizontal\", fmt.Sprintf(\"e %+.2f n %+.2f m\", gpsE.bias(), gpsN.bias()), \"m\", gpsH)\n\trow(\"GPS vertical\", fmt.Sprintf(\"%+.2f m\", gpsV.bias()), \"m\", gpsV)\n\trow(\"barometer\", fmt.Sprintf(\"%+.2f m\", baro.bias()), \"m\", baro)\n\trow(\"velocity horizontal\", fmt.Sprintf(\"e %+.3f n %+.3f m/s\", velE.bias(), velN.bias()), \"m/s\", velH)\n\n\t// Averaging N samples in the hover. Independent noise would shrink by the\n\t// square root of N; an error that wanders for tens of seconds does not.\n\tfmt.Println(\"GPS horizontal error of an N-sample average, 60 s hover:\")\n\tvar one float64\n\tfor _, n := range []int{1, 5, 25, 100} {\n\t\tvar s errStats\n\t\tfor i := n; i <= len(hover); i++ {\n\t\t\tvar avg drone.Vec3\n\t\t\tfor _, h := range hover[i-n : i] {\n\t\t\t\tavg = avg.Add(h.gps.Sub(h.truth).Scale(1 / float64(n)))\n\t\t\t}\n\t\t\ts.add(avg.Horizontal().Len())\n\t\t}\n\t\tif n == 1 {\n\t\t\tone = s.rmse()\n\t\t}\n\t\tfmt.Printf(\"  N=%3d (%4.1f s): RMSE %.2f m, independent noise would give %.2f m\\n\",\n\t\t\tn, float64(n)/5, s.rmse(), one/math.Sqrt(float64(n)))\n\t}\n\n\t// In motion an average also lags: it reports where the drone was.\n\tvar lag errStats\n\tfor i := 4; i < len(samples); i++ {\n\t\tif !samples[i].moving {\n\t\t\tcontinue\n\t\t}\n\t\tvar avg drone.Vec3\n\t\tfor _, s := range samples[i-4 : i+1] {\n\t\t\tavg = avg.Add(s.gps.Scale(0.2))\n\t\t}\n\t\tlag.add(avg.Sub(samples[i].truth).Horizontal().Len())\n\t}\n\tfmt.Printf(\"GPS 1 s average while moving: RMSE %.2f m over %d samples\\n\", lag.rmse(), lag.n)\n\n\t// Velocity measures change, not position: integrated from the first GPS\n\t// fix it is smooth, but it keeps that fix's error and slowly adds its own.\n\tvar dr errStats\n\tp := samples[0].gps\n\tfor i := 1; i < len(samples); i++ {\n\t\ta, b := samples[i-1], samples[i]\n\t\tp = p.Add(a.vel.Add(b.vel).Scale((b.t - a.t) / 2)) // trapezoid rule\n\t\tdr.add(p.Sub(b.truth).Horizontal().Len())\n\t}\n\tfmt.Printf(\"velocity integrated from the first GPS fix: start error %.2f m, RMSE %.2f m, final %.2f m\\n\",\n\t\tsamples[0].gps.Sub(samples[0].truth).Horizontal().Len(), dr.rmse(),\n\t\tp.Sub(samples[len(samples)-1].truth).Horizontal().Len())\n\n\t// Calibrating one sensor against another inherits the other's error: a\n\t// baro offset estimated from GPS altitude over this flight.\n\tconst weather = 1.5 // pressure fell after take-off: the baro reads 1.5 m high\n\tvar offset float64\n\tfor _, s := range samples {\n\t\toffset += (s.baro + weather - s.gps.Z) / float64(len(samples))\n\t}\n\tfmt.Printf(\"baro offset estimated from GPS altitude: %+.2f m (true %+.2f m)\\n\", offset, weather)\n\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Measure the simulator's sensors","walkthrough":"609 samples over 122 s confirm 5 Hz. GPS RMSE is 1.20 m horizontally and 1.51 m vertically, and over this one flight the mean errors are not zero (e -0.25, n +0.29 m, vertical +1.13 m): an error that wanders for about 20 s does not average out in two minutes, so it looks like bias. The barometer (0.30 m, mean +0.00 m) and velocity (0.14 m/s, means of a few mm/s) carry independent noise. In the hover, averages of 5, 25 and 100 GPS samples are still 1.09, 1.04 and 1.00 m off, where independent noise would fall to 0.57, 0.26 and 0.13 m. While moving, the 1 s average is 4.35 m off because it reports where the drone was 0.4 s earlier. Integrated velocity follows the path but stays as wrong as its first fix: the error is 1.56 m at the start, 1.81 m at the end and 1.85 m RMS. The baro offset estimated from GPS is +0.37 m instead of +1.50 m: the true offset minus GPS altitude's own +1.13 m mean error."},{"body":"The sensors fail in different ways. GPS position is absolute but wanders, so averaging it buys little and lags in motion. Velocity, from GNSS Doppler or an integrated IMU, follows motion precisely over seconds but only measures change, so integrating it inherits the starting error and slowly drifts. The barometer resolves small height changes but its offset moves with the weather, and calibrating it against GPS altitude imports GPS's own wander. A fusion filter predicts with the fast, smooth sensors and corrects with the absolute ones, weighting each by an error model that includes how its error evolves over time. PX4's EKF2 and ArduPilot's EKF3 predict with the IMU, correct with GNSS, barometer, magnetometer and other sensors, and estimate sensor biases as extra states. The simulator still leaves things out: it has no IMU signals and no barometer drift (the program adds the 1.5 m offset itself), and its autopilot flies on the true state, while a real vehicle holds its own estimate and wanders with it. The next unit builds complementary and Kalman filters on these measurements.","title":"Why fusion is needed"},{"body":"In the app, choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go. Tap Run to print the tables, then open Output: the replay shows the climb, the 60 s hover mark, the three waypoints and the return home. Change Seed or GPSNoise in drone.Config and run again: the RMSE scales with GPSNoise, the mean errors change sign and size from flight to flight because the error wanders, and the N-sample averages stay stuck near the single-sample error.","title":"Fly it in GopherForge"}],"takeaway":"Measure sensors against truth before trusting them: bias is the mean error and RMSE combines bias and noise. Averaging removes only fast, independent noise, lags in motion and leaves slow GPS wander and bias in place; fusing sensors with complementary errors, as an EKF does, is how flight controllers get estimates good enough to fly on.","title":"Sensors and noise: GPS, barometer and IMU, truth against measurement, RMSE and bias","unitID":"drones-foundations","wrongAnswers":["Yes: averaging N samples divides every error by the root of N","Yes, once the averaging window is at least 1 s long"]},{"conceptTag":"drones.pid-altitude","designGuide":{"cautions":["An integral without clamping turns saturation into overshoot.","D differentiates noise; feed it a filtered rate, not raw altitude."],"cost":"A few lines of code and a tuning session per airframe, repeated whenever mass, propellers or battery change.","family":"drones","flow":["Feedforward hover thrust","P on altitude error","I clamped, frozen at limit","D from climb rate"],"ratings":[],"strengths":["Three gains cover most single-axis loops on a multicopter.","Each term maps to a measurable symptom: offset, ringing, overshoot."]},"hint":"Write error = setpoint - measurement and differentiate it. Which part changes instantly when a new altitude is commanded?","id":"drones.pid-altitude","introduction":"SetThrust hands the program the collective thrust: about 0.5 hovers, more climbs, less sinks, and nothing else holds the altitude. Thrust sets vertical acceleration while you care about position, so the plant is a double integrator with a little drag, the simplest plant on which a naive controller rings. This lesson builds the PID found in every flight stack's inner loops, flies four variants of it through the same 10 m step on identical simulators, and measures what each term buys.","nuance":"While the setpoint is constant both forms give the same D term. They differ only at setpoint changes, where d(error)/dt contains the step divided by dt; noise still needs a low-pass filter either way.","objective":"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.","question":"Why do flight controllers usually compute the PID derivative term from the measured altitude instead of from the error?","references":["https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller","https://en.wikipedia.org/wiki/Integral_windup","https://docs.px4.io/main/en/config_mc/pid_tuning_guide_multicopter.html"],"reviewAnswer":"No derivative kick when the setpoint jumps","reviewPrompt":"Why take D on the measurement?","sections":[{"body":"In this simulator the vertical motion in manual thrust is z'' = 2g(u - 0.5) - 0.3 z': thrust u above 0.5 accelerates upward, below 0.5 downward, and a weak drag is the only damping. The proportional term pushes in proportion to the present error, which on a double integrator acts like a spring with almost no damper, so P alone overshoots and rings. A feedforward bias, the controller's estimate of hover thrust, does most of the holding; when that estimate is wrong (a payload, a sagging battery, a different propeller) a P-only loop needs a standing error to make up the difference, (true hover - bias) / Kp. The integral term accumulates past error until it supplies that missing thrust. The derivative term opposes the rate of change, adding the damping the plant lacks. Each term has a symptom you can measure: offset without I, ringing without D, overshoot when I is allowed to wind up.","title":"Three terms, three jobs"},{"body":"The program climbs to 5 m on the autopilot, waits 2 s, then hands thrust to a controller and commands 15 m for 40 s at 50 Hz. Every controller uses a hover guess of 0.45 while the true hover thrust is 0.50, and reads the true altitude so that only the controller differs (the next lessons replace it with an estimate). Rise time is the time from 10% to 90% of the step, overshoot is the peak beyond 15 m as a share of the 10 m step, settling time is the last moment the altitude was outside a band of 2% of the step (0.2 m), mean err and ripple cover the last 10 s, and sat is the share of steps with thrust at 0 or 1. The PID flight is landed and saved for the replay.","code":"package main\n\n// PID altitude control: the program owns the collective thrust and must\n// climb from 5 m to 15 m and stay there. Four controllers fly the same\n// step on identical simulators; the PID flight is saved for the replay.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// PID computes a thrust command from an altitude error.\ntype PID struct {\n\tKp, Ki, Kd float64\n\tBias       float64 // feedforward: our estimate of hover thrust\n\tMin, Max   float64 // actuator limits\n\tIMax       float64 // limit on the integral's contribution\n\tAntiWindup bool    // clamp the integral and freeze it while saturated\n\n\tintegral float64\n\tprevMeas float64\n\tprimed   bool\n}\n\n// Update runs one control step. The derivative acts on the measurement,\n// not on the error, so a setpoint change does not kick the output.\nfunc (c *PID) Update(setpoint, meas, dt float64) float64 {\n\terr := setpoint - meas\n\tderiv := 0.0\n\tif c.primed {\n\t\tderiv = -(meas - c.prevMeas) / dt\n\t}\n\tc.prevMeas, c.primed = meas, true\n\n\tcandidate := c.integral + c.Ki*err*dt\n\traw := c.Bias + c.Kp*err + candidate + c.Kd*deriv\n\tout := clamp(raw, c.Min, c.Max)\n\tpushingPastLimit := raw != out && (raw > out) == (err > 0)\n\tif !c.AntiWindup || !pushingPastLimit {\n\t\tc.integral = candidate\n\t}\n\tif c.AntiWindup {\n\t\tc.integral = clamp(c.integral, -c.IMax, c.IMax)\n\t}\n\treturn out\n}\n\ntype metrics struct {\n\trise, overshoot, settle float64\n\tsettled                 bool\n\tmeanErr, ripple, sat    float64\n}\n\nconst start, goal, window = 5.0, 15.0, 40.0\n\n// fly climbs to 5 m on the autopilot, then hands thrust to the controller\n// for a 10 m step and measures the response on the true altitude.\nfunc fly(name string, c *PID) (metrics, *drone.Sim) {\n\tsim := drone.New(drone.Config{Seed: 1})\n\td := sim.Drone()\n\td.Arm()\n\td.TakeOff(start)\n\tsim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })\n\tsim.Run(2, nil)\n\tsim.Mark(name + \": step to 15 m\")\n\n\tstep := goal - start\n\tt0 := sim.Time()\n\tvar t10, t90, lastOut, sum float64\n\tpeak, lo, hi := start, math.Inf(1), math.Inf(-1)\n\tvar n, satSteps, steps int\n\tsim.Run(window, func(t float64) {\n\t\tz := d.State().Pos.Z\n\t\tu := c.Update(goal, z, sim.Dt())\n\t\td.SetThrust(u)\n\t\tel := t - t0\n\t\tif t10 == 0 && z >= start+0.1*step {\n\t\t\tt10 = el\n\t\t}\n\t\tif t90 == 0 && z >= start+0.9*step {\n\t\t\tt90 = el\n\t\t}\n\t\tpeak = math.Max(peak, z)\n\t\tif math.Abs(goal-z) > 0.02*step {\n\t\t\tlastOut = el\n\t\t}\n\t\tif el >= window-10 {\n\t\t\tsum += goal - z\n\t\t\tlo, hi = math.Min(lo, z), math.Max(hi, z)\n\t\t\tn++\n\t\t}\n\t\tif u == c.Min || u == c.Max {\n\t\t\tsatSteps++\n\t\t}\n\t\tsteps++\n\t})\n\treturn metrics{\n\t\trise:      t90 - t10,\n\t\tovershoot: math.Max(0, peak-goal) / step * 100,\n\t\tsettle:    lastOut,\n\t\tsettled:   lastOut < window-10,\n\t\tmeanErr:   sum / float64(n),\n\t\tripple:    hi - lo,\n\t\tsat:       float64(satSteps) / float64(steps) * 100,\n\t}, sim\n}\n\nfunc main() {\n\tgains := func(kp, ki, kd float64, antiWindup bool) *PID {\n\t\treturn &PID{Kp: kp, Ki: ki, Kd: kd, Bias: 0.45, Min: 0, Max: 1, IMax: 0.1, AntiWindup: antiWindup}\n\t}\n\truns := []struct {\n\t\tname string\n\t\tc    *PID\n\t}{\n\t\t{\"P\", gains(0.10, 0, 0, true)},\n\t\t{\"PI\", gains(0.10, 0.03, 0, true)},\n\t\t{\"PID\", gains(0.10, 0.03, 0.12, true)},\n\t\t{\"PID no anti-windup\", gains(0.10, 0.03, 0.12, false)},\n\t}\n\n\tfmt.Println(\"step 5 m -> 15 m, hover guess 0.45 (true hover 0.50), 50 Hz\")\n\tfmt.Printf(\"%-19s %6s %9s %8s %9s %7s %5s\\n\", \"controller\", \"rise\", \"overshoot\", \"settle\", \"mean err\", \"ripple\", \"sat\")\n\tvar keep *drone.Sim\n\tfor _, r := range runs {\n\t\tm, sim := fly(r.name, r.c)\n\t\tsettle := \"never\"\n\t\tif m.settled {\n\t\t\tsettle = fmt.Sprintf(\"%.1f s\", m.settle)\n\t\t}\n\t\tfmt.Printf(\"%-19s %4.1f s %8.0f%% %8s %7.2f m %5.2f m %4.0f%%\\n\",\n\t\t\tr.name, m.rise, m.overshoot, settle, m.meanErr, m.ripple, m.sat)\n\t\tif r.name == \"PID\" {\n\t\t\tkeep = sim\n\t\t}\n\t}\n\n\td := keep.Drone()\n\td.Land()\n\tkeep.RunUntil(60, func(float64) bool { return d.State().Landed })\n\tkeep.Save()\n}\n\nfunc clamp(v, lo, hi float64) float64 { return math.Max(lo, math.Min(hi, v)) }","language":"go","title":"Four controllers, one step","walkthrough":"P rises fastest (1.0 s) but overshoots 55%, never enters the 0.2 m band and settles at a mean error of 0.50 m, exactly (0.50 - 0.45) / 0.10. PI removes that offset on average but adds lag to a loop that had almost no damping: 60% overshoot and a ripple of 7.25 m still swinging after 30 s. PID rises in 2.0 s with 4% overshoot, settles in 7.7 s and ends at 0.00 m error. The same gains without anti-windup reach 25% overshoot and settle in 9.5 s, because the integral grew during the climb and had to unwind past the target. The last line is the saved PID flight: landed, battery 90%."},{"body":"Because error = setpoint - measurement, its derivative equals minus the measurement's derivative whenever the setpoint is constant. The two differ only when the setpoint changes: a 10 m step differentiated over one 0.02 s sample is 500 m/s, which times Kd = 0.12 asks for a thrust of 60 for one step, a derivative kick that slams the motors. Taking D from the measurement keeps all the damping and drops the kick. The derivative also amplifies noise: differencing a barometer with 0.3 m of noise at 50 Hz gives a rate noise of about 21 m/s. Real controllers therefore take the rate from the estimator (or the gyro, for the rate loop) and low-pass filter the D path, as PX4 does in its rate controller.","code":"// Derivative on error: kicks when the setpoint jumps.\ndErr := (err - c.prevErr) / dt\n\n// Derivative on measurement: equal while the setpoint is constant,\n// and no kick when it changes.\ndMeas := -(meas - c.prevMeas) / dt\n\n// Better: the estimator's climb rate, low-pass filtered (tauD seconds).\nc.dFilt += (-climbRate - c.dFilt) * dt / (tauD + dt)\nd := c.Kd * c.dFilt","language":"go","title":"Derivative on measurement, not on error","walkthrough":"The first form differentiates the setpoint too. The second is what the program's Update method does. The third avoids differencing a noisy altitude at all: an estimator already provides the climb rate, and a first-order low-pass with time constant tauD trims what noise remains before the gain multiplies it."},{"body":"Thrust is limited to 0..1, so for part of a large step the controller asks for more than the motors can give. An integral that keeps accumulating during that time stores error the plant could never act on, and it must be paid back as overshoot after the target is reached. The program uses two common defences together: it clamps the integral's contribution to 0.1 of thrust (twice the expected hover error), and it freezes integration while the output is saturated in the direction the error pushes. Back-calculation, which bleeds the integral by the amount the output was clipped, is a third. Also reset or preload the integral when a mode hands control to the loop, so the first output continues the previous thrust instead of jumping, and saturate the output yourself rather than trusting the next layer to do it.","title":"Windup, clamping and saturation"},{"body":"Create the project with New project > Robotics and simulation > Drone flight, replace main.go with this lesson's program (mission.go can stay; this program does not use it) and tap Run. The table appears in the console; open Output to watch the replay of the PID flight: the take-off to 5 m, the marked step to 15 m with its small overshoot in the altitude strip, and the landing. Then change the gains in main, for example Kd to 0 or AntiWindup to false, and compare the tables and replays.","title":"Fly it in GopherForge"}],"takeaway":"On a thrust-to-altitude loop, P alone leaves an offset and rings, I removes the offset but adds lag, and D supplies the damping. Take D from the measurement, clamp the integral and freeze it while the output saturates, and judge a tune by rise time, overshoot, settling time and steady-state error.","title":"PID altitude control: P, I and D on the collective thrust","unitID":"drones-control","wrongAnswers":["It removes the steady-state error that P leaves","It stops the integral from winding up"]},{"conceptTag":"drones.cascaded-control","designGuide":{"cautions":["An outer loop nearly as fast as the inner one oscillates.","Noise in the target velocity passes straight through feedforward.","A lost setpoint stream makes PX4 leave offboard mode."],"cost":"One small controller per axis, a fixed-rate loop, and a setpoint stream the autopilot can rely on.","family":"drones","flow":["Target pos and velocity","P + feedforward -> vel","SetVelocity PI loop","Attitude and rate in FC"],"ratings":[],"strengths":["Each loop is simple and is tuned on its own, inside out.","Go closes only the slow outer loop; the firmware keeps the fast ones."]},"hint":"In steady following the outer loop must command 3 m/s. With only P, what error produces that command?","id":"drones.cascaded-control","introduction":"No flight stack controls position with one big loop. PX4 and ArduPilot nest them: position error becomes a velocity setpoint, velocity error an acceleration and tilt, attitude error a body rate, rate error a torque for the mixer. Each loop only has to control something that already responds quickly, because the loop inside it made it so. A companion computer running Go usually sits at the top of this cascade and sends position or velocity setpoints; this lesson writes that outer loop, holds a point in a 4 m/s wind and then follows a target that moves into the wind.","nuance":"Steady wind is different: the velocity loop's integral cancels it, and the P hold stayed within 0.12 m. An outer integral also removes the lag, after a 4.29 m transient; feedforward stayed within 0.77 m.","objective":"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.","question":"An outer P position loop with Kp 0.5 follows a target moving steadily at 3 m/s, over a velocity loop that tracks well. How far behind does the drone settle, and what removes the lag?","references":["https://docs.px4.io/main/en/flight_stack/controller_diagrams.html","https://docs.px4.io/main/en/flight_modes/offboard.html","https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller"],"reviewAnswer":"v / Kp = 6 m behind; feedforward removes it","reviewPrompt":"P loop follows 3 m/s, Kp 0.5: lag?","sections":[{"body":"PX4's multicopter controller is documented as a standard cascade: a P position loop (MPC_XY_P) produces a velocity setpoint, a PID velocity loop produces an acceleration, which becomes a thrust vector and attitude setpoint, a P attitude loop produces body rates, and a PID rate loop produces torques for control allocation. The rate loop runs at the gyro rate in the firmware, far faster than the position loop. The rule of thumb is that each inner loop should be several times, often five to ten times, faster in bandwidth than the loop around it, so the outer loop can treat it as nearly instant. In this simulator SetVelocity's loop is a PI loop on ground velocity that tilts the thrust by up to 35 degrees; its proportional gain of 2.5 per second gives a time constant of about 0.4 s, and it is stepped at 50 Hz. The program's position loop runs at 10 Hz with Kp = 0.5, a time constant of 2 s, five times slower. An outer gain close to the inner loop's bandwidth sees the inner loop's lag as phase loss and oscillates.","title":"The cascade and its rates"},{"body":"The program takes off to 10 m in a 4 m/s wind from the west with 1.5 m/s gusts. It first sends velocity zero with no position loop for 20 s, then holds the point with a P loop (Kp 0.5) for 20 s. Then the target starts moving west, into the wind, at 3 m/s, and three outer loops follow it for 30 s each: P alone, PI with Ki 0.1 (integral limited to 5 m/s and frozen while the command is at its limit), and P plus velocity feedforward. Before each of the last two runs the target stops for 15 s, so every run starts from a hover. The position loop runs on every fifth 50 Hz step; altitude has its own P term. Each row reports the largest horizontal distance from the target, and the mean east offset and mean east velocity command over the last 10 s.","code":"package main\n\n// Cascaded control: the program closes a position loop at 10 Hz and sends\n// velocity setpoints to the autopilot's faster velocity loop (SetVelocity).\n// A 4 m/s wind from the west with 1.5 m/s gusts pushes the drone east.\n// The drone first holds a point, then follows a target moving upwind.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// PositionLoop turns a position error into a velocity setpoint.\ntype PositionLoop struct {\n\tKp, Ki      float64\n\tFeedForward bool    // add the target's own velocity to the command\n\tMaxSpeed    float64 // limit on the commanded horizontal speed\n\tMaxI        float64 // limit on the integral's contribution, m/s\n\n\tintegral drone.Vec3\n}\n\nfunc (c *PositionLoop) Update(target, targetVel, pos drone.Vec3, dt float64) drone.Vec3 {\n\terr := target.Sub(pos).Horizontal()\n\tcmd := err.Scale(c.Kp)\n\tif c.FeedForward {\n\t\tcmd = cmd.Add(targetVel.Horizontal())\n\t}\n\tif c.Ki > 0 {\n\t\tif cmd.Add(c.integral).Len() < c.MaxSpeed { // integrate only while not limited\n\t\t\tc.integral = clampLen(c.integral.Add(err.Scale(c.Ki*dt)), c.MaxI)\n\t\t}\n\t\tcmd = cmd.Add(c.integral)\n\t}\n\treturn clampLen(cmd, c.MaxSpeed)\n}\n\ntype phase struct {\n\tname   string\n\tloop   *PositionLoop // nil: no position loop, velocity setpoint zero\n\tfollow bool          // the target moves upwind at 3 m/s\n\tsecs   float64\n\tquiet  bool // a pause between runs: the target stops, nothing is printed\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 4}, Gust: 1.5, Seed: 2})\n\td := sim.Drone()\n\td.Arm()\n\td.TakeOff(10)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\ttarget := d.State().Pos\n\ttargetVel := drone.Vec3{X: -3} // west, into the wind\n\tsim.Waypoint(target)\n\n\tconst outerEvery = 5 // physics runs at 50 Hz, the position loop at 10 Hz\n\touterDt := outerEvery * sim.Dt()\n\tpause := phase{\"target stops\", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, false, 15, true}\n\tphases := []phase{\n\t\t{\"velocity 0, no position loop\", nil, false, 20, false},\n\t\t{\"hold, P Kp 0.5\", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, false, 20, false},\n\t\t{\"follow, P Kp 0.5\", &PositionLoop{Kp: 0.5, MaxSpeed: 10}, true, 30, false},\n\t\tpause,\n\t\t{\"follow, PI Ki 0.1\", &PositionLoop{Kp: 0.5, Ki: 0.1, MaxSpeed: 10, MaxI: 5}, true, 30, false},\n\t\tpause,\n\t\t{\"follow, P + feedforward\", &PositionLoop{Kp: 0.5, FeedForward: true, MaxSpeed: 10}, true, 30, false},\n\t}\n\tfmt.Printf(\"wind (4.0, 0.0) m/s, gusts 1.5 m/s; position loop %.0f Hz over SetVelocity\\n\", 1/outerDt)\n\tfmt.Println(\"means over the last 10 s; x off > 0: east of the target, downwind and behind\")\n\tfmt.Printf(\"%-28s %8s %10s %12s\\n\", \"phase\", \"max off\", \"mean x off\", \"mean cmd vx\")\n\tfor _, p := range phases {\n\t\tsim.Mark(p.name)\n\t\tvar cmd drone.Vec3\n\t\tvar maxOff, sumOff, sumCmd float64\n\t\tvar n, step int\n\t\tt0 := sim.Time()\n\t\tsim.Run(p.secs, func(t float64) {\n\t\t\tif p.follow {\n\t\t\t\ttarget = target.Add(targetVel.Scale(sim.Dt()))\n\t\t\t}\n\t\t\tpos := d.State().Pos\n\t\t\tif step%outerEvery == 0 {\n\t\t\t\tcmd = drone.Vec3{}\n\t\t\t\tif p.loop != nil {\n\t\t\t\t\tv := drone.Vec3{}\n\t\t\t\t\tif p.follow {\n\t\t\t\t\t\tv = targetVel\n\t\t\t\t\t}\n\t\t\t\t\tcmd = p.loop.Update(target, v, pos, outerDt)\n\t\t\t\t}\n\t\t\t\tcmd.Z = 0.8 * (target.Z - pos.Z) // altitude: a plain P loop\n\t\t\t\td.SetVelocity(cmd, 0)\n\t\t\t}\n\t\t\tstep++\n\t\t\tmaxOff = math.Max(maxOff, pos.Sub(target).Horizontal().Len())\n\t\t\tif t-t0 >= p.secs-10 {\n\t\t\t\tsumOff += pos.X - target.X // positive: east, downwind of the target\n\t\t\t\tsumCmd += cmd.X\n\t\t\t\tn++\n\t\t\t}\n\t\t})\n\t\tif !p.quiet {\n\t\t\tfmt.Printf(\"%-28s %6.2f m %8.2f m %8.2f m/s\\n\", p.name, maxOff, sumOff/float64(n), sumCmd/float64(n))\n\t\t}\n\t}\n\td.ReturnHome()\n\tsim.RunUntil(120, func(float64) bool { return d.State().Landed })\n\tsim.Save()\n}\n\nfunc clampLen(v drone.Vec3, limit float64) drone.Vec3 {\n\tif l := v.Len(); l > limit {\n\t\treturn v.Scale(limit / l)\n\t}\n\treturn v\n}","language":"go","title":"Hold a point, then follow a target","walkthrough":"Velocity zero without any position loop stays within 0.18 m: the autopilot's velocity loop has an integral that learned the tilt against the 4 m/s wind during the take-off, and the gusts change slowly enough for it to follow. The P hold stays within 0.12 m with a mean command of 0.00 m/s, so the outer loop never sees the steady wind. Following the target, P alone settles 5.99 m behind while commanding -3.00 m/s: a P loop commands speed only in proportion to error, and 3 / 0.5 = 6 m. PI removes the lag (-0.03 m) after a 4.29 m transient. Feedforward removes it from the start and never falls more than 0.77 m behind."},{"body":"A steady disturbance is best cancelled by the loop it enters. Wind is a force, it shows up first as a velocity error, and an integral in the velocity loop learns the tilt that cancels it. PX4 is built this way, with a P position loop over a PID velocity loop, so a position setpoint is held in steady wind with no position integral; that is what the hold rows show. A moving reference is different: an outer P loop needs a standing error to command a speed, error = v / Kp. An outer integral removes that lag, but slowly, with overshoot and windup, and it can fight the inner integral in gusts. Feedforward is the better tool: send the target's velocity directly and let P correct only the residual, as PX4's position controller does with the velocity of a trajectory setpoint. Keep an outer integral for errors the inner loop cannot see, such as a target whose velocity you cannot measure.","code":"// Observe estimates the target's velocity from its reported positions,\n// low-passed so that position noise does not reach the feedforward.\nfunc (f *Follower) Observe(p drone.Vec3, t float64) {\n\tif f.seen && t > f.lastT {\n\t\traw := p.Sub(f.last).Scale(1 / (t - f.lastT))\n\t\tf.vel = f.vel.Add(raw.Sub(f.vel).Scale(f.Alpha))\n\t}\n\tf.last, f.lastT, f.seen = p, t, true\n}\n\n// Command feeds the velocity forward; P corrects only what is left.\nfunc (f *Follower) Command(pos drone.Vec3, now float64) drone.Vec3 {\n\tahead := f.last.Add(f.vel.Scale(now - f.lastT)) // where it is now\n\terr := ahead.Sub(pos).Horizontal()\n\treturn clampLen(f.vel.Horizontal().Add(err.Scale(f.Kp)), f.MaxSpeed)\n}","language":"go","title":"Where the integrator belongs","walkthrough":"On a real vehicle the target's velocity comes from its own reports or from a camera tracker. Differencing positions amplifies their noise, so the estimate is low-passed with Alpha between 0 and 1, and the last report is extrapolated to the present so that report latency does not become lag. Whatever noise remains in the feedforward goes straight into the velocity setpoint."},{"body":"On a real vehicle the Go program sends setpoints over MAVLink (SET_POSITION_TARGET_LOCAL_NED, which carries position, velocity and acceleration fields, so feedforward travels with the position) or ROS 2 (TrajectorySetpoint), typically at 10 to 50 Hz. PX4 requires a continuous stream of at least 2 Hz before it enters offboard mode and leaves offboard mode when the stream stops for longer than COM_OF_LOSS_T, so the loop must keep sending even when nothing changes. MAVLink local frames are NED while this simulator is ENU: north is the simulator's Y, east its X, and down is minus Z. Prefer sending position setpoints and letting the tuned firmware loops do the work; write your own outer loop when the task needs it, such as following a moving target or centring over a landing pad seen by a camera.","title":"Setpoints from a companion computer"},{"body":"Use New project > Robotics and simulation > Drone flight, replace main.go with this program (keep mission.go; it is not used here) and Run. Open Output: the replay shows the wind arrow, the waypoint above the take-off point, the hold, and the three runs heading west with a timeline mark for each phase. Try Kp 1.0 and the P lag shrinks to about 3 m; raise the gusts in drone.Config, or move the position loop to 2 Hz by changing outerEvery to 25, and watch the offsets grow.","title":"Fly it in GopherForge"}],"takeaway":"Nest loops so that each controls a quantity the faster loop inside it has already made responsive, and put the integrator where the disturbance enters: the velocity loop's integral cancels steady wind, so a P position loop holds a point. To follow a moving target, feed its velocity forward; a P loop alone lags by v / Kp.","title":"Cascaded control: a position loop on top of a velocity loop","unitID":"drones-control","wrongAnswers":["No lag: the velocity loop's integral removes it","3 m behind; a faster velocity loop removes it"]},{"conceptTag":"drones.complementary-filter","designGuide":{"cautions":["A sensor bias leaves a steady error of bias times tau.","An alpha computed for one rate but applied at another changes tau."],"cost":"One state and one parameter per signal, plus a bias state when the fast sensor drifts.","family":"drones","flow":["Integrate fast signal","Blend with alpha","Correct on baro sample","Score RMSE vs truth"],"ratings":[],"strengths":["A few multiplications per step, no matrices, easy to reason about.","Real motion passes without lag; each sensor's error is cut where it is large."]},"hint":"Each second the velocity path pushes the estimate by b, and the barometer path pulls it back by the error divided by tau. Where do they balance?","id":"drones.complementary-filter","introduction":"Sensors on a drone are either fast and smooth but drifting, or absolute but noisy and slow. Integrating an inertial vertical velocity gives a clean altitude that walks away over time; the barometer never walks away but jumps by tens of centimetres from sample to sample. A complementary filter takes the high frequencies from the first and the low frequencies from the second, with one parameter, the crossover time constant. It costs a few multiplications per step and is the right first estimator to write before a Kalman filter.","nuance":"The program's tau 1 s row has a mean error of 0.12 m and tau 3 s has 0.30 m, close to 0.10 m/s times tau. Estimating the bias as a third state removes the offset.","objective":"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.","question":"A complementary filter integrates a vertical velocity with a constant bias b and corrects it with a barometer using time constant tau. What altitude error remains in steady flight?","references":["https://en.wikipedia.org/wiki/Low-pass_filter","https://en.wikipedia.org/wiki/Alpha_beta_filter","https://docs.px4.io/main/en/advanced_config/tuning_the_ecl_ekf.html"],"reviewAnswer":"A steady altitude offset of about b times tau","reviewPrompt":"Bias b, time constant tau: error?","sections":[{"body":"The filter is z = alpha * (z + v * dt) + (1 - alpha) * baro with alpha = tau / (tau + dt), where dt is the period at which the blend runs. Seen from the velocity path it is a high-pass filter, seen from the barometer a low-pass filter, both with time constant tau, and the two transfer functions add up to exactly one. A real altitude change therefore passes through without lag, while each sensor's error is suppressed where it is large: barometer noise faster than tau, velocity bias slower than tau. Two consequences follow directly. A constant velocity bias b leaves a steady altitude error of b * tau. White barometer noise of sigma passes with a standard deviation of about sigma * sqrt((1 - alpha) / (1 + alpha)).","title":"High-pass plus low-pass equals one"},{"body":"The program flies a take-off to 20 m, three waypoints at 32, 12 and 26 m and a return home. Its velocity sensor is the true climb rate plus a 0.10 m/s bias and 0.10 m/s of noise at 50 Hz, a stand-in for an inertial vertical velocity. The simulator's Telemetry().Velocity is noisy too (0.15 m/s vertically, at 5 Hz) but has no bias, and bias is what makes integration drift, so the lesson models its own sensor. Five filters with different tau run side by side on the same data: each integrates the velocity every step and blends in each new barometer sample with alpha = tau / (tau + 0.2). All estimates are scored at every barometer sample against the true altitude.","code":"package main\n\n// A complementary filter for altitude: a 50 Hz vertical-velocity signal\n// with a bias (fast, smooth, drifts when integrated) fused with the 5 Hz\n// barometer (no drift, 0.3 m of noise). Several time constants run side by\n// side on the same flight and are scored against the true altitude.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/rand/v2\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Complementary blends a prediction from velocity with a measurement.\ntype Complementary struct {\n\tTau float64 // time constant, s: below it trust the baro, above it the velocity\n\tZ   float64\n}\n\n// Predict integrates the velocity signal over one step.\nfunc (f *Complementary) Predict(vz, dt float64) { f.Z += vz * dt }\n\n// Correct blends in a barometer sample that arrives every period seconds.\nfunc (f *Complementary) Correct(baro, period float64) {\n\talpha := f.Tau / (f.Tau + period)\n\tf.Z = alpha*f.Z + (1-alpha)*baro\n}\n\ntype score struct{ sumSq, maxAbs, sum float64 }\n\nfunc (s *score) add(err float64) {\n\ts.sumSq += err * err\n\ts.sum += err\n\ts.maxAbs = math.Max(s.maxAbs, math.Abs(err))\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Seed: 3})\n\td := sim.Drone()\n\tnoise := rand.New(rand.NewPCG(3, 33))\n\tconst bias, sigma = 0.10, 0.10 // velocity sensor: m/s bias, m/s noise\n\tconst baroPeriod = 0.2\n\n\ttaus := []float64{0.1, 0.3, 1, 3, 10}\n\tfilters := make([]*Complementary, len(taus))\n\tfor i, tau := range taus {\n\t\tfilters[i] = &Complementary{Tau: tau}\n\t}\n\tdeadReckoned := 0.0\n\tscores := make([]score, len(taus)+2) // baro, dead reckoning, filters\n\tvar lastBaro float64\n\tvar samples int\n\n\testimate := func(float64) {\n\t\tst := d.State()\n\t\tvz := st.Vel.Z + bias + sigma*noise.NormFloat64()\n\t\tdt := sim.Dt()\n\t\tdeadReckoned += vz * dt\n\t\tfor _, f := range filters {\n\t\t\tf.Predict(vz, dt)\n\t\t}\n\t\ttel := d.Telemetry()\n\t\tif tel.Time > lastBaro { // a new barometer sample\n\t\t\tlastBaro = tel.Time\n\t\t\ttruth := st.Pos.Z\n\t\t\tscores[0].add(tel.BaroAlt - truth)\n\t\t\tscores[1].add(deadReckoned - truth)\n\t\t\tfor i, f := range filters {\n\t\t\t\tf.Correct(tel.BaroAlt, baroPeriod)\n\t\t\t\tscores[i+2].add(f.Z - truth)\n\t\t\t}\n\t\t\tsamples++\n\t\t}\n\t}\n\n\td.Arm()\n\td.TakeOff(20)\n\tsim.RunUntil(40, func(t float64) bool { estimate(t); return d.State().Mode == drone.Hold })\n\tfor _, wp := range []drone.Vec3{{X: 40, Z: 32}, {X: 40, Y: 40, Z: 12}, {Y: 40, Z: 26}} {\n\t\td.GoTo(wp)\n\t\tsim.RunUntil(90, func(t float64) bool { estimate(t); return d.Arrived() })\n\t}\n\td.ReturnHome()\n\tsim.RunUntil(120, func(t float64) bool { estimate(t); return d.State().Landed })\n\n\tfmt.Printf(\"%.0f s flight, %d baro samples; velocity bias %.2f m/s\\n\", sim.Time(), samples, bias)\n\tfmt.Printf(\"%-23s %8s %8s %8s\\n\", \"estimate\", \"RMSE\", \"max\", \"mean\")\n\tnames := []string{\"raw baro\", \"integrated velocity\"}\n\tfor _, tau := range taus {\n\t\talpha := tau / (tau + baroPeriod)\n\t\tnames = append(names, fmt.Sprintf(\"tau %4.1f s, alpha %.3f\", tau, alpha))\n\t}\n\tfor i, s := range scores {\n\t\tn := float64(samples)\n\t\tfmt.Printf(\"%-23s %6.2f m %6.2f m %6.2f m\\n\", names[i], math.Sqrt(s.sumSq/n), s.maxAbs, s.sum/n)\n\t}\n\tsim.Save()\n}","language":"go","title":"Five time constants on one flight","walkthrough":"The raw barometer has an RMSE of 0.31 m, close to its specified 0.3 m, with a worst sample 0.87 m off. Integrated velocity alone drifts to an RMSE of 2.93 m and a mean of 2.55 m, the 0.10 m/s bias accumulating over the 51 s flight. tau 0.1 s still passes much of the barometer noise (0.22 m); tau 1.0 s is best at 0.15 m, with a mean error of 0.12 m, close to b * tau = 0.10 m. Longer constants trade noise for bias: tau 3.0 s has a mean of 0.30 m and tau 10.0 s 0.82 m, still on its way to 1.0 m when the flight ends."},{"body":"Choose tau where the two error sources cross: shorter than the time over which the fast sensor drifts noticeably, longer than the period over which the slow sensor's noise averages out. Logged flights make this concrete: replay the log through several values, as the program does, and pick the bottom of the curve. If the bias can be estimated, tau can grow. With an accelerometer as the fast sensor, a third-order complementary filter integrates acceleration to velocity and velocity to altitude, and feeds the barometer error back into all three states, including a bias estimate, which removes the b * tau offset.","code":"// Accelerometer-driven altitude filter with a bias estimate.\n// Choosing K1 = 3/tau, K2 = 3/tau^2, K3 = 1/tau^3 puts all three\n// error poles at -1/tau.\nfunc (f *Alt3) Predict(accZ, dt float64) {\n\tf.V += (accZ - f.Bias) * dt\n\tf.Z += f.V * dt\n}\n\nfunc (f *Alt3) Correct(baro, period float64) {\n\te := baro - f.Z\n\tf.Z += f.K1 * e * period\n\tf.V += f.K2 * e * period\n\tf.Bias -= f.K3 * e * period\n}","language":"go","title":"Choosing tau, and removing the bias","walkthrough":"If the accelerometer reads high, the predicted altitude climbs above the barometer, e turns negative, and the bias estimate grows until the prediction stops running away. The error dynamics have the characteristic polynomial s^3 + K1 s^2 + K2 s + K3, so the suggested gains make it critically damped with one time constant."},{"body":"Small flight controllers have long used complementary filters for attitude (gyro plus accelerometer) and altitude; PX4 and ArduPilot now run extended Kalman filters (EKF2, EKF3), but the complementary filter remains the tool of choice in companion and ground code: smoothing a rangefinder with inertial velocity, blending visual odometry with GPS for display, cleaning telemetry plots. Typical bugs: alpha computed for one rate and applied at another (computed for 50 Hz but applied per 5 Hz sample makes tau ten times longer); blending a held, stale sample at every fast step; starting the state at zero instead of the first absolute sample; mixing a sea-level altitude with a take-off-relative one; and forgetting that propeller wash and ground effect bias a barometer near the ground.","title":"Where complementary filters live, and how they fail"},{"body":"Start from New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go may stay) and Run. The console prints the RMSE table; Output replays the flight with its climbs and descents in the altitude strip. Change the bias, the noise or the list of taus at the top of main and watch the best time constant move: with a smaller bias the optimum shifts to longer tau, with more barometer noise as well.","title":"Fly it in GopherForge"}],"takeaway":"A complementary filter trusts the fast sensor above 1/tau and the absolute sensor below it, so real motion passes without lag while barometer noise and velocity drift are both suppressed. Pick tau between the two error sources, and remember that a velocity bias b costs a steady error of b times tau.","title":"Complementary filter: fusing a fast drifting signal with a slow noisy one","unitID":"drones-control","wrongAnswers":["None: the barometer correction removes any bias","An error that grows without limit, as in dead reckoning"]},{"conceptTag":"drones.kalman-filter","designGuide":{"cautions":["An overconfident filter gates out good data and diverges.","Q is a modelling knob; a wrong model cannot be tuned away entirely."],"cost":"A small state vector, a covariance update per step, and log-driven tuning of Q, R and the gates.","family":"drones","flow":["Predict x and P each step","Gate the innovation","Update with K = P/(P+R)","Reset after many rejects"],"ratings":[],"strengths":["Weights sensors by their noise and adapts the gain as it converges.","Estimates unmeasured states such as climb rate, with an uncertainty."]},"hint":"Write K = P00 / (P00 + R). Which quantity shrinks as the filter converges, and which one comes from the sensor?","id":"drones.kalman-filter","introduction":"A complementary filter has a fixed blend. A Kalman filter computes the blend at every step from its own uncertainty: right after start-up it trusts the measurements almost completely, once it has converged it leans on its model, and it weighs a 1.2 m GPS altitude against a 0.3 m barometer by their variances. It also estimates states it does not measure, such as the climb rate from altitude samples alone, fuses a direct measurement of them when one exists, and says how surprising each sample is, which is the basis for rejecting glitches. PX4's EKF2 and ArduPilot's EKF3 run the same predict-update cycle with many more states.","nuance":"With constant Q, R and sample rate the gain converges to a fixed value, 0.384 for altitude here, and the filter behaves like an alpha-beta filter. The covariance still drives gates and resets.","objective":"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.","question":"In a 1-D altitude Kalman filter, what determines the gain, the fraction of each barometer innovation applied to the estimate?","references":["https://en.wikipedia.org/wiki/Kalman_filter","https://docs.px4.io/main/en/advanced_config/tuning_the_ecl_ekf.html","https://ardupilot.org/copter/docs/common-apm-navigation-extended-kalman-filter-overview.html"],"reviewAnswer":"Predicted variance versus measurement variance","reviewPrompt":"What sets the Kalman gain?","sections":[{"body":"The state is x = [altitude, climb rate] and P is its 2x2 covariance. Predict assumes constant velocity: altitude += climb rate * dt, and P = F P F^T + Q, where Q models an unknown acceleration with variance q as q * [[dt^4/4, dt^3/2], [dt^3/2, dt^2]]. Update with an altitude sensor (H = [1 0]) forms the innovation y = z - altitude and its predicted variance S = P00 + R, computes the gain K = [P00 / S, P10 / S], adds K * y to the state and shrinks P to (I - K H) P. R is the sensor's noise variance: 1.2^2 m^2 for the simulator's GPS altitude and 0.3^2 for its barometer. A sensor that measures the climb rate uses H = [0 1]: the same equations then pick row and column 1 instead of 0. Sensors arriving together are fused one after the other. With 2x2 matrices, float64 and plain arrays are enough; larger filters use the Joseph form of the covariance update to keep P symmetric and positive.","title":"State, covariance, predict, update"},{"body":"The program predicts at 50 Hz and updates at 5 Hz with the GPS altitude and then the barometer, over a flight with climbs to 35 m and descents to 20 m. Three barometer samples are corrupted on purpose (+8 m twice, -6 m once), as a pressure spike or a sensor glitch would. Five filters start from P = diag(100, 25): Q 0.5, Q 10 and Q 300 with a 4-sigma innovation gate, Q 10 without a gate, and a gated Q 10 filter that also fuses the telemetry's climb rate (0.15 m/s of noise) with H = [0 1]. A gated filter that rejects five samples in a row from one sensor resets that state to the sensor. The program prints the convergence of the Q 10 filter's barometer gains and an error table against the true state.","code":"package main\n\n// A 1-D constant-velocity Kalman filter for altitude and climb rate, fed at\n// 5 Hz by the simulator's GPS altitude (about 1.2 m of slowly wandering\n// error) and barometer (0.3 m, three glitches injected); one filter also\n// fuses the telemetry's climb rate (0.15 m/s of noise).\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Sensors, and the state each one measures: H = [1 0] for altitude,\n// H = [0 1] for climb rate.\nconst (\n\tGPS = iota\n\tBaro\n\tVel\n)\n\nvar measures = [3]int{GPS: 0, Baro: 0, Vel: 1}\n\n// Kalman estimates X = [altitude m, climb rate m/s] with covariance P.\ntype Kalman struct {\n\tX         [2]float64\n\tP         [2][2]float64\n\tQ         float64    // variance of unmodelled acceleration, (m/s^2)^2\n\tR         [3]float64 // measurement variance per sensor\n\tGate      float64    // reject innovations beyond Gate standard deviations; 0 = off\n\tMaxMisses int        // consecutive rejections before a reset\n\n\tmisses           [3]int\n\tRejected, Resets int\n}\n\nfunc NewKalman(q, gate float64) *Kalman {\n\treturn &Kalman{\n\t\tP:         [2][2]float64{{100, 0}, {0, 25}}, // we know nothing yet\n\t\tQ:         q,\n\t\tR:         [3]float64{GPS: 1.2 * 1.2, Baro: 0.3 * 0.3, Vel: 0.15 * 0.15},\n\t\tGate:      gate,\n\t\tMaxMisses: 5,\n\t}\n}\n\n// Predict moves the state forward by dt assuming constant velocity, and\n// grows the covariance by the acceleration the model ignores.\nfunc (k *Kalman) Predict(dt float64) {\n\tk.X[0] += k.X[1] * dt\n\tp := k.P\n\tp00 := p[0][0] + dt*(p[0][1]+p[1][0]) + dt*dt*p[1][1]\n\tp01 := p[0][1] + dt*p[1][1]\n\tp10 := p[1][0] + dt*p[1][1]\n\tdt2 := dt * dt\n\tk.P = [2][2]float64{\n\t\t{p00 + k.Q*dt2*dt2/4, p01 + k.Q*dt2*dt/2},\n\t\t{p10 + k.Q*dt2*dt/2, p[1][1] + k.Q*dt2},\n\t}\n}\n\n// Update fuses one measurement of state i = measures[sensor]. It returns\n// the gains applied to altitude and climb rate (zero when rejected).\nfunc (k *Kalman) Update(sensor int, z float64) (k0, k1 float64) {\n\ti, r := measures[sensor], k.R[sensor]\n\ty := z - k.X[i]    // innovation\n\ts := k.P[i][i] + r // its predicted variance\n\tif k.Gate > 0 && y*y > k.Gate*k.Gate*s {\n\t\tk.misses[sensor]++\n\t\tif k.misses[sensor] < k.MaxMisses {\n\t\t\tk.Rejected++\n\t\t\treturn 0, 0\n\t\t}\n\t\t// The sensor has disagreed for a second: we are probably the ones\n\t\t// who are wrong. Take its value and forget our confidence.\n\t\tk.Resets++\n\t\tk.misses[sensor] = 0\n\t\tk.X[i] = z\n\t\tk.P[0][1], k.P[1][0] = 0, 0\n\t\tk.P[i][i] = r\n\t\tk.P[1-i][1-i] += 4\n\t\treturn 0, 0\n\t}\n\tk.misses[sensor] = 0\n\tk0, k1 = k.P[0][i]/s, k.P[1][i]/s\n\tk.X[0] += k0 * y\n\tk.X[1] += k1 * y\n\tp := k.P // P = (I - K H) P, where H picks row i\n\tk.P = [2][2]float64{\n\t\t{p[0][0] - k0*p[i][0], p[0][1] - k0*p[i][1]},\n\t\t{p[1][0] - k1*p[i][0], p[1][1] - k1*p[i][1]},\n\t}\n\treturn k0, k1\n}\n\ntype rms struct{ sum float64 }\n\nfunc (r *rms) add(e float64)   { r.sum += e * e }\nfunc (r rms) of(n int) float64 { return math.Sqrt(r.sum / float64(n)) }\n\n// glitch adds pressure spikes to a few barometer samples.\nfunc glitch(sample int) float64 {\n\tswitch sample {\n\tcase 120, 121:\n\t\treturn 8\n\tcase 200:\n\t\treturn -6\n\t}\n\treturn 0\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Seed: 4})\n\td := sim.Drone()\n\n\tnames := []string{\"Q 0.5, gate 4\", \"Q 10, gate 4\", \"Q 300, gate 4\", \"Q 10, no gate\", \"Q 10, gate 4, +vel\"}\n\tfilters := []*Kalman{NewKalman(0.5, 4), NewKalman(10, 4), NewKalman(300, 4), NewKalman(10, 0), NewKalman(10, 4)}\n\tfuseVel := []bool{false, false, false, false, true}\n\taltErr := make([]rms, len(filters))\n\tvelErr := make([]rms, len(filters))\n\tvar gpsErr, baroErr, diffErr, velErr0 rms\n\tvar lastTel, prevBaro float64\n\tvar samples int\n\tvar gains [][3]float64\n\n\testimate := func(float64) {\n\t\tfor _, k := range filters {\n\t\t\tk.Predict(sim.Dt())\n\t\t}\n\t\ttel := d.Telemetry()\n\t\tif tel.Time <= lastTel {\n\t\t\treturn\n\t\t}\n\t\tlastTel = tel.Time\n\t\tsamples++\n\t\tbaro := tel.BaroAlt + glitch(samples)\n\t\tst := d.State()\n\t\tfor i, k := range filters {\n\t\t\tk.Update(GPS, tel.GPS.Z)\n\t\t\tkz, kv := k.Update(Baro, baro)\n\t\t\tif fuseVel[i] {\n\t\t\t\tk.Update(Vel, tel.Velocity.Z)\n\t\t\t}\n\t\t\tif i == 1 && (samples <= 3 || samples == 10 || samples == 50) {\n\t\t\t\tgains = append(gains, [3]float64{float64(samples), kz, kv})\n\t\t\t}\n\t\t\taltErr[i].add(k.X[0] - st.Pos.Z)\n\t\t\tvelErr[i].add(k.X[1] - st.Vel.Z)\n\t\t}\n\t\tgpsErr.add(tel.GPS.Z - st.Pos.Z)\n\t\tbaroErr.add(baro - st.Pos.Z)\n\t\tvelErr0.add(tel.Velocity.Z - st.Vel.Z)\n\t\tif samples > 1 {\n\t\t\tdiffErr.add((baro-prevBaro)/0.2 - st.Vel.Z)\n\t\t}\n\t\tprevBaro = baro\n\t}\n\n\td.Arm()\n\td.TakeOff(15)\n\tsim.RunUntil(40, func(t float64) bool { estimate(t); return d.State().Mode == drone.Hold })\n\tfor _, wp := range []drone.Vec3{{X: 30, Z: 35}, {X: 30, Y: 30, Z: 20}, {Y: 30, Z: 28}} {\n\t\td.GoTo(wp)\n\t\tsim.RunUntil(90, func(t float64) bool { estimate(t); return d.Arrived() })\n\t\tsim.Run(5, estimate)\n\t}\n\td.ReturnHome()\n\tsim.RunUntil(120, func(t float64) bool { estimate(t); return d.State().Landed })\n\n\tfmt.Println(\"barometer gains of the Q 10 filter:\")\n\tfor _, g := range gains {\n\t\tfmt.Printf(\"  update %2.0f: altitude %.3f, climb rate %.3f /s\\n\", g[0], g[1], g[2])\n\t}\n\tfmt.Printf(\"%d samples at 5 Hz over %.0f s, 3 baro glitches injected\\n\", samples, sim.Time())\n\tfmt.Printf(\"%-25s %8s %10s %8s %6s\\n\", \"estimate\", \"alt RMSE\", \"rate RMSE\", \"rejected\", \"resets\")\n\tfmt.Printf(\"%-25s %6.2f m %10s\\n\", \"raw GPS Z\", gpsErr.of(samples), \"-\")\n\tfmt.Printf(\"%-25s %6.2f m %6.2f m/s\\n\", \"raw baro\", baroErr.of(samples), diffErr.of(samples-1))\n\tfmt.Printf(\"%-25s %8s %6.2f m/s\\n\", \"raw telemetry vel Z\", \"-\", velErr0.of(samples))\n\tfor i, k := range filters {\n\t\tfmt.Printf(\"%-25s %6.2f m %6.2f m/s %8d %6d\\n\", \"Kalman \"+names[i], altErr[i].of(samples), velErr[i].of(samples), k.Rejected, k.Resets)\n\t}\n\tsim.Save()\n}","language":"go","title":"Five filters on one flight","walkthrough":"The first barometer update has an altitude gain of 0.940, because the GPS update just before it already cut the variance from 100 m^2; the second has a climb-rate gain of 4.017 /s as the filter learns velocity from the first difference. By update 10 the gains are 0.395 and 0.504, by update 50 0.384 and 0.498: converged. Raw GPS altitude has an RMSE of 1.14 m, raw barometer 0.77 m including the glitches, and its differences give a 4.49 m/s climb rate; the telemetry's climb rate is off by 0.16 m/s. Q 10 with the gate reaches 0.22 m and 0.49 m/s, rejecting exactly the 3 glitches. Q 0.5 lags every manoeuvre: 20 rejections, 3 resets, 0.54 m. Q 300 follows the noise (0.67 m/s), and without a gate the glitches pull Q 10 to 0.51 m. Fusing the climb rate brings altitude to 0.13 m with a rate error of 0.17 m/s, about the measurement's own; its 5 rejections are the 3 glitches and two climb-rate samples at the start of the descent from 35 m, where the drone accelerates harder than Q allows."},{"body":"R comes from the sensor: log it at rest and measure the variance, or start from the datasheet. Q is the modelling error, everything the constant-velocity model ignores. Here the autopilot accelerates at up to 8 m/s^2 when it starts a climb, so q of about 10 (m/s^2)^2 fits, and the table shows both failure directions. Too small a Q makes the filter overconfident: it lags manoeuvres, its innovations grow, and with a gate it starts rejecting good data. Too large a Q makes it follow every measurement, and the climb rate becomes noisy. A consistency check helps: innovations should average zero, and y^2 / S should average about 1. Better than inflating Q is a better model: feed the accelerometer into the prediction as EKF2 does with the IMU, so Q only covers accelerometer noise and bias. R also assumes white noise, and the simulator's GPS error, like real GNSS, wanders slowly (a Gauss-Markov process with a 20 s time constant), so a filter that treats it as white trusts the GPS too much. The barometer dominates here; when GPS must carry the altitude, add its slowly varying error as a state, as full navigation filters do.","title":"Tuning Q and R"},{"body":"Before an update, y^2 / S tells how surprising the sample is in units of its expected variance. With Gaussian noise a 3-sigma gate still rejects 0.27% of good samples; models are never perfect, so practical gates are often 3 to 5 sigma, and PX4's EKF2 exposes them as parameters such as EKF2_BARO_GATE. The trap is a filter that has drifted: then the truth looks like an outlier, every sample is rejected and the estimate never recovers. Count consecutive rejections per sensor and reset to the sensor after a timeout, as production estimators do, and log every rejection and reset.","code":"i, r := measures[sensor], k.R[sensor]\ny := z - k.X[i]    // innovation\ns := k.P[i][i] + r // its predicted variance\nif k.Gate > 0 && y*y > k.Gate*k.Gate*s {\n\tk.misses[sensor]++\n\tif k.misses[sensor] < k.MaxMisses {\n\t\tk.Rejected++\n\t\treturn 0, 0\n\t}\n\tk.Resets++ // the sensor kept disagreeing: trust it\n\tk.misses[sensor] = 0\n\tk.X[i] = z\n\tk.P[0][1], k.P[1][0] = 0, 0\n\tk.P[i][i] = r\n\tk.P[1-i][1-i] += 4\n\treturn 0, 0\n}","language":"go","title":"Innovation gates and their trap","walkthrough":"The test compares y^2 with Gate^2 * S, so Gate is in standard deviations and no square root is needed. After MaxMisses rejections in a row the filter assumes it is the one that is wrong: it takes the measurement as the value of the state that sensor measures, with the sensor's variance, drops the correlation and widens the other state's variance so the next samples can correct it."},{"body":"Create New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay) and Run. The console shows the gains and the error table; Output replays the flight, whose climbs and descents are what the constant-velocity model has to follow. Edit the glitch function, change Q or the gate in the NewKalman calls, set the gate to 3, or fuse the climb rate in every filter, and watch the errors, rejections and resets change.","title":"Fly it in GopherForge"}],"takeaway":"A Kalman filter computes its blend from the covariance: high gain while uncertain, a steady gain once converged, weights set by each sensor's variance. Tune R from sensor noise and Q from what the model ignores, gate innovations in standard deviations, and reset after repeated rejections so a gate cannot lock out the truth.","title":"A Kalman filter for altitude and climb rate","unitID":"drones-control","wrongAnswers":["A fixed alpha chosen once from the sample rate","The innovation itself: large surprises get a larger fraction"]},{"conceptTag":"drones.loop-timing","designGuide":{"cautions":["Go on Linux cannot promise hard deadlines; fast loops stay in firmware.","The first tick after a stall is late; dt must come from the clock."],"cost":"A ticker, a measured dt, preallocated buffers and a test that pins the allocation count at zero.","family":"drones","flow":["NewTicker, defer Stop","dt from monotonic clock","Zero-alloc loop body","Count and log overruns"],"ratings":[],"strengths":["A ticker keeps a fixed grid and never bursts after a stall.","AllocsPerRun turns \"no allocations\" into a test you can keep."]},"hint":"The time package says a ticker adjusts the interval or drops ticks to make up for slow receivers. How many ticks can be waiting at once?","id":"drones.loop-timing","introduction":"A control loop assumes its dt. When an iteration starts late, the integral and derivative terms are computed with the wrong time step, and a burst of catch-up iterations is worse than a skipped one. Go is a good language for the 10 to 50 Hz supervisory loops of a companion computer or ground station and the wrong one for the kilohertz rate loop inside a flight controller. This lesson runs three loop styles on a virtual clock, so the results are the same on every run, then counts the heap allocations of two versions of a loop body.","nuance":"Since Go 1.23 timer channels are unbuffered and Stop or Reset discard stale ticks, but a late receiver still gets one tick at once. Measure dt with the monotonic clock instead of assuming the period.","objective":"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.","question":"A 50 Hz loop reads from a time.Ticker and one iteration blocks for 90 ms. What happens to the ticks that fell due during the stall?","references":["https://pkg.go.dev/time","https://go.dev/doc/gc-guide","https://pkg.go.dev/testing","https://go.dev/doc/go1.23"],"reviewAnswer":"One late tick waits; the rest are dropped","reviewPrompt":"Ticker vs slow receiver?","sections":[{"body":"A Ticker delivers ticks on a fixed grid, so the work inside the loop does not stretch the period, and the time package documents that it adjusts the interval or drops ticks to make up for slow receivers: at most one tick waits, the others are lost, and the grid keeps its phase. Since Go 1.23 timer channels are unbuffered and Stop or Reset guarantee that no stale tick is received afterwards, but a receiver that comes back late still gets one tick at once. Two common alternatives behave worse: time.Sleep(period) after the work makes the period work plus period, and a deadline loop that adds the period and sleeps until the deadline without ever skipping runs late iterations back to back after a stall. Whatever the loop, measure dt instead of assuming it.","code":"func run(ctx context.Context, period time.Duration, step func(dt time.Duration)) (overruns int, err error) {\n\tt := time.NewTicker(period)\n\tdefer t.Stop()\n\tlast := time.Now()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn overruns, ctx.Err()\n\t\tcase <-t.C:\n\t\t\tnow := time.Now()\n\t\t\tdt := now.Sub(last) // monotonic: immune to clock changes\n\t\t\tlast = now\n\t\t\tif dt > 2*period {\n\t\t\t\toverruns++\n\t\t\t\tdt = 2 * period // do not integrate a huge step\n\t\t\t}\n\t\t\tstep(dt)\n\t\t}\n\t}\n}","language":"go","title":"What time.Ticker promises","walkthrough":"time.Now carries a monotonic clock reading and Sub uses it, so an NTP correction of the wall clock cannot produce a negative or huge dt. Overruns are counted for the logs, and dt is limited so that one stall does not turn into one giant integration step in the controller."},{"body":"Sleeping in a lesson program would make its output depend on the machine, so the program models time with integer durations. Each loop body takes 8 to 12 ms from a seeded generator, and two stalls are injected: a 90 ms blocking log write at 0.6 s and 30 ms of CPU contention at 1.3 s. The sleep loop, the ticker and the catch-up deadline loop each run for 2 s at a 20 ms period. The table counts runs, 20 ms slots in which no iteration started, dropped ticks, the smallest and largest gap between starts, the worst lag behind the tick an iteration serves and the number of stale runs, those more than one period late. Then testing.AllocsPerRun measures two versions of a loop body.","code":"package main\n\n// Loop timing on a virtual clock: three ways to run a 50 Hz control loop\n// meet the same jittery workload and two stalls. Then testing.AllocsPerRun\n// counts heap allocations of two versions of the loop body.\n\nimport (\n\t\"fmt\"\n\t\"math/rand/v2\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\tperiod  = 20 * time.Millisecond // 50 Hz\n\thorizon = 2 * time.Second\n)\n\ntype stall struct {\n\tat, dur time.Duration\n\twhy     string\n}\n\nvar stalls = []stall{\n\t{600 * time.Millisecond, 90 * time.Millisecond, \"blocking log write\"},\n\t{1300 * time.Millisecond, 30 * time.Millisecond, \"CPU contention\"},\n}\n\n// worker decides how long each loop body takes: 8-12 ms of work plus any\n// stall due at the moment it starts. Every loop style gets the same seed.\ntype worker struct {\n\trng  *rand.Rand\n\tnext int\n}\n\nfunc newWorker() *worker { return &worker{rng: rand.New(rand.NewPCG(5, 50))} }\n\nfunc (w *worker) run(start time.Duration) time.Duration {\n\td := 8*time.Millisecond + time.Duration(w.rng.IntN(4000))*time.Microsecond\n\tif w.next < len(stalls) && start >= stalls[w.next].at {\n\t\td += stalls[w.next].dur\n\t\tw.next++\n\t}\n\treturn d\n}\n\n// iteration records when a loop body started and the tick it served.\ntype iteration struct{ start, sched time.Duration }\n\n// sleepLoop: work, then time.Sleep(period). The period becomes work+period.\nfunc sleepLoop() []iteration {\n\tw := newWorker()\n\tvar runs []iteration\n\tfor now := time.Duration(0); now < horizon; {\n\t\truns = append(runs, iteration{now, -1})\n\t\tnow += w.run(now)\n\t\tnow += period\n\t}\n\treturn runs\n}\n\n// tickerLoop models time.Ticker: ticks on a fixed grid, at most one tick\n// waits for a slow receiver, later ones are dropped.\nfunc tickerLoop() (runs []iteration, dropped int) {\n\tw := newWorker()\n\tvar now time.Duration\n\tfire := period\n\twaiting, value := false, time.Duration(0)\n\tfor {\n\t\tfor ; fire <= now; fire += period { // ticks that fired while we worked\n\t\t\tif waiting {\n\t\t\t\tdropped++\n\t\t\t} else {\n\t\t\t\twaiting, value = true, fire\n\t\t\t}\n\t\t}\n\t\tif !waiting { // block in <-ticker.C until the next tick\n\t\t\tnow, waiting, value = fire, true, fire\n\t\t\tfire += period\n\t\t}\n\t\tif now >= horizon {\n\t\t\treturn runs, dropped\n\t\t}\n\t\twaiting = false\n\t\truns = append(runs, iteration{now, value})\n\t\tnow += w.run(now)\n\t}\n}\n\n// catchUpLoop sleeps until next deadline, then deadline += period. It never\n// skips, so after a stall it runs late iterations back to back.\nfunc catchUpLoop() []iteration {\n\tw := newWorker()\n\tvar runs []iteration\n\tvar now time.Duration\n\tfor next := period; ; next += period {\n\t\tif now < next {\n\t\t\tnow = next\n\t\t}\n\t\tif now >= horizon {\n\t\t\treturn runs\n\t\t}\n\t\truns = append(runs, iteration{now, next})\n\t\tnow += w.run(now)\n\t}\n}\n\nfunc report(name string, runs []iteration, dropped string) {\n\thit := make([]bool, horizon/period)\n\tminGap, maxGap := time.Hour, time.Duration(0)\n\tstale, lag := 0, time.Duration(-1)\n\tfor i, r := range runs {\n\t\thit[r.start/period] = true\n\t\tif i > 0 {\n\t\t\tgap := r.start - runs[i-1].start\n\t\t\tminGap, maxGap = min(minGap, gap), max(maxGap, gap)\n\t\t}\n\t\tif r.sched >= 0 {\n\t\t\tlag = max(lag, r.start-r.sched)\n\t\t\tif r.start-r.sched > period {\n\t\t\t\tstale++\n\t\t\t}\n\t\t}\n\t}\n\tempty := 0\n\tfor _, h := range hit[1:] {\n\t\tif !h {\n\t\t\tempty++\n\t\t}\n\t}\n\tworst, staleRuns := \"-\", \"-\"\n\tif lag >= 0 {\n\t\tworst, staleRuns = ms(lag), strconv.Itoa(stale)\n\t}\n\tfmt.Printf(\"%-9s %4d %6d %8s %8s %8s %8s %6s\\n\", name, len(runs), empty, dropped, ms(minGap), ms(maxGap), worst, staleRuns)\n}\n\nfunc ms(d time.Duration) string { return strconv.FormatFloat(float64(d)/1e6, 'f', 1, 64) + \" ms\" }\n\n// ---- allocations in the loop body\n\ntype Command struct{ Vx, Vy, Vz, Yaw float64 }\n\ntype loopState struct {\n\twindow []float64 // last N altitude samples\n\thead   int\n\tcmd    *Command\n\tlast   Command\n\tnote   string\n\tbuf    []byte\n}\n\n// bodyAllocating copies the window, allocates a new command and formats a note\n// on every tick.\nfunc bodyAllocating(s *loopState, alt float64) {\n\tw := make([]float64, len(s.window))\n\tcopy(w, s.window[1:])\n\tw[len(w)-1] = alt\n\ts.window = w\n\ts.cmd = &Command{Vz: 0.8 * (10 - mean(w))}\n\ts.note = strconv.FormatFloat(s.cmd.Vz, 'f', 2, 64)\n}\n\n// bodyReusing writes into a ring buffer, stores the command by value and\n// appends the note into a buffer that keeps its capacity.\nfunc bodyReusing(s *loopState, alt float64) {\n\ts.window[s.head] = alt\n\ts.head = (s.head + 1) % len(s.window)\n\ts.last = Command{Vz: 0.8 * (10 - mean(s.window))}\n\ts.buf = strconv.AppendFloat(s.buf[:0], s.last.Vz, 'f', 2, 64)\n}\n\nfunc mean(xs []float64) float64 {\n\tsum := 0.0\n\tfor _, x := range xs {\n\t\tsum += x\n\t}\n\treturn sum / float64(len(xs))\n}\n\nfunc main() {\n\tfmt.Printf(\"virtual clock: %v period (50 Hz) for %v, loop body 8-12 ms\\n\", period, horizon)\n\tfor _, s := range stalls {\n\t\tfmt.Printf(\"stall: %v %s at %v\\n\", s.dur, s.why, s.at)\n\t}\n\tfmt.Printf(\"%-9s %4s %6s %8s %8s %8s %8s %6s\\n\", \"loop\", \"runs\", \"empty\", \"dropped\", \"min gap\", \"max gap\", \"max lag\", \"stale\")\n\treport(\"sleep\", sleepLoop(), \"-\")\n\truns, dropped := tickerLoop()\n\treport(\"ticker\", runs, strconv.Itoa(dropped))\n\treport(\"catch-up\", catchUpLoop(), \"0\")\n\n\ts := &loopState{window: make([]float64, 25), buf: make([]byte, 0, 32)}\n\talt := 9.5\n\ta := testing.AllocsPerRun(1000, func() { bodyAllocating(s, alt) })\n\tb := testing.AllocsPerRun(1000, func() { bodyReusing(s, alt) })\n\tfmt.Printf(\"allocations per tick: allocating body %.0f, reusing body %.0f\\n\", a, b)\n\tfmt.Printf(\"at 50 Hz that is %.0f vs %.0f heap objects a minute\\n\", a*50*60, b*50*60)\n}","language":"go","title":"Three loops on a virtual clock","walkthrough":"The sleep loop manages only 63 runs instead of 99, leaving 37 empty slots: its period became the body plus 20 ms (the smallest gap is 28.1 ms). The ticker makes 94 runs and drops 5 ticks; its smallest gap is 18.3 ms, so it never bursts, and only 2 runs are stale, the late tick after each stall, the worse one 80.4 ms late. The catch-up loop makes 99 runs and drops nothing, but its smallest gap is 8.1 ms: after the stall it runs 6 stale iterations back to back on old data. The allocating loop body makes 3 heap allocations per tick, the reusing one 0, which at 50 Hz is 9000 objects a minute against none."},{"body":"Go's collector runs concurrently with the program. Its stop-the-world phases are short, usually well under a millisecond, but while a cycle runs the background marker uses about a quarter of GOMAXPROCS, and a goroutine that allocates may be drafted into mark assist. A loop body that does not allocate triggers fewer cycles and is not drafted. The allocating body above makes three objects: a slice made with a non-constant length, a *Command stored in a heap object, and the string from strconv.FormatFloat. The reusing body writes into a ring buffer, stores the command by value and appends into a byte slice that keeps its capacity. Find escapes with go build -gcflags=-m, pin the count with testing.AllocsPerRun in a test, and on small boards set GOMEMLIMIT (or debug.SetMemoryLimit) so the runtime collects before the operating system kills the process; GOGC trades memory for collection frequency.","title":"Garbage collection and the loop body"},{"body":"Rate and attitude loops run at hundreds of hertz to kilohertz with deadlines in microseconds, on real-time operating systems (NuttX under PX4, ChibiOS under ArduPilot on most boards) with fixed priorities and the IMU's interrupts driving them. A Go process on Linux shares the CPU with the kernel, other processes and the USB and Wi-Fi drivers; a few milliseconds of jitter are normal and occasional spikes of tens of milliseconds happen. That is acceptable for 10 to 50 Hz setpoints when the autopilot has its own timeout and failsafe, which PX4's offboard mode does. Log dt for every tick, keep a histogram, alert on overruns, and design the outer loop so that a missed tick costs accuracy, not safety.","title":"What stays in firmware"},{"body":"This program does not use the simulator: run it in any Go project, or create New project > Robotics and simulation > Drone flight and replace main.go with it (mission.go can stay), then Run and read the console. To connect it to a flight, call bodyReusing from the control function of sim.Run with d.State().Pos.Z: the simulator calls that function at exactly 50 Hz of simulated time, the ideal loop this lesson approximates, and Output replays the flight.","title":"Fly it in GopherForge"}],"takeaway":"Use time.Ticker for fixed-rate loops: its grid does not drift, and after a stall it delivers one late tick and drops the rest instead of bursting. Compute dt from the monotonic clock, keep the loop body free of allocations and prove it with AllocsPerRun, set GOMEMLIMIT on small boards, and leave kilohertz loops to firmware.","title":"Fixed-rate loops in Go: tickers, jitter, GC and allocations","unitID":"drones-control","wrongAnswers":["All of them are queued and delivered back to back","The ticker restarts its grid from the end of the stall"]},{"conceptTag":"drones.motor-mixing","designGuide":{"cautions":["Clipping per motor couples axes and can flip the vehicle.","Raising thrust at zero throttle (Airmode) can make it climb."],"cost":"A small matrix per airframe, a desaturation routine and ground tests with the propellers removed.","family":"drones","flow":["Roll/pitch spread fits?","Shrink yaw to fit","Shift thrust into 0..1","Check achieved torques"],"ratings":[],"strengths":["Explicit priorities keep the vehicle upright under saturation.","Inverting the mix shows what the motors actually produce."]},"hint":"Ask what happens to the vehicle if each one is lost: a slow heading drift, a small change of height, or a tilt it cannot correct.","id":"drones.motor-mixing","introduction":"Below the rate controller sits the mixer, which PX4 calls control allocation. It knows where each rotor is and which way it spins, and turns four numbers, thrust and three torques, into four motor commands. That is a matrix multiplication until a motor reaches 0 or 1. Then something has to give, and what gives decides whether the vehicle keeps its attitude or rolls over. This lesson writes the mixer, the naive clip and a desaturation with explicit priorities.","nuance":"Clipping each motor separately is the worst option: in the program's last case it cut roll to +0.20 and added a pitch of +0.10 nobody asked for, coupling the axes.","objective":"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.","question":"A quad X mixer cannot fit a command into 0..1 on every motor. In what order should a desaturating mixer give things up?","references":["https://docs.px4.io/main/en/concept/control_allocation.html","https://docs.px4.io/main/en/config_mc/pid_tuning_guide_multicopter.html","https://github.com/PX4/PX4-Autopilot/blob/main/ROMFS/px4fmu_common/init.d/airframes/4001_quad_x","https://ardupilot.org/copter/docs/connect-escs-and-motors.html"],"reviewAnswer":"Yaw, then collective thrust; keep roll and pitch","reviewPrompt":"Mixer saturates: what goes first?","sections":[{"body":"In PX4's Quadrotor X, motor 1 is front right and spins counter-clockwise, motor 2 rear left counter-clockwise, motor 3 front left clockwise and motor 4 rear right clockwise; ArduPilot's Quad X uses the same order. Using the FRD body frame, a positive roll lowers the right side, so it needs more thrust on the left motors 2 and 3; a positive pitch raises the nose, so it needs more thrust on the front motors 1 and 3. Yaw comes from rotor drag torque: a counter-clockwise propeller twists the body clockwise, so yawing right (clockwise seen from above) speeds up motors 1 and 2 and slows 3 and 4. Each output is thrust plus signed shares of the three torques. PX4 builds that matrix from rotor positions and moment coefficients (CA_ROTORn_PX, CA_ROTORn_PY, and CA_ROTORn_KM, positive for counter-clockwise) and uses its pseudo-inverse. The default KM of 0.05 shows why yaw authority is weak: drag torque is small compared with thrust.","title":"Geometry and spin directions"},{"body":"The program prints the motor table, then mixes seven commands. Thrust is 0..1 and the torques are normalised so that a roll command of 0.1 moves the motors by 0.1. Commands that fit go straight through. For saturated ones the program prints two results: every motor clipped to 0..1 separately, and the desaturated mix. Each line ends with the command the four outputs actually produce, computed by inverting the mix, which is how you see what saturation cost.","code":"package main\n\n// Quad X motor mixing: collective thrust and roll, pitch and yaw torque\n// commands become four motor outputs in 0..1. Saturated cases are shown\n// clipped naively and desaturated with attitude before yaw before thrust.\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// Command is what the attitude and rate controllers ask for. Thrust is\n// 0..1; roll, pitch and yaw are normalised torques (FRD body frame:\n// positive roll = right side down, pitch = nose up, yaw = nose right).\ntype Command struct{ Thrust, Roll, Pitch, Yaw float64 }\n\n// Motor is one rotor's share of each torque.\ntype Motor struct {\n\tName             string\n\tRoll, Pitch, Yaw float64\n}\n\n// QuadX uses PX4's numbering for the Quadrotor X airframe.\nvar QuadX = [4]Motor{\n\t{\"1 front right, CCW\", -1, +1, +1},\n\t{\"2 rear left, CCW\", +1, -1, +1},\n\t{\"3 front left, CW\", +1, +1, -1},\n\t{\"4 rear right, CW\", -1, -1, -1},\n}\n\ntype Outputs [4]float64\n\nfunc torques(c Command, yawScale float64) Outputs {\n\tvar a Outputs\n\tfor i, m := range QuadX {\n\t\ta[i] = c.Roll*m.Roll + c.Pitch*m.Pitch + c.Yaw*yawScale*m.Yaw\n\t}\n\treturn a\n}\n\nfunc spread(a Outputs) (lo, hi float64) {\n\tlo, hi = a[0], a[0]\n\tfor _, v := range a[1:] {\n\t\tlo, hi = math.Min(lo, v), math.Max(hi, v)\n\t}\n\treturn lo, hi\n}\n\n// Clipped adds thrust and clamps each motor: the simple, wrong way.\nfunc Clipped(c Command) Outputs {\n\ta := torques(c, 1)\n\tfor i := range a {\n\t\ta[i] = clamp(c.Thrust+a[i], 0, 1)\n\t}\n\treturn a\n}\n\n// Desaturated keeps roll and pitch if at all possible, gives up yaw next\n// and moves collective thrust last.\nfunc Desaturated(c Command) Outputs {\n\tif lo, hi := spread(torques(Command{Roll: c.Roll, Pitch: c.Pitch}, 0)); hi-lo > 1 {\n\t\tk := 1 / (hi - lo) // even roll and pitch alone do not fit: scale them\n\t\tc = Command{Thrust: c.Thrust, Roll: c.Roll * k, Pitch: c.Pitch * k}\n\t}\n\tyawScale := 1.0\n\tif lo, hi := spread(torques(c, 1)); hi-lo > 1 {\n\t\tlow, high := 0.0, 1.0 // largest yaw share that still fits\n\t\tfor range 40 {\n\t\t\tmid := (low + high) / 2\n\t\t\tif lo, hi := spread(torques(c, mid)); hi-lo <= 1 {\n\t\t\t\tlow = mid\n\t\t\t} else {\n\t\t\t\thigh = mid\n\t\t\t}\n\t\t}\n\t\tyawScale = low\n\t}\n\ta := torques(c, yawScale)\n\tlo, hi := spread(a)\n\tthrust := clamp(c.Thrust, -lo, 1-hi) // shift everything into 0..1\n\tfor i := range a {\n\t\ta[i] = clamp(thrust+a[i], 0, 1)\n\t}\n\treturn a\n}\n\n// Achieved inverts the mixer: what the four outputs really produce.\nfunc Achieved(o Outputs) Command {\n\tvar c Command\n\tfor i, m := range QuadX {\n\t\tc.Thrust += o[i] / 4\n\t\tc.Roll += o[i] * m.Roll / 4\n\t\tc.Pitch += o[i] * m.Pitch / 4\n\t\tc.Yaw += o[i] * m.Yaw / 4\n\t}\n\treturn c\n}\n\nfunc (c Command) String() string {\n\treturn fmt.Sprintf(\"T %.2f R %+.2f P %+.2f Y %+.2f\", r2(c.Thrust), r2(c.Roll), r2(c.Pitch), r2(c.Yaw))\n}\n\n// r2 rounds to 0.01 and turns -0 into 0 so the bisection's last bits\n// do not print as -0.00.\nfunc r2(v float64) float64 { return math.Round(v*100)/100 + 0 }\n\nfunc (o Outputs) String() string {\n\treturn fmt.Sprintf(\"%.2f %.2f %.2f %.2f\", o[0], o[1], o[2], o[3])\n}\n\nfunc saturated(c Command) bool {\n\tlo, hi := spread(torques(c, 1))\n\treturn c.Thrust+lo < 0 || c.Thrust+hi > 1\n}\n\nfunc main() {\n\tfmt.Println(\"motors (PX4 Quadrotor X):\")\n\tfor _, m := range QuadX {\n\t\tfmt.Printf(\"  %-19s roll %+.0f pitch %+.0f yaw %+.0f\\n\", m.Name, m.Roll, m.Pitch, m.Yaw)\n\t}\n\tcases := []struct {\n\t\tname string\n\t\tcmd  Command\n\t}{\n\t\t{\"hover\", Command{Thrust: 0.5}},\n\t\t{\"roll right\", Command{Thrust: 0.5, Roll: 0.1}},\n\t\t{\"pitch down, yaw right\", Command{Thrust: 0.55, Pitch: -0.1, Yaw: 0.05}},\n\t\t{\"full throttle + roll\", Command{Thrust: 0.95, Roll: 0.2}},\n\t\t{\"idle + roll\", Command{Thrust: 0.05, Roll: 0.2}},\n\t\t{\"hard yaw at hover\", Command{Thrust: 0.5, Yaw: 0.6}},\n\t\t{\"climb, roll and yaw\", Command{Thrust: 0.8, Roll: 0.3, Yaw: 0.3}},\n\t}\n\tfor _, tc := range cases {\n\t\tfmt.Printf(\"%-22s asks %v\\n\", tc.name, tc.cmd)\n\t\tif !saturated(tc.cmd) {\n\t\t\to := Desaturated(tc.cmd)\n\t\t\tfmt.Printf(\"  %-12s %v -> %v\\n\", \"mixed\", o, Achieved(o))\n\t\t\tcontinue\n\t\t}\n\t\to := Clipped(tc.cmd)\n\t\tfmt.Printf(\"  %-12s %v -> %v\\n\", \"clipped\", o, Achieved(o))\n\t\to = Desaturated(tc.cmd)\n\t\tfmt.Printf(\"  %-12s %v -> %v\\n\", \"desaturated\", o, Achieved(o))\n\t}\n}\n\nfunc clamp(v, lo, hi float64) float64 { return math.Max(lo, math.Min(hi, v)) }","language":"go","title":"Seven commands through the mixer","walkthrough":"Roll right gives 0.40 0.60 0.60 0.40, and pitch down with a little yaw gives 0.50 0.70 0.40 0.60; both achieve exactly what was asked. At full throttle with roll, clipping yields 0.75 1.00 1.00 0.75, which achieves only R +0.13 at T 0.88; desaturation lowers thrust to 0.80 and keeps R +0.20. At idle with roll, clipping again cuts the roll to +0.13, while desaturation raises thrust to 0.20 and keeps it. Hard yaw is limited to Y +0.50 either way. In the last case clipping produces P +0.10 that nobody asked for and only R +0.20; desaturation keeps R +0.30 and P +0.00 and gives up yaw (+0.20) and thrust (0.50)."},{"body":"The desaturating mixer applies the priorities in order. Roll and pitch come first: losing them means a tilt the vehicle cannot correct. If even they do not fit into the 0..1 range, they are scaled down together, which keeps the direction of the correction. Yaw comes next: the program finds the largest share of the yaw command that still fits, since losing yaw only lets the heading drift. Thrust comes last: the collective is moved to the nearest value at which every motor lies in 0..1. PX4 offers both behaviours through CA_METHOD (pseudo-inverse with output clipping, or with sequential desaturation). At the top it reduces thrust. At the bottom, with Airmode off it reduces the torque instead, so at zero throttle no attitude correction is possible; with MC_AIRMODE it raises thrust, as the idle case above does, which keeps control at zero throttle but can make a badly tuned vehicle climb after the throttle is cut.","code":"a := torques(c, yawScale)            // roll, pitch and yaw share per motor\nlo, hi := spread(a)                  // their range now fits in 1\nthrust := clamp(c.Thrust, -lo, 1-hi) // nearest thrust that fits\nfor i := range a {\n\ta[i] = clamp(thrust+a[i], 0, 1)\n}","language":"go","title":"Desaturation and its priorities","walkthrough":"After roll, pitch and yaw have been made to fit, the lowest motor needs thrust of at least -lo and the highest at most 1 - hi. Clamping the requested thrust into that interval moves all four outputs by the same amount, so the torques are untouched and only the collective changes."},{"body":"Outputs in 0..1 reach the ESCs as PWM pulses, OneShot or DShot. Thrust grows roughly with the square of rotor speed, so equal steps in output are not equal steps in thrust; PX4 compensates with a thrust model parameter (THR_MDL_FAC). A minimum output keeps motors spinning in flight, and battery sag lowers the maximum thrust, so a vehicle saturates more often late in a flight. Go meets mixing outside the firmware: in simulators, in log analysis that recomputes achieved torques from recorded motor outputs to find saturation, and in tools for new frame geometries. Test motor order and direction on the ground with the propellers removed.","title":"From normalised outputs to motors"},{"body":"The simulator models the airframe as a point mass whose thrust tilts, without attitude dynamics or individual motors, so there is nothing to mix and this program does not use it. Run it in any project, or create New project > Robotics and simulation > Drone flight, replace main.go with it (mission.go can stay) and Run to read the table in the console. To connect it to a flight, call Desaturated(Command{Thrust: u}) with the thrust a SetThrust loop computes and add a roll command, then count how often a hard climb saturates the motors.","title":"Fly it in GopherForge"}],"takeaway":"A quad X mixer adds thrust and signed roll, pitch and yaw shares per motor, with signs set by rotor position and spin direction. When outputs saturate, never clip motors one by one: keep roll and pitch, cut yaw, then shift the collective, and check what the outputs achieve by inverting the mix.","title":"Motor mixing for a quad X: thrust and torques to four motors","unitID":"drones-control","wrongAnswers":["Roll and pitch first, since thrust keeps it in the air","Clip each motor to 0..1 and accept the result"]},{"conceptTag":"drones.flight-modes","designGuide":{"cautions":["The autopilot can change mode itself; reconcile, do not fight.","Guards that read clocks or I/O make the machine hard to test."],"cost":"A table, a few pure guard functions and a monitor that turns telemetry into events.","family":"drones","flow":["Snapshot vehicle state","Match row, run guard","Command, then commit","Log transition or reason"],"ratings":[],"strengths":["Every allowed path is in one table you can review and test.","Refusals carry reasons the operator can act on."]},"hint":"A table lists every allowed path. What does that imply for an event with no matching row, and what should the operator see?","id":"drones.flight-modes","introduction":"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.","nuance":"Rejections matter as much as transitions in the log: they explain why the drone did not move. Guards add reasons to rows that exist; a missing row means the request is never valid in that state.","objective":"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.","question":"A ground station's state machine receives goto while in DISARMED, and no row of its transition table matches. What should happen?","references":["https://docs.px4.io/main/en/flight_modes_mc/","https://docs.px4.io/main/en/flying/pre_flight_checks.html","https://ardupilot.org/copter/docs/flight-modes.html","https://mavlink.io/en/messages/common.html"],"reviewAnswer":"Rejected with a reason; the state stays the same","reviewPrompt":"Request not in the table?","sections":[{"body":"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.","title":"States, events and guards"},{"body":"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.","code":"package main\n\n// Flight modes as an explicit state machine: a transition table with\n// guards, rejected requests with reasons, and a logged run that drives the\n// simulator only through the machine's decisions.\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\ntype State int\n\nconst (\n\tDisarmed State = iota\n\tArmed\n\tTakingOff\n\tHolding\n\tMission\n\tReturning\n\tLanding\n)\n\nvar stateNames = [...]string{\"DISARMED\", \"ARMED\", \"TAKEOFF\", \"HOLD\", \"MISSION\", \"RTL\", \"LAND\"}\n\nfunc (s State) String() string { return stateNames[s] }\n\ntype Event int\n\nconst (\n\tArm Event = iota\n\tDisarm\n\tTakeOff\n\tGoTo\n\tHold\n\tReturnHome\n\tLand\n\tReached    // from the vehicle: take-off altitude or waypoint reached\n\tTouchdown  // from the vehicle: on the ground and disarmed\n\tBatteryLow // from our own monitor\n)\n\nvar eventNames = [...]string{\"arm\", \"disarm\", \"takeoff\", \"goto\", \"hold\", \"rtl\", \"land\", \"reached\", \"touchdown\", \"battery low\"}\n\nfunc (e Event) String() string { return eventNames[e] }\n\n// Snapshot is what guards may look at.\ntype Snapshot struct {\n\tBattery float64 // percent\n\tSats    int     // GPS satellites used in the fix\n\tPos     drone.Vec3\n}\n\n// Request is an event with its argument.\ntype Request struct {\n\tEvent  Event\n\tTarget drone.Vec3 // take-off altitude in Z, or the go-to point\n}\n\nfunc (r Request) String() string {\n\tswitch r.Event {\n\tcase TakeOff:\n\t\treturn fmt.Sprintf(\"takeoff %.0f m\", r.Target.Z)\n\tcase GoTo:\n\t\treturn \"goto \" + r.Target.String()\n\t}\n\treturn r.Event.String()\n}\n\n// Rules are the limits the guards enforce.\ntype Rules struct {\n\tMinArmBattery float64\n\tReserve       float64 // below this, return home\n\tMinSats       int\n\tFence         []drone.Vec3\n\tCeiling       float64\n}\n\ntype Guard func(Rules, Snapshot, Request) error\n\ntype Transition struct {\n\tFrom  State\n\tEvent Event\n\tTo    State\n\tGuard Guard\n}\n\n// preArm reports every failing check at once, as a ground station should.\nfunc preArm(r Rules, s Snapshot, _ Request) error {\n\tvar errs []error\n\tif s.Battery < r.MinArmBattery {\n\t\terrs = append(errs, fmt.Errorf(\"battery %.0f%% < %.0f%%\", s.Battery, r.MinArmBattery))\n\t}\n\tif s.Sats < r.MinSats {\n\t\terrs = append(errs, fmt.Errorf(\"GPS %d satellites < %d\", s.Sats, r.MinSats))\n\t}\n\tif !drone.Inside(r.Fence, s.Pos) {\n\t\terrs = append(errs, errors.New(\"outside geofence\"))\n\t}\n\treturn errors.Join(errs...)\n}\n\nfunc altitudeOK(r Rules, _ Snapshot, q Request) error {\n\tif q.Target.Z <= 2 || q.Target.Z > r.Ceiling {\n\t\treturn fmt.Errorf(\"altitude %.0f m outside 2..%.0f m\", q.Target.Z, r.Ceiling)\n\t}\n\treturn nil\n}\n\nfunc targetOK(r Rules, s Snapshot, q Request) error {\n\tif !drone.Inside(r.Fence, q.Target) {\n\t\treturn fmt.Errorf(\"target %v outside geofence\", q.Target)\n\t}\n\tif s.Battery < r.Reserve+5 {\n\t\treturn fmt.Errorf(\"battery %.0f%% too close to reserve\", s.Battery)\n\t}\n\treturn altitudeOK(r, s, q)\n}\n\nvar table = []Transition{\n\t{Disarmed, Arm, Armed, preArm},\n\t{Armed, Disarm, Disarmed, nil},\n\t{Armed, TakeOff, TakingOff, altitudeOK},\n\t{TakingOff, Reached, Holding, nil},\n\t{Holding, GoTo, Mission, targetOK},\n\t{Mission, GoTo, Mission, targetOK},\n\t{Mission, Reached, Holding, nil},\n\t{Mission, Hold, Holding, nil},\n\t{Returning, Hold, Holding, nil},\n\t{TakingOff, ReturnHome, Returning, nil},\n\t{Holding, ReturnHome, Returning, nil},\n\t{Mission, ReturnHome, Returning, nil},\n\t{TakingOff, BatteryLow, Returning, nil},\n\t{Holding, BatteryLow, Returning, nil},\n\t{Mission, BatteryLow, Returning, nil},\n\t{Holding, Land, Landing, nil},\n\t{Mission, Land, Landing, nil},\n\t{Returning, Land, Landing, nil},\n\t{Returning, Touchdown, Disarmed, nil},\n\t{Landing, Touchdown, Disarmed, nil},\n}\n\n// Machine holds the current state. Fire finds the transition, checks its\n// guard, lets act command the vehicle and commits only if act succeeds.\ntype Machine struct {\n\tState State\n\tRules Rules\n\tLog   func(from, to State, r Request)\n}\n\nfunc (m *Machine) Fire(s Snapshot, r Request, act func(Request) error) error {\n\tfor _, tr := range table {\n\t\tif tr.From != m.State || tr.Event != r.Event {\n\t\t\tcontinue\n\t\t}\n\t\tif tr.Guard != nil {\n\t\t\tif err := tr.Guard(m.Rules, s, r); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v in %v rejected: %s\", r, m.State, strings.ReplaceAll(err.Error(), \"\\n\", \"; \"))\n\t\t\t}\n\t\t}\n\t\tif act != nil {\n\t\t\tif err := act(r); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v in %v: vehicle refused: %w\", r, m.State, err)\n\t\t\t}\n\t\t}\n\t\tfrom := m.State\n\t\tm.State = tr.To\n\t\tif m.Log != nil {\n\t\t\tm.Log(from, m.State, r)\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%v not allowed in %v\", r, m.State)\n}\n\nfunc main() {\n\tfence := []drone.Vec3{{X: -100, Y: -100}, {X: 100, Y: -100}, {X: 100, Y: 100}, {X: -100, Y: 100}}\n\trules := Rules{MinArmBattery: 40, Reserve: 30, MinSats: 6, Fence: fence, Ceiling: 60}\n\n\tfmt.Println(\"table-driven checks:\")\n\tgood := Snapshot{Battery: 90, Sats: 12}\n\tcases := []struct {\n\t\tfrom State\n\t\tsnap Snapshot\n\t\treq  Request\n\t}{\n\t\t{Disarmed, good, Request{Event: Arm}},\n\t\t{Disarmed, Snapshot{Battery: 35, Sats: 4, Pos: drone.Vec3{X: 140}}, Request{Event: Arm}},\n\t\t{Armed, good, Request{TakeOff, drone.Vec3{Z: 80}}},\n\t\t{Holding, good, Request{GoTo, drone.Vec3{X: 150, Z: 20}}},\n\t\t{Holding, Snapshot{Battery: 33, Sats: 12}, Request{GoTo, drone.Vec3{X: 50, Z: 20}}},\n\t\t{Mission, good, Request{Event: Disarm}},\n\t\t{Disarmed, good, Request{GoTo, drone.Vec3{X: 10, Z: 10}}},\n\t\t{Mission, good, Request{Event: BatteryLow}},\n\t\t{Returning, good, Request{Event: Hold}},\n\t}\n\tfor _, c := range cases {\n\t\tm := &Machine{State: c.from, Rules: rules}\n\t\tif err := m.Fire(c.snap, c.req, nil); err != nil {\n\t\t\tfmt.Println(\"  no: \", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"  ok:  %v + %v -> %v\\n\", c.from, c.req, m.State)\n\t\t}\n\t}\n\n\tsim := drone.New(drone.Config{Geofence: fence, Ceiling: rules.Ceiling, Battery: 45, Seed: 7})\n\td := sim.Drone()\n\tsnapshot := func() Snapshot {\n\t\tst := d.State()\n\t\tsats := min(int(sim.Time()*1.5), 14) // the receiver needs a few seconds for a fix\n\t\treturn Snapshot{Battery: st.Battery, Sats: sats, Pos: st.Pos}\n\t}\n\tm := &Machine{State: Disarmed, Rules: rules}\n\tm.Log = func(from, to State, r Request) {\n\t\tline := fmt.Sprintf(\"%v -> %v (%v)\", from, to, r)\n\t\tfmt.Printf(\"  %5.1f s  %s\\n\", sim.Time(), line)\n\t\tsim.Mark(line)\n\t}\n\tact := func(r Request) error {\n\t\tswitch r.Event {\n\t\tcase Arm:\n\t\t\treturn d.Arm()\n\t\tcase TakeOff:\n\t\t\treturn d.TakeOff(r.Target.Z)\n\t\tcase GoTo:\n\t\t\treturn d.GoTo(r.Target)\n\t\tcase Hold:\n\t\t\treturn d.Hold()\n\t\tcase ReturnHome, BatteryLow:\n\t\t\treturn d.ReturnHome()\n\t\tcase Land:\n\t\t\treturn d.Land()\n\t\t}\n\t\treturn nil // disarm on the ground, reached, touchdown: nothing to command\n\t}\n\trequest := func(r Request) {\n\t\tif err := m.Fire(snapshot(), r, act); err != nil {\n\t\t\tfmt.Printf(\"  %5.1f s  no: %v\\n\", sim.Time(), err)\n\t\t}\n\t}\n\t// monitor turns what the vehicle reports into events, once per step.\n\tmonitor := func(float64) {\n\t\tst, s := d.State(), m.State\n\t\tswitch {\n\t\tcase (s == TakingOff || s == Mission) && d.Arrived():\n\t\t\tm.Fire(snapshot(), Request{Event: Reached}, nil)\n\t\tcase (s == Returning || s == Landing) && st.Landed:\n\t\t\tm.Fire(snapshot(), Request{Event: Touchdown}, nil)\n\t\tcase (s == TakingOff || s == Holding || s == Mission) && st.Battery <= rules.Reserve:\n\t\t\trequest(Request{Event: BatteryLow})\n\t\t}\n\t}\n\tsettle := func(want State, limit float64) {\n\t\tsim.RunUntil(limit, func(t float64) bool { monitor(t); return m.State == want || m.State == Returning })\n\t}\n\n\tfmt.Println(\"flight:\")\n\trequest(Request{Event: Arm})\n\tsim.Run(5, nil)\n\trequest(Request{Event: Arm})\n\trequest(Request{TakeOff, drone.Vec3{Z: 80}})\n\trequest(Request{TakeOff, drone.Vec3{Z: 20}})\n\tsettle(Holding, 30)\n\trequest(Request{GoTo, drone.Vec3{X: 150, Z: 20}})\n\trequest(Request{Event: Disarm})\n\trequest(Request{GoTo, drone.Vec3{X: 80, Y: 60, Z: 30}})\n\tsettle(Holding, 60)\n\trequest(Request{GoTo, drone.Vec3{X: -70, Y: 80, Z: 30}})\n\tsettle(Holding, 90)\n\tsim.RunUntil(120, func(t float64) bool { monitor(t); return m.State == Disarmed })\n\tfmt.Printf(\"machine %v, simulator %v\\n\", m.State, d.State().Mode)\n\tsim.Save()\n}","language":"go","title":"The table, tested and flown","walkthrough":"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."},{"body":"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.","code":"// fromVehicle maps the simulator's mode onto the machine's states, for\n// reconciling after the autopilot changed mode on its own.\nfunc fromVehicle(m drone.Mode) (State, bool) {\n\tswitch m {\n\tcase drone.Idle, drone.Landed:\n\t\treturn Disarmed, true\n\tcase drone.Armed:\n\t\treturn Armed, true\n\tcase drone.TakingOff:\n\t\treturn TakingOff, true\n\tcase drone.Hold:\n\t\treturn Holding, true\n\tcase drone.GoingTo:\n\t\treturn Mission, true\n\tcase drone.Returning:\n\t\treturn Returning, true\n\tcase drone.Landing:\n\t\treturn Landing, true\n\t}\n\treturn 0, false // Velocity, Manual, Crashed: outside this machine\n}","language":"go","title":"Command the vehicle, then commit","walkthrough":"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."},{"body":"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.","title":"Logging and testing transitions"},{"body":"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.","title":"Fly it in GopherForge"}],"takeaway":"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.","title":"Flight modes as an explicit state machine","unitID":"drones-control","wrongAnswers":["Arm automatically, then fly to the target","Ignore it silently and keep no record"]},{"conceptTag":"drones.waypoint-missions","designGuide":{"cautions":["Uploads may not be atomic; verify the stored plan before arming.","Acceptance radius trades corner cutting against slow arrivals."],"cost":"A mission builder, an uploader with timeouts and retries, and a download-and-compare check before every flight.","family":"drones","flow":["Generate mission items","Upload on request","Verify plan on board","Fly and track progress"],"ratings":[],"strengths":["Lost messages are repaired by re-requesting one sequence number.","A generated survey covers the area with a known overlap."]},"hint":"Think about how a lost item gets repaired: whoever asks for items by number can simply ask again.","id":"drones.waypoint-missions","introduction":"An autonomous flight is a list of numbered mission items that the flight controller executes one after another: take off, fly to a point, wait, come back, land. The ground station builds that list, moves it onto the vehicle intact over a lossy radio link, and then watches progress. Each step has a classic failure: a waypoint that is never reached, an upload that leaves half of the old mission on board, a survey whose legs leave gaps between camera footprints.","nuance":"The ground station sends only MISSION_COUNT unprompted; the vehicle then pulls items by sequence number, so a loss is fixed by asking again. MISSION_ACK comes once, at the end, with the result.","objective":"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.","question":"In a MAVLink mission upload, which side asks for each item, and how?","references":["https://mavlink.io/en/services/mission.html","https://mavlink.io/en/messages/common.html#MAV_CMD_NAV_WAYPOINT","https://ardupilot.org/copter/docs/mission-command-list.html","https://docs.px4.io/main/en/flying/missions.html"],"reviewAnswer":"The vehicle, with MISSION_REQUEST_INT per seq","reviewPrompt":"Who asks for each mission item?","sections":[{"body":"A MAVLink mission item is a MAV_CMD number with seven parameters, a frame and a sequence number. NAV commands move the vehicle: MAV_CMD_NAV_TAKEOFF (22) climbs to the altitude in param7, MAV_CMD_NAV_WAYPOINT (16) flies to a position with a hold time in param1 and an acceptance radius in param2, MAV_CMD_NAV_LOITER_TIME (19) stays for param1 seconds, and MAV_CMD_NAV_RETURN_TO_LAUNCH (20) and MAV_CMD_NAV_LAND (21) end the flight. DO commands, such as a camera trigger or a speed change, run between NAV commands. A waypoint is complete when the vehicle enters its acceptance radius; flight stacks differ in whether they honour param2 or use a vehicle-wide radius parameter, so check your autopilot's mission command list. A tiny radius makes the vehicle slow down and fight the wind to hit an exact point; a large one cuts corners, which matters next to a fence. Holds and loiters stop the vehicle, which suits a photo or a sensor reading, not a survey leg.","title":"Mission items and when they count as done"},{"body":"The upload is driven by the vehicle. The ground station sends MISSION_COUNT; the vehicle answers MISSION_REQUEST_INT for seq 0; the ground station sends MISSION_ITEM_INT with seq 0; the vehicle asks for seq 1, and so on until it sends MISSION_ACK with MAV_MISSION_ACCEPTED or an error. Because the receiver asks for every item by number, a lost message is repaired by asking again. The MAVLink specification recommends resending after 1500 ms by default (250 ms for plan items) and giving up after 5 retries; out-of-sequence messages are recoverable, timeouts are not errors, and an error ACK ends the transfer and should leave the stored mission unaltered. Downloads run the same exchange the other way, starting with MISSION_REQUEST_LIST, and geofences and rally points use the same protocol with a different mission_type. Link, Item and the message types in the sketch stand in for a MAVLink library such as gomavlib.","code":"func Upload(ctx context.Context, link Link, items []Item) error {\n\tlast := Message(MissionCount{Count: uint16(len(items))})\n\tfor retries := 0; retries <= 5; {\n\t\tif err := link.Send(last); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Receive returns only mission messages from this vehicle.\n\t\tmsg, err := link.Receive(ctx, 1500*time.Millisecond)\n\t\tswitch m := msg.(type) {\n\t\tcase MissionRequestInt:\n\t\t\tif int(m.Seq) >= len(items) {\n\t\t\t\treturn fmt.Errorf(\"vehicle asked for item %d of %d\", m.Seq, len(items))\n\t\t\t}\n\t\t\tlast, retries = items[m.Seq].Encode(m.Seq), 0\n\t\tcase MissionAck:\n\t\t\tif m.Type != MavMissionAccepted {\n\t\t\t\treturn fmt.Errorf(\"upload rejected: %v\", m.Type)\n\t\t\t}\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tif !errors.Is(err, ErrTimeout) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tretries++ // silence: send the same message again\n\t\t}\n\t}\n\treturn errors.New(\"mission upload: no answer after 5 retries\")\n}","language":"go","title":"Moving a mission over a lossy link","walkthrough":"The loop always sends last: first the count, then whichever item the vehicle asked for. A timeout resends the same bytes, a repeated MISSION_REQUEST_INT for the same seq is answered with the same item from the same slice, and progress resets the retry counter. Any ACK other than MAV_MISSION_ACCEPTED, a request beyond the list, a cancelled context or five silent timeouts end the upload with an error."},{"body":"Retries mean duplicates: the vehicle may request item 7 twice because your first answer arrived late, and an operator may press Upload again after a dropout. Make every step safe to repeat: build the item list once, encode it deterministically, serve every request from that immutable list, and treat a repeated request as normal. On the vehicle, the specification asks that a new mission be fully uploaded and accepted before the old one is replaced, but ArduPilot documents that its uploads are not atomic, so a failed upload can leave a mix of old and new items, and that it stores home in seq 0. Newer MAVLink adds an opaque_id to MISSION_ACK, MISSION_COUNT and MISSION_CURRENT, so a ground station can tell whether the plan on board is the one it uploaded. After an interrupted upload, download the mission and compare it before arming, with tolerances, because the vehicle may round coordinates.","title":"Idempotent uploads and stale plans"},{"body":"Mapping flights cover an area with parallel legs flown in alternating directions, the boustrophedon or lawnmower pattern. The camera sets the spacing: the ground footprint across track is 2 h tan(HFOV/2), and side overlap, typically 60 to 80 percent for photogrammetry, shrinks the spacing to footprint times (1 - overlap). The generator rounds the number of legs up so they divide the area evenly and the last leg lies on the far edge. The program builds a mission of a take-off, twelve survey waypoints with a 2 m acceptance radius, a 5 s LOITER_TIME over the centre and an RTL, executes it item by item in a 2 m/s wind with gusts and prints when each item completed, the speed at that moment and the battery.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Command is the MAV_CMD_NAV_* number a MAVLink mission item carries.\ntype Command int\n\nconst (\n\tCmdWaypoint   Command = 16 // MAV_CMD_NAV_WAYPOINT\n\tCmdLoiterTime Command = 19 // MAV_CMD_NAV_LOITER_TIME\n\tCmdRTL        Command = 20 // MAV_CMD_NAV_RETURN_TO_LAUNCH\n\tCmdLand       Command = 21 // MAV_CMD_NAV_LAND\n\tCmdTakeoff    Command = 22 // MAV_CMD_NAV_TAKEOFF\n)\n\nfunc (c Command) String() string {\n\tswitch c {\n\tcase CmdWaypoint:\n\t\treturn \"WAYPOINT\"\n\tcase CmdLoiterTime:\n\t\treturn \"LOITER_TIME\"\n\tcase CmdRTL:\n\t\treturn \"RTL\"\n\tcase CmdLand:\n\t\treturn \"LAND\"\n\tcase CmdTakeoff:\n\t\treturn \"TAKEOFF\"\n\t}\n\treturn fmt.Sprintf(\"CMD_%d\", int(c))\n}\n\n// Item is one mission item: what to do, where, and when it counts as done.\ntype Item struct {\n\tSeq    int\n\tCmd    Command\n\tPos    drone.Vec3\n\tAccept float64 // acceptance radius, m\n\tHold   float64 // seconds to stay at the point\n}\n\n// Footprint is the width of ground a camera sees across track.\nfunc Footprint(alt, hfovDeg float64) float64 { return 2 * alt * math.Tan(hfovDeg/2*math.Pi/180) }\n\n// Lawnmower covers the rectangle x0..x1, y0..y1 with legs parallel to X,\n// alternating direction. The spacing is at most maxSpacing, reduced so the\n// legs divide the area evenly and the last one lies on the far edge.\nfunc Lawnmower(x0, y0, x1, y1, alt, maxSpacing float64) (pts []drone.Vec3, spacing float64) {\n\tlegs := int(math.Ceil((y1-y0)/maxSpacing)) + 1\n\tspacing = (y1 - y0) / float64(legs-1)\n\tfor i := 0; i < legs; i++ {\n\t\ty := y0 + float64(i)*spacing\n\t\ta, b := x0, x1\n\t\tif i%2 == 1 {\n\t\t\ta, b = x1, x0\n\t\t}\n\t\tpts = append(pts, drone.Vec3{X: a, Y: y, Z: alt}, drone.Vec3{X: b, Y: y, Z: alt})\n\t}\n\treturn pts, spacing\n}\n\n// BuildMission turns survey points into a numbered mission.\nfunc BuildMission(alt float64, survey []drone.Vec3) []Item {\n\titems := []Item{{Cmd: CmdTakeoff, Pos: drone.Vec3{Z: alt}}}\n\tfor _, p := range survey {\n\t\titems = append(items, Item{Cmd: CmdWaypoint, Pos: p, Accept: 2})\n\t}\n\tcentre := drone.Vec3{X: 0, Y: 30, Z: alt}\n\titems = append(items, Item{Cmd: CmdLoiterTime, Pos: centre, Accept: 1, Hold: 5})\n\titems = append(items, Item{Cmd: CmdRTL})\n\tfor i := range items {\n\t\titems[i].Seq = i\n\t}\n\treturn items\n}\n\n// Execute flies one item and reports whether it completed in time.\nfunc Execute(sim *drone.Sim, d *drone.Drone, it Item) error {\n\tvar err error\n\tswitch it.Cmd {\n\tcase CmdTakeoff:\n\t\tif err = d.Arm(); err == nil {\n\t\t\terr = d.TakeOff(it.Pos.Z)\n\t\t}\n\t\tif err == nil && !sim.RunUntil(60, func(float64) bool { return d.State().Mode == drone.Hold }) {\n\t\t\terr = fmt.Errorf(\"take-off timed out\")\n\t\t}\n\tcase CmdWaypoint, CmdLoiterTime:\n\t\tif err = d.GoTo(it.Pos); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treached := func(float64) bool { return d.State().Pos.Sub(it.Pos).Len() < it.Accept }\n\t\tif !sim.RunUntil(90, reached) {\n\t\t\treturn fmt.Errorf(\"item %d: not within %.0f m after 90 s\", it.Seq, it.Accept)\n\t\t}\n\t\tif it.Hold > 0 {\n\t\t\tsim.Run(it.Hold, nil)\n\t\t}\n\tcase CmdLand:\n\t\terr = d.Land()\n\t\tif err == nil && !sim.RunUntil(120, func(float64) bool { return d.State().Landed }) {\n\t\t\terr = fmt.Errorf(\"landing timed out\")\n\t\t}\n\tcase CmdRTL:\n\t\terr = d.ReturnHome()\n\t\tif err == nil && !sim.RunUntil(180, func(float64) bool { return d.State().Landed }) {\n\t\t\terr = fmt.Errorf(\"return timed out\")\n\t\t}\n\t}\n\treturn err\n}\n\nfunc main() {\n\tfootprint := Footprint(20, 70) // 20 m up, 70 degree lens\n\tmaxSpacing := footprint * (1 - 0.7)\n\tsurvey, spacing := Lawnmower(-30, 10, 30, 50, 20, maxSpacing)\n\tmission := BuildMission(20, survey)\n\tfmt.Printf(\"footprint %.1f m, 70%% sidelap: legs at most %.1f m apart\\n\", footprint, maxSpacing)\n\tfmt.Printf(\"survey 60 x 40 m at 20 m: %d legs %.1f m apart, %d mission items\\n\", len(survey)/2, spacing, len(mission))\n\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 2, Y: 1}, Gust: 1, MaxSpeed: 8, Seed: 11})\n\td := sim.Drone()\n\tfmt.Println(\"seq  command      target               done at  speed     battery\")\n\tstart := 0.0\n\tfor _, it := range mission {\n\t\tif err := Execute(sim, d, it); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tst := d.State()\n\t\ttarget := it.Pos.String()\n\t\tif it.Cmd == CmdRTL {\n\t\t\ttarget = \"home \" + d.Home().String()\n\t\t}\n\t\tfmt.Printf(\"%3d  %-11s  %-19s  %6.1f s  %3.1f m/s  %5.1f%%\\n\", it.Seq, it.Cmd, target, sim.Time(), st.Vel.Len(), st.Battery)\n\t\tif it.Cmd == CmdTakeoff {\n\t\t\tstart = sim.Time()\n\t\t}\n\t}\n\tst := d.State()\n\tfmt.Printf(\"survey and return took %.0f s; landed %.1f m from home\\n\", sim.Time()-start, st.Pos.Horizontal().Len())\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A lawnmower survey, flown item by item","walkthrough":"At 20 m a 70 degree lens sees a 28.0 m strip and 70 percent sidelap allows at most 8.4 m between legs, so the 40 m depth needs 6 legs exactly 8.0 m apart and the mission has 15 items. Take-off completes at 8.3 s. Every waypoint completes while the drone still moves at 4.0 to 4.7 m/s, because the 2 m radius starts the next leg before it stops. Each 60 m leg takes about 8 s, and the battery shows the wind: eastbound legs with the 2 m/s wind behind cost 1.9 to 2.1 percent, westbound legs into it 2.6 to 2.7, because drain grows with airspeed. The loiter completes at 80.5 s, stopped, after its hold, and RTL lands at 98.9 s with 74.3 percent, 0.2 m from home."},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program and keep mission.go: its Square helper is unused here and does not clash. Tap Run to see the timeline in the console, then open Output: the replay of flight.gfflight draws the survey waypoints and the loiter point, the trail, the wind arrow and the altitude strip. Try 50 percent sidelap or a 5 m acceptance radius and compare the times and the corners in the replay.","title":"Fly it in GopherForge"}],"takeaway":"A mission is a list of numbered items, each with a completion rule: an acceptance radius, a hold time or a landing. Upload it with the vehicle-driven MAVLink handshake, resend on timeouts, serve repeated requests from one immutable list, verify the stored plan before arming, and derive survey spacing from the camera footprint and overlap.","title":"Waypoint missions: mission items, the MAVLink upload protocol and a survey pattern","unitID":"drones-missions","wrongAnswers":["The ground station, by streaming items after MISSION_COUNT","The vehicle, by sending MISSION_ACK after every item"]},{"conceptTag":"drones.geofencing","designGuide":{"cautions":["Points on edges and rays through vertices need explicit rules.","Position error and tailwind eat into any margin you draw."],"cost":"A point-in-polygon test per position update, an intersection per edge for prediction, and a margin chosen from measured braking.","family":"drones","flow":["Draw inclusion, exclusion","Check point and ceiling","Predict time to boundary","Hold, return or land"],"ratings":[],"strengths":["Ray casting handles concave polygons in a few lines.","Prediction stops the vehicle inside the fence, not beyond it."]},"hint":"Compare where the fence check triggers with how far a vehicle at 8 m/s travels while braking at about 4 m/s squared.","id":"drones.geofencing","introduction":"A geofence stands between a software bug, a gust or a confused operator and an airspace infringement. Most flight stacks act only once the vehicle is already outside, and a multicopter at 8 m/s needs several metres to stop, so where the fence acts matters as much as where it is drawn. The geometry is short; the edge cases and the physics are where fences fail.","nuance":"Most fence actions trigger once the position is outside. At 8 m/s braking at 4 m/s2 the vehicle still covers about 8 m, so use a contingency boundary inside the fence or predict the breach from velocity.","objective":"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.","question":"A multicopter flies at 8 m/s straight at a geofence whose action is RTL. Why does it end up several metres outside?","references":["https://en.wikipedia.org/wiki/Point_in_polygon","https://docs.px4.io/main/en/config/safety.html","https://ardupilot.org/copter/docs/common-polygon_fence.html","https://docs.px4.io/main/en/flying/geofence.html"],"reviewAnswer":"After the breach; stopping still takes metres","reviewPrompt":"When does a fence action fire?","sections":[{"body":"A fence plan combines inclusion areas the vehicle must stay inside, exclusion areas it must stay out of (an airfield approach, a crowd, a mast) and altitude limits. PX4 and ArduPilot accept polygons and circles of both kinds, uploaded with the MAVLink mission protocol as the fence mission type, next to a simple cylinder around home with a maximum radius and altitude; with several inclusion polygons, ArduPilot lets the vehicle fly only where they all overlap. A position is allowed only if it is inside the inclusion area, outside every exclusion area and below the ceiling. The check runs on the position estimate, so it is only as good as the estimate: a GPS glitch can trigger a false breach, and a fence drawn to the metre needs a margin for position error.","title":"Inclusion, exclusion and ceiling"},{"body":"Cast a ray from the point towards +X and count the edges it crosses: an odd count means inside. The condition (a.Y > p.Y) != (b.Y > p.Y) treats each edge as half-open, so a ray through a vertex is counted once, not twice, and horizontal edges are skipped. Points exactly on an edge are the ambiguous case: plain ray casting puts left and bottom edges inside and right and top edges outside, which is fine for drawing and wrong for a safety check, so test for the boundary first and decide explicitly. Concave polygons need nothing special, but self-intersecting ones break the parity rule and a fence editor should reject them. For fences of a few kilometres, local metres around a reference point are accurate enough; over tens of kilometres, project carefully.","title":"Ray casting and its edge cases"},{"body":"The program defines an L-shaped field, a no-fly box around a mast and a 40 m ceiling. Locate is ray casting with an on-segment test first; Allowed combines the three rules and treats the boundary as a breach. Then the drone dashes east at 8 m/s with the simulator's Geofence set: every 2 s the program prints the time to the boundary along the velocity and the stopping distance, the simulator's failsafe switches to RTL on the breach, and the drone overshoots before it stops. Back inside, a careless mission overrides the RTL and sends it out again; the fence has re-armed and catches the second breach. A second flight holds as soon as the stopping distance plus a 3 m margin reaches the boundary, then tries to climb through the ceiling under velocity control.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// An L-shaped field (concave), a no-fly box around a mast, and a ceiling.\nvar (\n\tfence = []drone.Vec3{{X: -40, Y: -40}, {X: 60, Y: -40}, {X: 60, Y: 20}, {X: 10, Y: 20}, {X: 10, Y: 60}, {X: -40, Y: 60}}\n\tmast  = []drone.Vec3{{X: -25, Y: 30}, {X: -10, Y: 30}, {X: -10, Y: 45}, {X: -25, Y: 45}}\n)\n\nconst ceiling = 40.0\n\nfunc cross(a, b drone.Vec3) float64 { return a.X*b.Y - a.Y*b.X }\n\n// onSegment reports whether p lies on the segment a-b (within 1 cm).\nfunc onSegment(a, b, p drone.Vec3) bool {\n\tab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()\n\tif math.Abs(cross(ab, ap)) > 0.01*ab.Len() {\n\t\treturn false\n\t}\n\tdot := ab.X*ap.X + ab.Y*ap.Y\n\treturn dot >= 0 && dot <= ab.X*ab.X+ab.Y*ab.Y\n}\n\n// Locate is ray casting with an explicit boundary case. A horizontal ray goes\n// east from p; an edge counts when one end is strictly above p and the other\n// is not, so a ray through a vertex is counted exactly once.\nfunc Locate(poly []drone.Vec3, p drone.Vec3) string {\n\tin := false\n\tfor i, j := 0, len(poly)-1; i < len(poly); j, i = i, i+1 {\n\t\ta, b := poly[i], poly[j]\n\t\tif onSegment(a, b, p) {\n\t\t\treturn \"boundary\"\n\t\t}\n\t\tif (a.Y > p.Y) != (b.Y > p.Y) {\n\t\t\tx := a.X + (p.Y-a.Y)*(b.X-a.X)/(b.Y-a.Y)\n\t\t\tif p.X < x {\n\t\t\t\tin = !in\n\t\t\t}\n\t\t}\n\t}\n\tif in {\n\t\treturn \"inside\"\n\t}\n\treturn \"outside\"\n}\n\n// Allowed applies the whole fence: inclusion polygon, exclusion zone and\n// ceiling. A point on the boundary is treated as a breach.\nfunc Allowed(p drone.Vec3) (bool, string) {\n\tswitch {\n\tcase Locate(fence, p) != \"inside\":\n\t\treturn false, \"outside the field\"\n\tcase Locate(mast, p) != \"outside\":\n\t\treturn false, \"in the mast zone\"\n\tcase p.Z > ceiling:\n\t\treturn false, \"above the ceiling\"\n\t}\n\treturn true, \"ok\"\n}\n\n// TimeToBoundary returns how long until p moving at v crosses an edge.\nfunc TimeToBoundary(poly []drone.Vec3, p, v drone.Vec3) float64 {\n\tbest := math.Inf(1)\n\tv = v.Horizontal()\n\tfor i := range poly {\n\t\ta, b := poly[i], poly[(i+1)%len(poly)]\n\t\te, w := b.Sub(a).Horizontal(), a.Sub(p).Horizontal()\n\t\tden := cross(v, e)\n\t\tif den == 0 {\n\t\t\tcontinue // moving parallel to this edge\n\t\t}\n\t\tt, u := cross(w, e)/den, cross(w, v)/den\n\t\tif t >= 0 && u >= 0 && u <= 1 && t < best {\n\t\t\tbest = t\n\t\t}\n\t}\n\treturn best\n}\n\n// stopping distance at speed v: reaction time plus braking at decel m/s^2.\nfunc stopping(v float64) float64 { return v*0.2 + v*v/(2*4.0) }\n\nfunc takeOff(sim *drone.Sim, d *drone.Drone) {\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := d.TakeOff(15); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })\n}\n\nfunc newSim() *drone.Sim {\n\treturn drone.New(drone.Config{Wind: drone.Vec3{X: 2}, Gust: 0.5, Geofence: fence, Ceiling: ceiling, Seed: 5})\n}\n\nfunc main() {\n\tfmt.Println(\"point            mine      drone.Inside  allowed\")\n\tpoints := []struct {\n\t\tname string\n\t\tp    drone.Vec3\n\t}{\n\t\t{\"home\", drone.Vec3{}},\n\t\t{\"notch\", drone.Vec3{X: 30, Y: 40}},\n\t\t{\"east edge\", drone.Vec3{X: 60, Y: 0}},\n\t\t{\"west edge\", drone.Vec3{X: -40, Y: 0}},\n\t\t{\"inner corner\", drone.Vec3{X: 10, Y: 20}},\n\t\t{\"ray via vertex\", drone.Vec3{X: 0, Y: 20}},\n\t\t{\"mast\", drone.Vec3{X: -15, Y: 35, Z: 20}},\n\t\t{\"too high\", drone.Vec3{X: 0, Y: 10, Z: 45}},\n\t}\n\tfor _, c := range points {\n\t\tok, why := Allowed(c.p)\n\t\tfmt.Printf(\"%-15s  %-8s  %-12v  %v (%s)\\n\", c.name, Locate(fence, c.p), drone.Inside(fence, c.p), ok, why)\n\t}\n\n\t// Reactive: dash east at 8 m/s and let the simulator's fence act. Once\n\t// the drone is back inside, a careless mission sends it out again.\n\tsim := newSim()\n\td := sim.Drone()\n\ttakeOff(sim, d)\n\tstart := sim.Time()\n\tif err := d.SetVelocity(drone.Vec3{X: 8}, 0); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"\\nreactive fence: dash east at 8 m/s from home\")\n\tbreaches, peak, resumed, prev := 0, 0.0, false, d.State().Mode\n\tsim.RunUntil(180, func(t float64) bool {\n\t\tst := d.State()\n\t\tpeak = math.Max(peak, st.Pos.X)\n\t\tk := t - start\n\t\tif breaches == 0 && k > 1 && math.Abs(k-math.Round(k)) < sim.Dt()/2 && int(math.Round(k))%2 == 0 {\n\t\t\tspeed := st.Vel.Horizontal().Len()\n\t\t\tfmt.Printf(\"  t=%4.1f s  x=%5.1f m  %4.1f m/s  boundary in %5.1f s, stop needs %4.1f m\\n\",\n\t\t\t\tk, st.Pos.X, speed, TimeToBoundary(fence, st.Pos, st.Vel), stopping(speed))\n\t\t}\n\t\tif st.Mode == drone.Returning && prev != drone.Returning {\n\t\t\tbreaches++\n\t\t\tfmt.Printf(\"  t=%4.1f s  x=%5.1f m  %4.1f m/s  simulator: geofence breach %d, RTL\\n\",\n\t\t\t\tk, st.Pos.X, st.Vel.Horizontal().Len(), breaches)\n\t\t}\n\t\tif breaches == 1 && !resumed && st.Mode == drone.Returning && st.Pos.X < 45 {\n\t\t\tresumed = true\n\t\t\tfmt.Printf(\"  t=%4.1f s  x=%5.1f m  overshoot was %.1f m; mission resumes: go to x=75 m\\n\", k, st.Pos.X, peak-60)\n\t\t\tpeak = 0\n\t\t\td.GoTo(drone.Vec3{X: 75, Z: 15}) // overrides the RTL: a bug\n\t\t}\n\t\tprev = st.Mode\n\t\treturn st.Landed\n\t})\n\tst := d.State()\n\tfmt.Printf(\"  second overshoot %.1f m; %s %.1f m from home at t=%.1f s\\n\", peak-60, st.Mode, st.Pos.Horizontal().Len(), sim.Time()-start)\n\n\t// Predictive: same dash, but hold when the stopping distance plus a\n\t// margin reaches the boundary along the velocity.\n\tg := newSim()\n\tgd := g.Drone()\n\ttakeOff(g, gd)\n\tgd.SetVelocity(drone.Vec3{X: 8}, 0)\n\theld, gmax := false, 0.0\n\tg.Run(20, func(float64) {\n\t\tst := gd.State()\n\t\tgmax = math.Max(gmax, st.Pos.X)\n\t\tspeed := st.Vel.Horizontal().Len()\n\t\tif !held && TimeToBoundary(fence, st.Pos, st.Vel)*speed <= stopping(speed)+3 {\n\t\t\theld = true\n\t\t\tgd.Hold()\n\t\t\tfmt.Printf(\"\\npredictive guard: hold at x=%.1f m, %.1f m/s\\n\", st.Pos.X, speed)\n\t\t}\n\t})\n\tfmt.Printf(\"  closest approach %.1f m inside the fence, mode %s\\n\", 60-gmax, gd.State().Mode)\n\t// The ceiling holds in every mode, even under velocity control.\n\tgd.SetVelocity(drone.Vec3{Z: 3}, 0)\n\tg.Run(15, nil)\n\tfmt.Printf(\"  climb at 3 m/s for 15 s: altitude %.1f m under the %.0f m ceiling\\n\", gd.State().Pos.Z, ceiling)\n\n\tif err := g.SaveAs(\"guarded\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Check points, then fly at the fence","walkthrough":"drone.Inside says false for the east edge and true for the west edge; Locate calls both boundary and Allowed rejects them, like the inner corner of the L. The ray from (0, 20) through the vertex (10, 20) still counts as inside. The mast point is inside the field but in the exclusion zone, and 45 m is above the ceiling. In the dash the boundary is 0.1 s away at t=8.0 s and the first breach comes at 8.1 s at x=60.3 m; the drone overshoots by 4.6 m, half the 9.6 m that the deliberately cautious 4 m/s2 braking figure predicts. Back inside at x=44.9 m the resumed mission overrides the RTL, but the fence has re-armed: the second breach at 16.2 s comes at 11.3 m/s, overshoots by 8.5 m, and the second RTL lands the drone 0.3 m from home. The guard holds at x=47.5 m and stops 8.2 m inside, and a 15 s climb at 3 m/s levels off at 39.0 m, 1 m under the ceiling."},{"body":"The time to the boundary is the smallest t at which p + v t crosses an edge, a ray-segment intersection per edge computed with 2D cross products. Compare the distance along the velocity with the stopping distance v t_react + v squared / (2a): the reaction time covers the telemetry period and command latency, and a is the braking you have measured, not the best case. When the distance falls below that plus a margin for position error and tailwind, hold or turn. PX4's GF_ACTION and ArduPilot's FENCE_ACTION fire only after the breach; newer PX4 adds a contingency geofence (GF_CONT_H_MARGIN, GF_CONT_ACTION) inside the fence and asks for a margin of at least v squared / 2a, and ArduPilot can stop a Copter before the fence in Loiter when object avoidance is set up.","title":"Predict the breach instead of detecting it"},{"body":"What should happen after a breach depends on what lies beyond the line. Hold stops at once near the boundary and leaves the pilot to decide. Return flies home, usually after climbing to a return altitude, which is wrong if home lies behind an exclusion zone or the climb crosses a ceiling. Land puts the vehicle down outside the fence: acceptable over an empty field, dangerous over a road. Flight termination cuts the motors and is reserved for vehicles with a parachute or for cases where anything else is worse. The simulator's action is RTL on every new breach, re-armed once the drone is back inside, so mission code that overrides the return is caught again; better mission code never overrides a failsafe at all. A real setup chooses the action per fence and checks that the return path stays inside. Log every breach with position, velocity and estimate quality: most breaches turn out to be planning or estimation errors.","title":"Breach actions"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output shows two recordings: flight.gfflight is the reactive run, with the L-shaped fence on the map, both breaches, both overshoots and the return home; guarded.gfflight stops short of the east edge and levels off under the ceiling in the altitude strip. Set the margin to 0 or the dash speed to 12 m/s and watch where the guard stops.","title":"Fly it in GopherForge"}],"takeaway":"Use ray casting with an explicit rule for points on the boundary, combine inclusion, exclusion and ceiling checks, and remember that most breach actions fire after the breach. Predict the boundary from velocity and stopping distance, and keep a margin inside the fence for braking, wind and position error.","title":"Geofencing: inclusion and exclusion polygons, ray casting and predicting a breach","unitID":"drones-missions","wrongAnswers":["RTL climbs first, and the climb drifts it outside","Ray casting misses points that lie on the boundary"]},{"conceptTag":"drones.failsafes","designGuide":{"cautions":["Voltage sag and cold packs distort charge estimates.","A reserve below the land failsafe ends in a forced landing."],"cost":"A consumption model fitted from flight logs, a budget check in the control loop and a test for every failsafe path.","family":"drones","flow":["Fit drain from logs","Budget home plus reserve","Turn back at the need","Keep thresholds as backup"],"ratings":[],"strengths":["The turn-back point adapts to distance and wind.","Fixed thresholds remain an independent last resort."]},"hint":"Ask what a single percentage threshold knows about where the vehicle is and which way the wind blows on the way back.","id":"drones.failsafes","introduction":"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.","nuance":"The charge needed to get home grows with distance and headwind. A budget checked every second turns back earlier when the vehicle is far away or downwind, and later when it is close to home.","objective":"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.","question":"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?","references":["https://docs.px4.io/main/en/config/safety.html","https://ardupilot.org/copter/docs/failsafe-battery.html","https://ardupilot.org/copter/docs/gcs-failsafe.html","https://pkg.go.dev/time#Timer"],"reviewAnswer":"It ignores the distance home and the wind on the way","reviewPrompt":"Why is a 20% RTL rule not enough?","sections":[{"body":"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.","title":"State of charge, voltage and sag"},{"body":"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.","title":"An energy budget for the way home"},{"body":"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.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Budget estimates the charge needed to fly home and land from where the\n// drone is now. The autopilot flies home at a set ground speed unless the\n// airframe's top airspeed cannot make it; drain is hover plus a term that\n// grows with airspeed squared, fitted from flight logs.\ntype Budget struct {\n\tSpeed   float64 // ground speed the autopilot flies home, m/s\n\tMaxAir  float64 // top airspeed of the airframe, m/s\n\tHover   float64 // drain in a hover, %/s\n\tDrag    float64 // extra drain per (m/s of airspeed)^2, %/s\n\tFactor  float64 // time margin for the turn, braking and the approach\n\tDescent float64 // average descent rate, m/s\n\tReserve float64 // charge to keep on the ground, %: above the land failsafe\n}\n\n// Need returns the charge to get home, the ground speed and airspeed it\n// assumes, and the time it takes. A headwind raises the airspeed for the\n// same ground speed; once the airspeed limit is reached it lowers the\n// ground speed instead. If the wind beats the airframe, the need is infinite.\nfunc (b Budget) Need(p, home, wind drone.Vec3) (need, groundSpeed, airspeed, seconds float64) {\n\ttoHome := home.Sub(p).Horizontal()\n\tdist := toHome.Len()\n\tu := drone.Vec3{X: 1}\n\tif dist > 0 {\n\t\tu = toHome.Scale(1 / dist)\n\t}\n\talong := wind.X*u.X + wind.Y*u.Y  // tailwind on the way home\n\tacross := wind.X*u.Y - wind.Y*u.X // crosswind the airframe must cancel\n\tinf := math.Inf(1)\n\tif across*across >= b.MaxAir*b.MaxAir {\n\t\treturn inf, 0, b.MaxAir, inf\n\t}\n\tgroundSpeed = math.Min(b.Speed, along+math.Sqrt(b.MaxAir*b.MaxAir-across*across))\n\tif groundSpeed <= 0.5 {\n\t\treturn inf, groundSpeed, b.MaxAir, inf\n\t}\n\tairspeed = u.Scale(groundSpeed).Sub(wind.Horizontal()).Len()\n\tcruise, descend := b.Factor*dist/groundSpeed, p.Z/b.Descent\n\tneed = cruise*(b.Hover+b.Drag*airspeed*airspeed) + descend*b.Hover + b.Reserve\n\treturn need, groundSpeed, airspeed, cruise + descend\n}\n\nvar (\n\twind   = drone.Vec3{X: 5} // blowing east: a tailwind out, a headwind home\n\ttarget = drone.Vec3{X: 600, Z: 20}\n\tbudget = Budget{Speed: 10, MaxAir: 18, Hover: 0.18, Drag: 0.0016, Factor: 1.1, Descent: 1.5, Reserve: 15}\n)\n\n// fly sends the drone out to the target, where it holds for an inspection,\n// and prints the autopilot's events as a ground station receives them.\nfunc fly(useBudget bool) *drone.Sim {\n\tsim := drone.New(drone.Config{Wind: wind, Gust: 0.5, Battery: 45, MaxSpeed: 10, Seed: 9})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(20)\n\tsim.RunUntil(30, func(float64) bool { return d.Arrived() })\n\tseen := len(sim.Events())\n\td.GoTo(target)\n\tturned, atTurn := false, 0.0\n\tsim.RunUntil(400, func(t float64) bool {\n\t\tst := d.State()\n\t\tevents := sim.Events()\n\t\tfor _, e := range events[seen:] {\n\t\t\tfmt.Printf(\"  %5.1f s  %-35s battery %4.1f%%  %5.1f m out\\n\", e.T, e.Text, st.Battery, st.Pos.Horizontal().Len())\n\t\t}\n\t\tseen = len(events)\n\t\tonSecond := math.Abs(t-math.Round(t)) < sim.Dt()/2\n\t\tif useBudget && !turned && onSecond && (st.Mode == drone.GoingTo || st.Mode == drone.Hold) {\n\t\t\tneed, gs, air, secs := budget.Need(st.Pos, d.Home(), wind)\n\t\t\tif st.Battery <= need {\n\t\t\t\tturned, atTurn = true, st.Battery\n\t\t\t\tfmt.Printf(\"  %5.1f s  budget: need %.1f%% (%.0f s home at %.1f m/s, airspeed %.1f), have %.1f%%\\n\",\n\t\t\t\t\tt, need, secs, gs, air, st.Battery)\n\t\t\t\td.ReturnHome()\n\t\t\t}\n\t\t}\n\t\treturn st.Landed\n\t})\n\tst := d.State()\n\tif turned {\n\t\tfmt.Printf(\"  used %.1f%% to get home, budgeted %.1f%% plus the %.0f%% reserve\\n\",\n\t\t\tatTurn-st.Battery, atTurn-budget.Reserve, budget.Reserve)\n\t}\n\tfmt.Printf(\"  %s %.1f m from home with %.1f%%\\n\", st.Mode, st.Pos.Horizontal().Len(), st.Battery)\n\treturn sim\n}\n\nfunc main() {\n\tfmt.Println(\"charge to get home from x m east at 20 m (10 m/s home, 18 m/s top airspeed, 15% reserve)\")\n\tfmt.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\")\n\tfor _, dist := range []float64{100, 300, 500} {\n\t\tfmt.Printf(\"  %3.0f m \", dist)\n\t\tfor _, w := range []drone.Vec3{{}, {X: 5}, {X: 12}, {X: 20}, {Y: 10}} {\n\t\t\tneed, _, _, _ := budget.Need(drone.Vec3{X: dist, Z: 20}, drone.Vec3{}, w)\n\t\t\tcell := fmt.Sprintf(\"%.1f%%\", need)\n\t\t\tif math.IsInf(need, 1) {\n\t\t\t\tcell = \"no way home\"\n\t\t\t}\n\t\t\tfmt.Printf(\"%13s\", cell)\n\t\t}\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println(\"\\nfixed thresholds only: out to x=600 m on 45%, hold there\")\n\tfixed := fly(false)\n\tif err := fixed.SaveAs(\"thresholds\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"\\nenergy budget checked every second, same mission\")\n\tsim := fly(true)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Thresholds against a budget","walkthrough":"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."},{"body":"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.","code":"func Watch(ctx context.Context, beats <-chan struct{}, timeout time.Duration, lost func(bool)) {\n\tt := time.NewTimer(timeout)\n\tdefer t.Stop()\n\tdown := false\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-beats:\n\t\t\tif down {\n\t\t\t\tdown = false\n\t\t\t\tlost(false)\n\t\t\t}\n\t\t\tt.Reset(timeout)\n\t\tcase <-t.C:\n\t\t\tdown = true\n\t\t\tlost(true)\n\t\t}\n\t}\n}","language":"go","title":"Link loss is a timeout","walkthrough":"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."},{"body":"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.","title":"Priorities, and testing every failsafe"},{"body":"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.","title":"Fly it in GopherForge"}],"takeaway":"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.","title":"Failsafes: battery energy budgets, link-loss timeouts and which action wins","unitID":"drones-missions","wrongAnswers":["Percent readings are too coarse to trigger in time","RTL always diverts to the nearest rally point"]},{"conceptTag":"drones.path-planning","designGuide":{"cautions":["Grid resolution can close narrow gaps or waste space.","A straight-line RTL ignores the zones you planned around."],"cost":"A rasterized map with an inflation step, a priority-queue search and a replan hook wherever the map can change.","family":"drones","flow":["Inflate zones into a grid","A* with octile heuristic","Prune by line of sight","Replan when map changes"],"ratings":[],"strengths":["Optimal grid paths with far fewer expansions than Dijkstra.","Pruned paths are short lists of flyable waypoints."]},"hint":"Compare the Manhattan distance of one diagonal step with what that step actually costs on the grid.","id":"drones.path-planning","introduction":"A straight line from take-off to destination is the shortest path until something is in the way: a stay-out zone, a building, a temporary restriction published in the middle of a mission. Planning turns a map of allowed space into waypoints the autopilot can fly. The classic pipeline is a grid, an A* search, smoothing, and a replan whenever the map changes; each stage has a property to protect: the safety margin, optimality and flyability.","nuance":"With diagonals allowed, Manhattan counts a diagonal step as 2 instead of 1.41. That overestimate makes A* trust a wrong ordering, so the first path to reach the goal is no longer guaranteed shortest.","objective":"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.","question":"On an 8-connected grid you switch the A* heuristic from octile to Manhattan distance, and some paths get longer. What went wrong?","references":["https://en.wikipedia.org/wiki/A*_search_algorithm","https://en.wikipedia.org/wiki/Any-angle_path_planning","https://ardupilot.org/copter/docs/common-oa-dijkstras.html","https://pkg.go.dev/container/heap"],"reviewAnswer":"Overestimating the remaining cost to the goal","reviewPrompt":"What must an A* heuristic avoid?","sections":[{"body":"Rasterize the area into cells, 5 m here, mark every cell covered by a no-fly zone, then inflate the zones by the safety buffer: the vehicle's size, the position error and the tracking error in wind. Planning on the inflated map lets the planner treat the drone as a point. Cell size is a trade: coarse cells close narrow gaps and waste space, fine cells multiply the work. Altitude can be a third dimension, but small-drone planning is usually 2D at a fixed height, with terrain and ceilings checked separately. ArduPilot does this kind of planning on board: its Dijkstra's object avoidance (OA_TYPE = 2) plans around fences and stay-out zones in Auto, Guided and RTL, and OA_MARGIN_MAX sets how far it stays from them.","title":"From map to grid"},{"body":"A* expands the cell with the lowest f = g + h, where g is the cost so far and h estimates the cost to the goal. If h never overestimates (admissible), the first time the goal is expanded its path is optimal; if h is also consistent, no cell is ever expanded twice. On an 8-connected grid where straight moves cost 1 and diagonals sqrt(2), the octile distance max(dx, dy) + (sqrt(2) - 1) min(dx, dy) is the exact cost on an empty map, so it is both. Euclidean distance is admissible but weaker; Manhattan distance overestimates once diagonals are allowed and silently gives up optimality. Forbid diagonals that cut a blocked corner, and break ties deterministically (here by h, then insertion order) so the same map always yields the same path. container/heap provides the priority queue.","title":"A* and an admissible heuristic"},{"body":"The program blocks a 4 by 10 cell zone (a smaller zone grown by one cell), runs A* and Dijkstra's algorithm (A* with h = 0) from home to a goal 95 m east, prunes the cell path by line of sight and flies the waypoints with a 2 m acceptance radius. After the first waypoint a new restriction is published: the program blocks it, replans from the cell the drone is in, prints the new plan and flies it, then lands at the goal. Clearance records the distance from the drone to the nearest blocked cell on every step.","code":"package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\nconst (\n\tW, H = 24, 14 // grid size in cells\n\tcell = 5.0    // metres per cell\n\talt  = 15.0   // flight altitude, m\n\tsx   = 2      // start cell X\n\tsy   = 7      // start cell Y (home)\n)\n\ntype P struct{ X, Y int }\n\n// Grid marks blocked cells: a no-fly zone already grown by a safety buffer.\ntype Grid [H][W]bool\n\nfunc (g *Grid) Block(x0, y0, x1, y1 int) {\n\tfor y := y0; y <= y1; y++ {\n\t\tfor x := x0; x <= x1; x++ {\n\t\t\tg[y][x] = true\n\t\t}\n\t}\n}\n\nfunc (g *Grid) Free(p P) bool { return p.X >= 0 && p.Y >= 0 && p.X < W && p.Y < H && !g[p.Y][p.X] }\n\n// octile distance: the exact cost on an empty 8-connected grid, so it never\n// overestimates and A* stays optimal.\nfunc octile(a, b P) float64 {\n\tdx, dy := math.Abs(float64(a.X-b.X)), math.Abs(float64(a.Y-b.Y))\n\treturn math.Max(dx, dy) + (math.Sqrt2-1)*math.Min(dx, dy)\n}\n\ntype node struct {\n\tp    P\n\tf, h float64\n\tseq  int\n}\ntype queue []node\n\nfunc (q queue) Len() int { return len(q) }\nfunc (q queue) Less(i, j int) bool {\n\tif q[i].f != q[j].f {\n\t\treturn q[i].f < q[j].f\n\t}\n\tif q[i].h != q[j].h {\n\t\treturn q[i].h < q[j].h\n\t}\n\treturn q[i].seq < q[j].seq\n}\nfunc (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\nfunc (q *queue) Push(x any)   { *q = append(*q, x.(node)) }\nfunc (q *queue) Pop() any {\n\told := *q\n\tn := old[len(old)-1]\n\t*q = old[:len(old)-1]\n\treturn n\n}\n\n// AStar returns the cheapest 8-connected path and how many cells it\n// expanded. With useH false it is Dijkstra's algorithm.\nfunc AStar(g *Grid, start, goal P, useH bool) ([]P, int) {\n\th := func(p P) float64 {\n\t\tif useH {\n\t\t\treturn octile(p, goal)\n\t\t}\n\t\treturn 0\n\t}\n\tcost := map[P]float64{start: 0}\n\tfrom := map[P]P{}\n\tclosed := map[P]bool{}\n\tq := &queue{{p: start, f: h(start), h: h(start)}}\n\tseq, expanded := 0, 0\n\tfor q.Len() > 0 {\n\t\tcur := heap.Pop(q).(node)\n\t\tif closed[cur.p] {\n\t\t\tcontinue\n\t\t}\n\t\tclosed[cur.p] = true\n\t\texpanded++\n\t\tif cur.p == goal {\n\t\t\tpath := []P{goal}\n\t\t\tfor p := goal; p != start; {\n\t\t\t\tp = from[p]\n\t\t\t\tpath = append([]P{p}, path...)\n\t\t\t}\n\t\t\treturn path, expanded\n\t\t}\n\t\tfor dy := -1; dy <= 1; dy++ {\n\t\t\tfor dx := -1; dx <= 1; dx++ {\n\t\t\t\tn := P{cur.p.X + dx, cur.p.Y + dy}\n\t\t\t\tif (dx == 0 && dy == 0) || !g.Free(n) || closed[n] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// no corner cutting: a diagonal needs both side cells free\n\t\t\t\tif dx != 0 && dy != 0 && (!g.Free(P{cur.p.X + dx, cur.p.Y}) || !g.Free(P{cur.p.X, cur.p.Y + dy})) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tc := cost[cur.p] + math.Hypot(float64(dx), float64(dy))\n\t\t\t\tif old, ok := cost[n]; ok && old <= c {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcost[n], from[n] = c, cur.p\n\t\t\t\tseq++\n\t\t\t\theap.Push(q, node{p: n, f: c + h(n), h: h(n), seq: seq})\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, expanded\n}\n\n// Visible samples the straight segment between two cell centres.\nfunc Visible(g *Grid, a, b P) bool {\n\tn := int(math.Ceil(math.Hypot(float64(b.X-a.X), float64(b.Y-a.Y)) * 4))\n\tfor i := 0; i <= n; i++ {\n\t\tt := float64(i) / float64(max(n, 1))\n\t\tx := float64(a.X) + t*float64(b.X-a.X)\n\t\ty := float64(a.Y) + t*float64(b.Y-a.Y)\n\t\tif !g.Free(P{int(math.Round(x)), int(math.Round(y))}) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Prune keeps a cell only when the next one is not in line of sight from\n// the last kept cell.\nfunc Prune(g *Grid, path []P) []P {\n\tout := []P{path[0]}\n\tfor i := 1; i < len(path)-1; i++ {\n\t\tif !Visible(g, out[len(out)-1], path[i+1]) {\n\t\t\tout = append(out, path[i])\n\t\t}\n\t}\n\treturn append(out, path[len(path)-1])\n}\n\nfunc length(path []P) float64 {\n\tsum := 0.0\n\tfor i := 1; i < len(path); i++ {\n\t\tsum += math.Hypot(float64(path[i].X-path[i-1].X), float64(path[i].Y-path[i-1].Y)) * cell\n\t}\n\treturn sum\n}\n\nfunc toWorld(p P) drone.Vec3 {\n\treturn drone.Vec3{X: float64(p.X-sx) * cell, Y: float64(p.Y-sy) * cell, Z: alt}\n}\nfunc toCell(v drone.Vec3) P {\n\treturn P{int(math.Round(v.X/cell)) + sx, int(math.Round(v.Y/cell)) + sy}\n}\n\n// Clearance is the distance from a position to the nearest blocked cell.\nfunc Clearance(g *Grid, v drone.Vec3) float64 {\n\tbest := math.Inf(1)\n\tfor y := 0; y < H; y++ {\n\t\tfor x := 0; x < W; x++ {\n\t\t\tif !g[y][x] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := toWorld(P{x, y})\n\t\t\tdx := math.Max(0, math.Abs(v.X-c.X)-cell/2)\n\t\t\tdy := math.Max(0, math.Abs(v.Y-c.Y)-cell/2)\n\t\t\tbest = math.Min(best, math.Hypot(dx, dy))\n\t\t}\n\t}\n\treturn best\n}\n\nfunc draw(g *Grid, path, wps []P) {\n\trows := make([][]byte, H)\n\tfor y := range rows {\n\t\trows[y] = []byte(strings.Repeat(\".\", W))\n\t\tfor x := 0; x < W; x++ {\n\t\t\tif g[y][x] {\n\t\t\t\trows[y][x] = '#'\n\t\t\t}\n\t\t}\n\t}\n\tfor _, p := range path {\n\t\trows[p.Y][p.X] = '*'\n\t}\n\tfor i, p := range wps {\n\t\trows[p.Y][p.X] = byte('0' + i)\n\t}\n\tfor y := H - 1; y >= 0; y-- { // north up\n\t\tfmt.Println(\"  \" + string(rows[y]))\n\t}\n}\n\nfunc main() {\n\tvar g Grid\n\tg.Block(9, 2, 12, 11) // zone x 10..11, y 3..10 grown by one 5 m cell\n\tstart, goal := P{sx, sy}, P{21, sy}\n\n\tpath, n := AStar(&g, start, goal, true)\n\tdpath, nd := AStar(&g, start, goal, false)\n\twps := Prune(&g, path)\n\tfmt.Printf(\"A*: %d cells, %.1f m, expanded %d cells\\n\", len(path), length(path), n)\n\tfmt.Printf(\"Dijkstra: %d cells, %.1f m, expanded %d cells\\n\", len(dpath), length(dpath), nd)\n\tfmt.Printf(\"pruned to %d waypoints, %.1f m\\n\", len(wps), length(wps))\n\tdraw(&g, path, wps)\n\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: -2, Y: 1}, Gust: 1, MaxSpeed: 8, Seed: 3})\n\td := sim.Drone()\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\td.TakeOff(alt)\n\tsim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })\n\n\tplan, clearance := 1, math.Inf(1)\n\tfor i := 1; i < len(wps); i++ {\n\t\tp := toWorld(wps[i])\n\t\td.GoTo(p)\n\t\tlast := i == len(wps)-1\n\t\tif !sim.RunUntil(90, func(float64) bool {\n\t\t\tclearance = math.Min(clearance, Clearance(&g, d.State().Pos))\n\t\t\tif last {\n\t\t\t\treturn d.Arrived()\n\t\t\t}\n\t\t\treturn d.State().Pos.Sub(p).Len() < 2\n\t\t}) {\n\t\t\tlog.Fatalf(\"waypoint %d not reached\", i)\n\t\t}\n\t\tfmt.Printf(\"plan %d, waypoint %d %v at %.1f s\\n\", plan, i, p, sim.Time())\n\t\tif plan == 1 && i == 1 {\n\t\t\t// A new restriction is published: plan again from here.\n\t\t\tplan = 2\n\t\t\tg.Block(16, 4, 18, 13)\n\t\t\there := toCell(d.State().Pos)\n\t\t\tpath, n = AStar(&g, here, goal, true)\n\t\t\twps = Prune(&g, path)\n\t\t\ti = 0\n\t\t\tfmt.Printf(\"new zone x 16..18, y 4..13: replan from cell %d,%d: %d waypoints, %.1f m, expanded %d\\n\",\n\t\t\t\there.X, here.Y, len(wps), length(wps), n)\n\t\t\tdraw(&g, path, wps)\n\t\t}\n\t}\n\t// Land at the goal: a straight-line RTL from here would cross the zones.\n\td.Land()\n\tsim.RunUntil(60, func(float64) bool {\n\t\tclearance = math.Min(clearance, Clearance(&g, d.State().Pos))\n\t\treturn d.State().Landed\n\t})\n\tfmt.Printf(\"closest approach to a blocked cell: %.1f m\\n\", clearance)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Plan, prune, fly, replan","walkthrough":"A* finds a 20-cell, 115.7 m path over the zone after expanding 85 cells; Dijkstra finds a path of the same 115.7 m but expands 274. Pruning keeps 4 waypoints, the start, two corners above the zone and the goal, and cuts the flight to 110.2 m because straight segments replace the 45 degree staircase. The new zone at x 16..18 closes the northern route, so the replan from cell 9,12 runs down the corridor between the zones and under the new one: 5 waypoints, 108.5 m, 79 cells expanded. The drone lands at (95.3, 0.8, 0.0) and came no closer than 0.6 m to a blocked cell, so the buffer absorbed its tracking error."},{"body":"Grid paths zigzag in 45 degree steps, and a waypoint per cell would make the autopilot slow down at each one. Line-of-sight pruning (string pulling) keeps a cell only when the next cell cannot be seen in a straight line from the last kept one, checking the segment against the inflated grid; any-angle planners such as Theta* fold the same test into the search. The result is never longer than the grid path and never crosses a blocked cell, though it is not guaranteed shortest in continuous space. Convert cell centres to the vehicle's frame, add the altitude, and keep the acceptance radius smaller than the buffer, or corner cutting near a zone eats the margin; ArduPilot's documentation gives the same advice for its waypoint radius and fence margin.","title":"Smoothing and waypoints"},{"body":"Replan from the vehicle's current cell whenever the map changes: a new restriction, an obstacle seen by a sensor, a wind that makes a leg infeasible. Keep flying the old plan only while it is still clear, and make the switch an explicit event in the log. On grids this small a full A* is cheap enough to rerun; on large or frequently changing maps, incremental planners such as D* Lite reuse the previous search. Plan the way back too: a plain RTL flies a straight line home and in this example would cross both zones, which is why the program lands at the goal. ArduPilot can run its Dijkstra planner in RTL, and its SmartRTL mode retraces the path already flown.","title":"Replanning and the way back"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. The console shows both grids; Output replays the flight with every waypoint flown from both plans on the map, the turn at the first waypoint where the replan happened, and the landing at the goal. Move the second zone or switch the heuristic to Manhattan distance and compare the paths and the expanded counts.","title":"Fly it in GopherForge"}],"takeaway":"Inflate no-fly zones by the safety buffer, search the grid with A* and an admissible, consistent heuristic such as the octile distance, prune the path by line of sight into a few waypoints, keep the acceptance radius below the buffer, and replan from the current position whenever the map changes.","title":"Path planning around no-fly zones: A*, line-of-sight pruning and replanning","unitID":"drones-missions","wrongAnswers":["Manhattan distance makes A* expand every cell","Manhattan distance ignores blocked cells"]},{"conceptTag":"drones.fleets","designGuide":{"cautions":["A slow consumer can stall a fan-in unless channels are bounded.","Lockstep tests hide the timing problems of real links."],"cost":"A goroutine and inbox per vehicle, a supervisor loop with a context, and a pairwise separation check sized to position error.","family":"drones","flow":["Goroutine per vehicle","Fan-in tagged telemetry","Supervisor with context","Check pairs every cycle"],"ratings":[],"strengths":["Each vehicle state has exactly one owner, so no locks.","One context cancel stops every vehicle goroutine."]},"hint":"Layered routes cross directly above each other. Which of the two distances still protects them at the crossing point?","id":"drones.fleets","introduction":"Go's concurrency maps naturally onto fleets: every vehicle has its own link, its own state machine and its own failures, and a supervisor watches them all. The hard parts are not the goroutines. They are keeping one slow or broken vehicle from stalling the others, shutting down cleanly, and showing at every moment that no two aircraft are too close, with tests that stay deterministic although the code is concurrent.","nuance":"Either distance is enough. At a crossing the horizontal distance falls to zero and the layer spacing carries the separation, so it must exceed the vertical minimum plus altitude error.","objective":"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.","question":"Under a rule of 10 m horizontal or 4 m vertical separation, when are two drones in a fleet separated?","references":["https://go.dev/blog/pipelines","https://pkg.go.dev/context","https://github.com/bluenviron/gomavlib","https://pkg.go.dev/sync#WaitGroup.Go"],"reviewAnswer":"When horizontal or vertical distance meets its minimum","reviewPrompt":"When are two drones separated?","sections":[{"body":"Give each vehicle a goroutine that owns its link and mission state: it reads that vehicle's telemetry, runs its state machine and emits commands, and nothing else touches that state, so it needs no lock. Telemetry fans in to the supervisor over one channel, tagged with the vehicle's ID, much as every MAVLink frame carries a system ID. With a library such as gomavlib, a node delivers frames from all its endpoints as events on one channel, and a dispatcher fans them out by system ID to the vehicle goroutines. Bound every channel and decide what a slow consumer means: telemetry may be dropped or replaced by the latest sample, commands must never be silently dropped.","title":"One goroutine per vehicle"},{"body":"The supervisor starts the vehicle goroutines with sync.WaitGroup.Go (Go 1.25 and later), hands them a context and cancels it to stop everything: at the end of the mission, on an operator abort, or when an error makes the fleet unable to continue. Every blocking send and receive in a vehicle goroutine also selects on ctx.Done(); otherwise cancel leaves goroutines stuck on a channel nobody reads, and wg.Wait never returns. Decide per error whether it is local (that vehicle returns home, the others carry on) or global (everyone holds). A supervisor that restarts a crashed vehicle goroutine must rebuild its state from fresh telemetry, not from what the old goroutine last believed.","title":"Supervisor, context and shutdown"},{"body":"Separation has two numbers: horizontal and vertical distance. A pair is separated while either one meets its minimum, here 10 m horizontally or 4 m vertically. Altitude layering gives each vehicle its own cruise altitude, so crossing routes are separated vertically by design, and climbs and descents between layers happen away from the crossings. The monitor works on reported positions, so the minimums must include position uncertainty (GPS horizontally, barometer vertically) plus the distance covered in one telemetry period and the reaction time. Track the closest approach per pair, alert before a minimum is lost, and log it: losses of separation are near misses that never appear in a crash count.","title":"Separation assurance"},{"body":"The program adds bravo and charlie to the simulator's alpha and gives them routes that all cross (0, 30), at 20, 25 and 30 m. Each pilot goroutine sees only telemetry and answers only with commands. Every 0.2 s of simulated time the supervisor sends each pilot its vehicle's latest telemetry, collects one report from each, applies the commands in vehicle order and steps the simulation. The separation monitor uses GPS for the horizontal and barometric altitude for the vertical distance, as a real one would.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"sync\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// Command is what a pilot goroutine asks the link to send to its vehicle.\ntype Command struct {\n\tKind   string // \"takeoff\", \"goto\" or \"land\"\n\tTarget drone.Vec3\n}\n\n// Report is one telemetry cycle from a pilot: what it saw, what it wants.\ntype Report struct {\n\tDrone int\n\tTel   drone.Telemetry\n\tCmd   *Command\n}\n\n// Route is one vehicle's job: climb to its layer, fly to a point, land.\ntype Route struct {\n\tLayer float64\n\tTo    drone.Vec3\n}\n\n// pilot runs in its own goroutine. It only sees telemetry and only\n// answers with commands, exactly as it would over a radio link.\nfunc pilot(ctx context.Context, id int, r Route, in <-chan drone.Telemetry, out chan<- Report) {\n\tphase := \"ground\"\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase tel := <-in:\n\t\t\tvar cmd *Command\n\t\t\tdest := drone.Vec3{X: r.To.X, Y: r.To.Y, Z: r.Layer}\n\t\t\tswitch {\n\t\t\tcase phase == \"ground\":\n\t\t\t\tphase, cmd = \"climb\", &Command{Kind: \"takeoff\", Target: drone.Vec3{Z: r.Layer}}\n\t\t\tcase phase == \"climb\" && tel.Mode == drone.Hold:\n\t\t\t\tphase, cmd = \"cruise\", &Command{Kind: \"goto\", Target: dest}\n\t\t\tcase phase == \"cruise\" && tel.GPS.Sub(dest).Horizontal().Len() < 3 && tel.Velocity.Len() < 1:\n\t\t\t\tphase, cmd = \"land\", &Command{Kind: \"land\"}\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase out <- Report{Drone: id, Tel: tel, Cmd: cmd}:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc apply(d *drone.Drone, c Command) error {\n\tswitch c.Kind {\n\tcase \"takeoff\":\n\t\tif err := d.Arm(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn d.TakeOff(c.Target.Z)\n\tcase \"goto\":\n\t\treturn d.GoTo(c.Target)\n\tcase \"land\":\n\t\treturn d.Land()\n\t}\n\treturn fmt.Errorf(\"unknown command %q\", c.Kind)\n}\n\nfunc main() {\n\tsim := drone.New(drone.Config{Wind: drone.Vec3{X: 1.5, Y: -1}, Gust: 1, MaxSpeed: 6, Seed: 21})\n\tsim.AddDrone(\"bravo\", drone.Vec3{X: -20, Y: 30})\n\tsim.AddDrone(\"charlie\", drone.Vec3{X: 15, Y: 45})\n\tdrones := sim.Drones()\n\t// Three routes that all cross (0, 30), one altitude layer each.\n\troutes := []Route{\n\t\t{Layer: 20, To: drone.Vec3{X: 0, Y: 60}},\n\t\t{Layer: 25, To: drone.Vec3{X: 30, Y: 30}},\n\t\t{Layer: 30, To: drone.Vec3{X: -30, Y: 0}},\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\treports := make(chan Report, len(drones))\n\tinboxes := make([]chan drone.Telemetry, len(drones))\n\tvar wg sync.WaitGroup\n\tfor i := range drones {\n\t\tinboxes[i] = make(chan drone.Telemetry)\n\t\twg.Go(func() { pilot(ctx, i, routes[i], inboxes[i], reports) })\n\t}\n\n\ttype pair struct{ min, minH, vAtMinH, t float64 }\n\tpairs := map[[2]int]*pair{}\n\tkeys := [][2]int{{0, 1}, {0, 2}, {1, 2}}\n\tfor _, k := range keys {\n\t\tpairs[k] = &pair{min: math.Inf(1), minH: math.Inf(1)}\n\t}\n\tviolations := 0\n\n\t// The supervisor: one telemetry cycle every 0.2 s of simulated time.\n\tfor sim.Time() < 120 {\n\t\tfor i, d := range drones {\n\t\t\tinboxes[i] <- d.Telemetry()\n\t\t}\n\t\tbatch := make([]Report, len(drones))\n\t\tfor range drones {\n\t\t\tr := <-reports\n\t\t\tbatch[r.Drone] = r // fan-in arrives in any order; index it\n\t\t}\n\t\tfor i, r := range batch { // act in a fixed order\n\t\t\tif r.Cmd == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := apply(drones[i], *r.Cmd); err != nil {\n\t\t\t\tcancel()\n\t\t\t\tlog.Fatalf(\"%s: %v\", drones[i].Name, err)\n\t\t\t}\n\t\t\twhat := r.Cmd.Kind\n\t\t\tswitch r.Cmd.Kind {\n\t\t\tcase \"takeoff\":\n\t\t\t\twhat = fmt.Sprintf(\"take off to the %.0f m layer\", r.Cmd.Target.Z)\n\t\t\tcase \"goto\":\n\t\t\t\twhat = fmt.Sprintf(\"go to %v\", r.Cmd.Target)\n\t\t\t}\n\t\t\tfmt.Printf(\"%5.1f s  %-7s %s\\n\", sim.Time(), drones[i].Name, what)\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\ta, b := batch[k[0]].Tel, batch[k[1]].Tel\n\t\t\tif a.Time == 0 || drones[k[0]].State().Landed && drones[k[1]].State().Landed {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\th := a.GPS.Sub(b.GPS).Horizontal().Len()\n\t\t\tv := math.Abs(a.BaroAlt - b.BaroAlt)\n\t\t\tp := pairs[k]\n\t\t\tif dist := math.Hypot(h, v); dist < p.min {\n\t\t\t\tp.min, p.t = dist, a.Time\n\t\t\t}\n\t\t\tif h < p.minH {\n\t\t\t\tp.minH, p.vAtMinH = h, v\n\t\t\t}\n\t\t\tif h < 10 && v < 4 {\n\t\t\t\tviolations++\n\t\t\t}\n\t\t}\n\t\tlanded := 0\n\t\tfor _, d := range drones {\n\t\t\tif d.State().Landed {\n\t\t\t\tlanded++\n\t\t\t}\n\t\t}\n\t\tif sim.Time() > 1 && landed == len(drones) {\n\t\t\tbreak\n\t\t}\n\t\tsim.Run(0.2, nil)\n\t}\n\tcancel()\n\twg.Wait()\n\n\tfmt.Println(\"separation (rule: 10 m horizontal or 4 m vertical)\")\n\tfor _, k := range keys {\n\t\tp := pairs[k]\n\t\tfmt.Printf(\"  %-7s %-7s closest %4.1f m at %4.1f s; min horizontal %4.1f m with %3.1f m vertical\\n\",\n\t\t\tdrones[k[0]].Name, drones[k[1]].Name, p.min, p.t, p.minH, p.vAtMinH)\n\t}\n\tfmt.Printf(\"  samples breaking the rule: %d\\n\", violations)\n\tif err := sim.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Three drones, three layers","walkthrough":"The commands appear in a fixed order because the supervisor indexes the reports by vehicle and acts in vehicle order, whatever order the goroutines answered in; the output is the same with any GOMAXPROCS and under the race detector. All three cross near (0, 30): alpha and bravo come within 2.0 m horizontally with 4.7 m vertical, alpha and charlie 4.2 m with 9.5 m, bravo and charlie 5.8 m with 4.7 m. No sample breaks the rule, but 4.7 m shows how little of the 5 m layer spacing is left once barometer noise and altitude-hold error are counted."},{"body":"The simulator advances every drone together in one Step, so the program runs in lockstep: telemetry out, commands in, one step. That makes runs repeatable and lets a test assert exact separation figures. Real links are concurrent: telemetry arrives at different rates, packets are lost, one radio is slower than the others, and the supervisor must work with the latest timestamped sample per vehicle instead of waiting for a complete set. Design the production code for that case, with timestamps, staleness checks and no assumptions about order between vehicles, and keep lockstep as the test harness. PX4 and ArduPilot SITL can run several vehicle instances with distinct MAVLink system IDs for the next level of fleet testing.","title":"Deterministic simulation, concurrent reality"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. The replay in Output shows the three drones with their trails crossing over (0, 30), and the altitude strip shows the three layers. Set every layer to 20 m and run again: the count of samples breaking the rule shows what the layering was buying.","title":"Fly it in GopherForge"}],"takeaway":"Give every vehicle a goroutine that owns its link and state, fan telemetry into a supervisor tagged with the vehicle ID, stop everything through one context, and check separation pairwise with horizontal and vertical minimums that include position error. Keep the simulation lockstep and deterministic, and design the real code for concurrent, lossy links.","title":"Fleets from Go: a goroutine per vehicle, telemetry fan-in and separation","unitID":"drones-missions","wrongAnswers":["Only when both distances exceed their minimums","Only when their straight-line distance exceeds 10 m"]},{"conceptTag":"drones.simulation-testing","designGuide":{"cautions":["A simple model can pass what a real airframe fails.","A harness that overrides failsafes tests the wrong program."],"cost":"A deterministic simulator, a scenario table with expectations, an invariant checker and CI time for SITL runs.","family":"drones","flow":["Seed and fixed timestep","Scenarios as table rows","Check invariants per run","SITL, HIL, then field"],"ratings":[],"strengths":["Hundreds of flights per second, reproducible to the last digit.","A new world costs one table row; the invariants stay."]},"hint":"Ask which properties must hold in every world whatever the tuning: the fence, the landing, the speed, the reserve.","id":"drones.simulation-testing","introduction":"Drone software cannot be tested the way it fails: nobody crashes an aircraft to find out whether the fence works. Most of its behaviour can be tested on a laptop in milliseconds, provided the simulation is deterministic, the scenarios are a table and the pass criteria are invariants rather than golden logs. The same scenarios then run against the real flight stack in SITL, on the real board in HIL, and only after that in the field.","nuance":"Golden logs change with every harmless tweak. Invariants such as never leaving the fence and landing near home must always hold, and each row adds its expected outcome, such as a safe abort on low battery.","objective":"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.","question":"Your mission test compares the whole printed flight log with a golden file and breaks after every tuning change. What should it assert instead?","references":["https://go.dev/wiki/TableDrivenTests","https://pkg.go.dev/testing/synctest","https://ardupilot.org/dev/docs/sitl-simulator-software-in-the-loop.html","https://docs.px4.io/main/en/simulation/"],"reviewAnswer":"Safety invariants, plus each row's expected outcome","reviewPrompt":"What do scenario tests assert?","sections":[{"body":"A failure you cannot reproduce is a rumour. Make every source of variation an input: seed the random number generator, advance a fixed timestep instead of reading the clock, iterate slices rather than maps where order reaches the output, and keep goroutine scheduling out of the results, as the fleet supervisor did. A run then becomes a pure function of its scenario, and rerunning it must give the same final state to the last bit. The simulator used here is deterministic by construction, since time advances only in Step and all noise comes from the seeded source, which is what lets the program below print exact values and compare two runs with ==.","title":"Determinism first"},{"body":"Describe each world as a row: wind, gusts, battery, seed and what the mission is expected to do. Include the boring case, each stress on its own (crosswind, gusts, a storm, a wind beyond the airframe's top airspeed, a low battery) and then combinations. The expected outcome belongs to the row: with 30 percent in a 6 m/s wind the correct behaviour is an aborted survey that lands safely at home, and a test demanding completion there would test the wrong thing. Every row also runs the same invariants, so a new scenario costs one line. Never let the test harness override a failsafe: once the autopilot has switched to RTL or Land, the mission code must stop commanding, or the test exercises a program you would never fly. Here Arrived is true only while the autopilot holds the last target, within 1 m and nearly stopped, so the mission sends the next waypoint only after Arrived; a failsafe in command, or a vehicle that cannot hold position, stops the mission.","title":"Scenarios as a table"},{"body":"The program flies a 60 m survey square inside a fence that leaves 2 m around the corners, in eight worlds. A watch function records the highest horizontal speed, the furthest excursion outside the fence and the vertical speed just before touchdown; Check compares the result with the invariants (landed without crashing, never outside the fence, at most 10.5 m/s, touchdown at most 1.5 m/s, within 3 m of home, at least 10 percent left) and with the row's expected outcome. Then it flies the gusty row twice and compares the final states.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"strings\"\n\n\t\"gopherforge.app/drone\"\n)\n\n// The survey corners are at 30 m; the fence leaves a 2 m margin.\nvar fence = []drone.Vec3{{X: -32, Y: -32}, {X: 32, Y: -32}, {X: 32, Y: 32}, {X: -32, Y: 32}}\n\n// Scenario is one row of the test matrix: the world the mission flies in\n// and whether the mission is expected to finish or to be aborted safely.\ntype Scenario struct {\n\tName     string\n\tWind     drone.Vec3\n\tGust     float64\n\tBattery  float64\n\tSeed     int64\n\tComplete bool\n}\n\n// Result is what the run measured; invariants are checked against it.\ntype Result struct {\n\tWaypoints int     // survey corners reached\n\tMaxSpeed  float64 // horizontal, m/s\n\tOutside   float64 // furthest distance outside the fence, m\n\tTouchdown float64 // vertical speed at touchdown, m/s\n\tHomeDist  float64 // landing distance from home, m\n\tBattery   float64 // at the end, %\n\tCrashed   bool\n\tFinal     drone.State\n}\n\n// distance from p to the nearest fence edge\nfunc edgeDistance(poly []drone.Vec3, p drone.Vec3) float64 {\n\tbest := math.Inf(1)\n\tfor i := range poly {\n\t\ta, b := poly[i], poly[(i+1)%len(poly)]\n\t\tab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()\n\t\tt := math.Max(0, math.Min(1, (ab.X*ap.X+ab.Y*ap.Y)/(ab.X*ab.X+ab.Y*ab.Y)))\n\t\tbest = math.Min(best, ap.Sub(ab.Scale(t)).Len())\n\t}\n\treturn best\n}\n\n// Fly runs the survey mission in one scenario and measures it.\nfunc Fly(sc Scenario) (*drone.Sim, Result) {\n\tsim := drone.New(drone.Config{Wind: sc.Wind, Gust: sc.Gust, Battery: sc.Battery, MaxSpeed: 10, Geofence: fence, Seed: sc.Seed})\n\td := sim.Drone()\n\tvar r Result\n\tprevVz := 0.0\n\twatch := func() {\n\t\tst := d.State()\n\t\tr.MaxSpeed = math.Max(r.MaxSpeed, st.Vel.Horizontal().Len())\n\t\tif !drone.Inside(fence, st.Pos) {\n\t\t\tr.Outside = math.Max(r.Outside, edgeDistance(fence, st.Pos))\n\t\t}\n\t\tif !st.Landed {\n\t\t\tprevVz = st.Vel.Z\n\t\t}\n\t}\n\tuntil := func(limit float64, done func() bool) bool {\n\t\treturn sim.RunUntil(limit, func(float64) bool { watch(); return done() })\n\t}\n\tif err := d.Arm(); err != nil {\n\t\tlog.Fatalf(\"%s: %v\", sc.Name, err)\n\t}\n\td.TakeOff(15)\n\tuntil(30, d.Arrived)\n\tfor _, p := range []drone.Vec3{{X: 30, Y: -30, Z: 15}, {X: 30, Y: 30, Z: 15}, {X: -30, Y: 30, Z: 15}, {X: -30, Y: -30, Z: 15}} {\n\t\t// Arrived means the autopilot holds our last target. Otherwise a\n\t\t// failsafe owns the vehicle or it cannot hold: never override it.\n\t\tif !d.Arrived() {\n\t\t\tbreak\n\t\t}\n\t\td.GoTo(p)\n\t\tuntil(90, func() bool { return d.State().Mode != drone.GoingTo })\n\t\tif d.Arrived() {\n\t\t\tr.Waypoints++\n\t\t}\n\t}\n\tif d.Arrived() {\n\t\td.ReturnHome()\n\t}\n\tuntil(240, func() bool { s := d.State(); return s.Landed || s.Mode == drone.Crashed })\n\tst := d.State()\n\tr.Touchdown, r.HomeDist, r.Battery = -prevVz, st.Pos.Horizontal().Len(), st.Battery\n\tr.Crashed, r.Final = st.Mode == drone.Crashed, st\n\treturn sim, r\n}\n\n// Check returns the invariants and expectations a run broke.\nfunc Check(sc Scenario, r Result) []string {\n\tvar failed []string\n\tif sc.Complete != (r.Waypoints == 4) {\n\t\tfailed = append(failed, \"mission\")\n\t}\n\tif r.Crashed || !r.Final.Landed {\n\t\tfailed = append(failed, \"landed\")\n\t}\n\tif r.Outside > 0 {\n\t\tfailed = append(failed, \"fence\")\n\t}\n\tif r.MaxSpeed > 10.5 {\n\t\tfailed = append(failed, \"speed\")\n\t}\n\tif r.Touchdown > 1.5 {\n\t\tfailed = append(failed, \"touchdown\")\n\t}\n\tif r.HomeDist > 3 {\n\t\tfailed = append(failed, \"home\")\n\t}\n\tif r.Battery < 10 {\n\t\tfailed = append(failed, \"reserve\")\n\t}\n\treturn failed\n}\n\nfunc main() {\n\tscenarios := []Scenario{\n\t\t{Name: \"calm\", Battery: 100, Seed: 1, Complete: true},\n\t\t{Name: \"crosswind 5\", Wind: drone.Vec3{Y: 5}, Battery: 100, Seed: 1, Complete: true},\n\t\t{Name: \"gusty 6+3\", Wind: drone.Vec3{X: -6}, Gust: 3, Battery: 100, Seed: 2, Complete: true},\n\t\t{Name: \"storm 10+4\", Wind: drone.Vec3{X: 10}, Gust: 4, Battery: 100, Seed: 3, Complete: true},\n\t\t{Name: \"gale 14+4\", Wind: drone.Vec3{X: 14}, Gust: 4, Battery: 100, Seed: 3, Complete: true},\n\t\t{Name: \"wind 20\", Wind: drone.Vec3{X: 20}, Battery: 100, Seed: 3, Complete: true},\n\t\t{Name: \"battery 40\", Battery: 40, Seed: 4, Complete: true},\n\t\t{Name: \"battery 30 wind\", Wind: drone.Vec3{X: 6}, Battery: 30, Seed: 5, Complete: false},\n\t}\n\tfmt.Printf(\"%-16s  %-3s  %4s  %8s  %5s  %7s  %6s  %s\\n\", \"scenario\", \"wps\", \"vmax\", \"outside\", \"touch\", \"home\", \"batt\", \"result\")\n\tvar last *drone.Sim\n\tfor _, sc := range scenarios {\n\t\tsim, r := Fly(sc)\n\t\tverdict := \"PASS\"\n\t\tif failed := Check(sc, r); len(failed) > 0 {\n\t\t\tverdict = \"FAIL \" + strings.Join(failed, \",\")\n\t\t}\n\t\tfmt.Printf(\"%-16s  %d/4  %4.1f  %6.2f m  %5.1f  %5.1f m  %5.1f%%  %s\\n\",\n\t\t\tsc.Name, r.Waypoints, r.MaxSpeed, r.Outside, r.Touchdown, r.HomeDist, r.Battery, verdict)\n\t\tlast = sim\n\t}\n\n\t// Same seed, same inputs, same flight: bit for bit.\n\t_, a := Fly(scenarios[2])\n\t_, b := Fly(scenarios[2])\n\tfmt.Printf(\"gusty run twice: identical final state %v (%v, %.4f%%)\\n\", a.Final == b.Final, a.Final.Pos, a.Final.Battery)\n\n\tif err := last.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"A scenario matrix","walkthrough":"Six rows pass, and the battery column shows what wind costs: 85.7 percent left in calm air, 74.1 after the same survey in storm 10+4. In gale 14+4 the drone reaches the first corner, then wind and a gust push it 1.56 m past the east fence on the next leg; the fence failsafe brings it home and the row reports FAIL mission,fence. The fix belongs in the plan, a wider margin or a slower approach, not in the test. wind 20 beats the airframe's 18 m/s airspeed: after the climb the drone drifts east at 2.0 m/s, its top speed in the whole run, so Arrived never reports a hold and the mission never sends the first corner. It drifts out of the fence, RTL cannot make headway, the 10 percent forced landing puts it down 268.9 m downwind with 1.6 percent, and four checks fail. battery 40 completes with 25.7 percent; battery 30 wind is expected to abort, reaches 2 corners and lands 0.3 m from home with 15.8, so it passes. Touchdown is 0.9 m/s in every row. The gusty run twice ends in an identical state, battery 81.3682 percent, and the replay is the last row."},{"body":"In a repository the same table becomes a table-driven test: t.Run gives each scenario a name that go test -run can select, and t.Parallel is safe because every scenario builds its own simulator. Fuzzing extends the table: go test -fuzz can generate wind, gust and battery values and keeps any input that breaks an invariant as a regression case under testdata. For code with timeouts, such as a link-loss watchdog, testing/synctest runs the test in a bubble with a fake clock, so a 5 s timeout passes instantly and the same way every time.","code":"func TestSurveyScenarios(t *testing.T) {\n\tfor _, sc := range scenarios {\n\t\tt.Run(sc.Name, func(t *testing.T) {\n\t\t\tt.Parallel() // each scenario builds its own Sim\n\t\t\t_, r := Fly(sc)\n\t\t\tfor _, broken := range Check(sc, r) {\n\t\t\t\tt.Errorf(\"%s: %+v\", broken, r)\n\t\t\t}\n\t\t})\n\t}\n}","language":"go","title":"From a program to go test","walkthrough":"Each row becomes a subtest named after its scenario, so go test -run 'TestSurveyScenarios/storm' reruns exactly one world. The subtests can run in parallel because Fly creates a new simulator per call, and every broken invariant is reported with the measured result instead of stopping at the first one."},{"body":"A Go simulator tests your ground-station and mission logic against a simplified vehicle. Software in the loop runs the real flight stack on your computer against a physics model: ArduPilot's SITL binary has built-in physics and sim_vehicle.py starts MAVProxy, which forwards MAVLink to ground stations on UDP port 14550, while PX4 runs in lockstep with Gazebo or its SIH model and can run faster than real time. Point your Go code at that MAVLink port and the same scenarios now exercise the real autopilot's mission handling and failsafes. Hardware in the loop runs the flight stack on the real flight controller with simulated sensors and catches timing and driver problems. In CI, run the Go scenarios on every commit, SITL on merges or nightly, HIL before releases, and field tests with a pilot ready to take over last.","title":"SITL, HIL and CI"},{"body":"In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run: the console prints the matrix and Output replays the last scenario, the low-battery abort with its return home. The template's mission_test.go already shows the testing side; move the scenario table into a _test.go file as a table-driven test and tap Test to run it the way go test does.","title":"Fly it in GopherForge"}],"takeaway":"Make the simulation a pure function of its inputs, describe worlds as table rows with expected outcomes, and check safety invariants on every run instead of comparing golden logs. Then climb the pyramid: Go scenarios on every commit, SITL with the real flight stack, HIL on the real board, and the field last.","title":"Testing drone software: seeded scenarios, invariants, SITL, HIL and CI","unitID":"drones-missions","wrongAnswers":["Only the final position, with no other checks","Only that the program exits without an error"]}],"revision":"2026-12-01.1","schemaVersion":1,"solutions":{},"units":[{"id":"drones-foundations","lessons":[{"conceptTags":["drones.architecture"],"explanation":"A drone that flies itself is several computers that trust each other only so far. A microcontroller runs the flight controller firmware and keeps the aircraft upright hundreds of times a second; a Linux computer on board may run mission logic, cameras and networking; a ground control station shows the operator what is happening; and a backend may coordinate many vehicles. Go is a strong fit for the last three and a poor fit for the first, and the reasons explain most design choices in this course.","id":"drones.architecture","objective":"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.","task":{"reading":{}},"title":"Drone software architecture: flight controller, companion computer, ground station and fleet backend"},{"conceptTags":["drones.mavlink-frames"],"explanation":"MAVLink is the protocol PX4, ArduPilot, QGroundControl and most drone tooling speak. It is deliberately small: a 10-byte header, a payload of fixed-size little-endian fields and a 2-byte checksum, designed for slow and lossy serial radios. Building a frame by hand once is the best way to understand what every library does for you, and why one wrong byte or a mismatched message definition makes frames silently disappear.","id":"drones.mavlink-frames","objective":"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.","task":{"reading":{}},"title":"MAVLink v2 frames: header, truncated payload, CRC_EXTRA and signing"},{"conceptTags":["drones.telemetry-streams"],"explanation":"A vehicle does not answer questions about its position; it streams messages at configured rates and the ground station keeps the latest value of each. That design is efficient on a narrow radio link, but it means the newest value you hold may be seconds old. A ground station that shows a position without knowing its age, or calls a link healthy because heartbeats still arrive, is behind many confusing incidents.","id":"drones.telemetry-streams","objective":"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.","task":{"reading":{}},"title":"Telemetry streams: message rates, GLOBAL_POSITION_INT and stale-data detection"},{"conceptTags":["drones.coordinates"],"explanation":"GPS reports latitude, longitude and altitude on the WGS84 ellipsoid; controllers work in metres in a local frame; MAVLink and the flight stacks use NED while ROS and this simulator use ENU. Every drone codebase converts between them, and a swapped axis, a wrong sign or a missing cos(latitude) produces a vehicle that flies confidently to the wrong place. The conversions are short; knowing their error budget is the real skill.","id":"drones.coordinates","objective":"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.","task":{"reading":{}},"title":"Coordinates for drones: WGS84, ENU and NED, haversine and local tangent planes"},{"conceptTags":["drones.ground-station"],"explanation":"A ground station is a small concurrent system: bytes arrive whenever the radio delivers them, heartbeats must go out on time whether or not anything arrives, operator commands interleave with both, and the link can vanish at any moment. Goroutines, channels, select and context map onto that shape directly. The hard parts are deciding who owns what and making sure every goroutine stops when the link or the program ends.","id":"drones.ground-station","objective":"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.","task":{"reading":{}},"title":"A ground station in Go: reader goroutine, heartbeat, context and link-loss timeouts"},{"conceptTags":["drones.telemetry-noise"],"explanation":"Every number a drone reports is an estimate built from imperfect sensors. GPS wanders by metres, a barometer measures altitude changes finely but drifts with the weather, and an IMU measures motion hundreds of times a second but drifts when integrated. Simulation gives you what real flights never do, the truth, so you can measure exactly how wrong each sensor is and in which way.","id":"drones.telemetry-noise","objective":"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.","task":{"reading":{}},"title":"Sensors and noise: GPS, barometer and IMU, truth against measurement, RMSE and bias"}],"summary":"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.","title":"Drone software: architecture, MAVLink and telemetry","translationNote":"Programs fly gopherforge.app/drone, a deterministic simulator bundled with GopherForge, and Output replays each saved flight. Real vehicles speak MAVLink to PX4 or ArduPilot; test against their simulators before any hardware."},{"id":"drones-control","lessons":[{"conceptTags":["drones.pid-altitude"],"explanation":"SetThrust hands the program the collective thrust: about 0.5 hovers, more climbs, less sinks, and nothing else holds the altitude. Thrust sets vertical acceleration while you care about position, so the plant is a double integrator with a little drag, the simplest plant on which a naive controller rings. This lesson builds the PID found in every flight stack's inner loops, flies four variants of it through the same 10 m step on identical simulators, and measures what each term buys.","id":"drones.pid-altitude","objective":"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.","task":{"reading":{}},"title":"PID altitude control: P, I and D on the collective thrust"},{"conceptTags":["drones.cascaded-control"],"explanation":"No flight stack controls position with one big loop. PX4 and ArduPilot nest them: position error becomes a velocity setpoint, velocity error an acceleration and tilt, attitude error a body rate, rate error a torque for the mixer. Each loop only has to control something that already responds quickly, because the loop inside it made it so. A companion computer running Go usually sits at the top of this cascade and sends position or velocity setpoints; this lesson writes that outer loop, holds a point in a 4 m/s wind and then follows a target that moves into the wind.","id":"drones.cascaded-control","objective":"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.","task":{"reading":{}},"title":"Cascaded control: a position loop on top of a velocity loop"},{"conceptTags":["drones.complementary-filter"],"explanation":"Sensors on a drone are either fast and smooth but drifting, or absolute but noisy and slow. Integrating an inertial vertical velocity gives a clean altitude that walks away over time; the barometer never walks away but jumps by tens of centimetres from sample to sample. A complementary filter takes the high frequencies from the first and the low frequencies from the second, with one parameter, the crossover time constant. It costs a few multiplications per step and is the right first estimator to write before a Kalman filter.","id":"drones.complementary-filter","objective":"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.","task":{"reading":{}},"title":"Complementary filter: fusing a fast drifting signal with a slow noisy one"},{"conceptTags":["drones.kalman-filter"],"explanation":"A complementary filter has a fixed blend. A Kalman filter computes the blend at every step from its own uncertainty: right after start-up it trusts the measurements almost completely, once it has converged it leans on its model, and it weighs a 1.2 m GPS altitude against a 0.3 m barometer by their variances. It also estimates states it does not measure, such as the climb rate from altitude samples alone, fuses a direct measurement of them when one exists, and says how surprising each sample is, which is the basis for rejecting glitches. PX4's EKF2 and ArduPilot's EKF3 run the same predict-update cycle with many more states.","id":"drones.kalman-filter","objective":"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.","task":{"reading":{}},"title":"A Kalman filter for altitude and climb rate"},{"conceptTags":["drones.loop-timing"],"explanation":"A control loop assumes its dt. When an iteration starts late, the integral and derivative terms are computed with the wrong time step, and a burst of catch-up iterations is worse than a skipped one. Go is a good language for the 10 to 50 Hz supervisory loops of a companion computer or ground station and the wrong one for the kilohertz rate loop inside a flight controller. This lesson runs three loop styles on a virtual clock, so the results are the same on every run, then counts the heap allocations of two versions of a loop body.","id":"drones.loop-timing","objective":"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.","task":{"reading":{}},"title":"Fixed-rate loops in Go: tickers, jitter, GC and allocations"},{"conceptTags":["drones.motor-mixing"],"explanation":"Below the rate controller sits the mixer, which PX4 calls control allocation. It knows where each rotor is and which way it spins, and turns four numbers, thrust and three torques, into four motor commands. That is a matrix multiplication until a motor reaches 0 or 1. Then something has to give, and what gives decides whether the vehicle keeps its attitude or rolls over. This lesson writes the mixer, the naive clip and a desaturation with explicit priorities.","id":"drones.motor-mixing","objective":"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.","task":{"reading":{}},"title":"Motor mixing for a quad X: thrust and torques to four motors"},{"conceptTags":["drones.flight-modes"],"explanation":"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.","id":"drones.flight-modes","objective":"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.","task":{"reading":{}},"title":"Flight modes as an explicit state machine"}],"summary":"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.","title":"Flight control: PID, cascades, filters and loops","translationNote":"Control code runs against the simulator's physics: tilt-limited thrust, drag on airspeed, wind and gusts and a battery. Gains that work here are a starting point, not a tune for a real airframe."},{"id":"drones-missions","lessons":[{"conceptTags":["drones.waypoint-missions"],"explanation":"An autonomous flight is a list of numbered mission items that the flight controller executes one after another: take off, fly to a point, wait, come back, land. The ground station builds that list, moves it onto the vehicle intact over a lossy radio link, and then watches progress. Each step has a classic failure: a waypoint that is never reached, an upload that leaves half of the old mission on board, a survey whose legs leave gaps between camera footprints.","id":"drones.waypoint-missions","objective":"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.","task":{"reading":{}},"title":"Waypoint missions: mission items, the MAVLink upload protocol and a survey pattern"},{"conceptTags":["drones.geofencing"],"explanation":"A geofence stands between a software bug, a gust or a confused operator and an airspace infringement. Most flight stacks act only once the vehicle is already outside, and a multicopter at 8 m/s needs several metres to stop, so where the fence acts matters as much as where it is drawn. The geometry is short; the edge cases and the physics are where fences fail.","id":"drones.geofencing","objective":"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.","task":{"reading":{}},"title":"Geofencing: inclusion and exclusion polygons, ray casting and predicting a breach"},{"conceptTags":["drones.failsafes"],"explanation":"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.","id":"drones.failsafes","objective":"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.","task":{"reading":{}},"title":"Failsafes: battery energy budgets, link-loss timeouts and which action wins"},{"conceptTags":["drones.path-planning"],"explanation":"A straight line from take-off to destination is the shortest path until something is in the way: a stay-out zone, a building, a temporary restriction published in the middle of a mission. Planning turns a map of allowed space into waypoints the autopilot can fly. The classic pipeline is a grid, an A* search, smoothing, and a replan whenever the map changes; each stage has a property to protect: the safety margin, optimality and flyability.","id":"drones.path-planning","objective":"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.","task":{"reading":{}},"title":"Path planning around no-fly zones: A*, line-of-sight pruning and replanning"},{"conceptTags":["drones.fleets"],"explanation":"Go's concurrency maps naturally onto fleets: every vehicle has its own link, its own state machine and its own failures, and a supervisor watches them all. The hard parts are not the goroutines. They are keeping one slow or broken vehicle from stalling the others, shutting down cleanly, and showing at every moment that no two aircraft are too close, with tests that stay deterministic although the code is concurrent.","id":"drones.fleets","objective":"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.","task":{"reading":{}},"title":"Fleets from Go: a goroutine per vehicle, telemetry fan-in and separation"},{"conceptTags":["drones.simulation-testing"],"explanation":"Drone software cannot be tested the way it fails: nobody crashes an aircraft to find out whether the fence works. Most of its behaviour can be tested on a laptop in milliseconds, provided the simulation is deterministic, the scenarios are a table and the pass criteria are invariants rather than golden logs. The same scenarios then run against the real flight stack in SITL, on the real board in HIL, and only after that in the field.","id":"drones.simulation-testing","objective":"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.","task":{"reading":{}},"title":"Testing drone software: seeded scenarios, invariants, SITL, HIL and CI"}],"summary":"Waypoint missions and the MAVLink mission protocol, geofences, failsafes and energy budgets, A* around no-fly zones, fleets with goroutines, and seeded scenario tests.","title":"Missions, safety and fleets","translationNote":"Before flying anything real, follow your local rules: registration, remote ID, altitude limits and keeping the drone in sight. Simulation is where drone code should fail first."}]}