PID, failsafe and firmware

Separates the teaching equations from ArduCopter SITL results and reads the reasons for mode changes, through the reading lesson and the previously checked practice kit, with steps and limitations

Last updated:

A development board connected to a debugger, beside a log graph and an oscilloscope, on a control-systems analysis bench
A conceptual illustration generated by AI; it is not a screenshot or a device model with confirmed support

Before you start

Objective: separate the teaching equations from ArduCopter SITL results and read the reasons for mode changes Prerequisites: the lessons on sensors, units, time and reading logs Estimated practice time: 90 minutes, a time proposed by the authors and not yet measured with real learners

Check your understanding: cite the time/mode in the log and state that real flight was not confirmed. Use the earlier results to support your study. A successful compile or simulation does not confirm the board or real flight

View the whole learning path · Review sensors and communication

From measured values to thrust commands

The short path is IMU → state estimation → error → controller → command allocation → ESC/motor . A state estimator such as an EKF fuses data with its uncertainty and checks data quality before the controller uses attitude/position values; see PX4 EKF v1.16

Attitude control often has several layers. The outer loop turns the attitude error into a desired rotation rate; the inner loop compares that rate with the gyro and computes the control command, which is then allocated according to the airframe geometry and actuators. So you must read which variables each loop receives and sends; the command is not always a 'target motor RPM'

Diagram: the outer loop controls attitude → the inner loop controls rotation rate → command allocation → actuators, with feedback data and logs

A simplified diagram of several control loops, where the measured data feeds back into the loop that uses that variable; the realistic graph image at the start of the lesson is not test evidence

PID term Role Limitations to study
P Responds to the current error A gain that is too high may cause oscillation
I Accumulates error to remove steady-state offset Integral windup must be handled when the command saturates
D Responds to the rate of change of the variable used in the calculation It can amplify noise and usually needs filtering; it is not an exact predictor of the future

Discrete mathematical example: I[k] = I[k-1] + e[k] × dt and u[k] = Kp × e[k] + Ki × I[k] + Kd × (e[k] - e[k-1]) / dt are used only to understand the relationships. dt must be positive and consistent with the actual sampling time. A working system must consider output limits, anti-windup, filtering, and taking the derivative from the measured value according to that controller's structure. Do not take the simplified formula and fly with it without these parts

Failsafe must relate to the flight state

Define the abnormal causes and the response before testing, such as loss of the control signal, untrustworthy sensor data or low power. Separate the states disarmed, armed on the ground, and in flight. Cutting the motors immediately suits some bench tests, but in flight it may make the aircraft fall. A real system may use Hold, Return or Land depending on conditions and settings; see PX4 safety/failsafe and the manual of the firmware used

Before testing hardware, use SITL to check triggers, state transitions and the recorded reasons. Simulated data loss should be able to stop the run or change the mode as planned; avoid creating real faults just to get a log

Download the timing, PID and failsafe exercises for PC

Download the PC practice kit and answer key (ZIP) · Blank worksheet (CSV) · Combined answer key (JSON) · File list and SHA-256

Use Python 3.11 or later and the standard library from the same ZIP as the applied lesson; no STM32 is needed. The purpose is to read cause and effect in the log before choosing firmware test tools. The program passed repeated trials on Windows Python 3.11/3.14 and Ubuntu Python 3.12. This one-axis model was defined by the developers for teaching; it did not run PX4/ArduPilot or SITL

  1. Read the protocol and check the practice kit: extract the ZIP, open a terminal in that folder, read README.md/protocol.json , then run python -m unittest discover -s . -v . Use python3 instead as your system requires
  2. Create a baseline, then change the cause one case at a time: run the four commands below; each folder can have control-log.csv and summary.json
  3. Trace the cause from the time: compare scheduled_ms, start_ms, dt_ms, finish_ms and missed_deadline before looking at the setpoint, measured angle/rate, PID terms, integral and command
  4. Record the evidence: fill in the worksheet with the log rows showing saturation, integral hold or STOP_SIM , then compare with answers/control-* . Changing the gain or conditions is the learner's own experiment and must keep its protocol separate from the original answer key
python control_lab.py --scenario healthy --output results/control-healthy
python control_lab.py --scenario overload --output results/control-overload
python control_lab.py --scenario saturation --output results/control-saturation
python control_lab.py --scenario data-loss --output results/control-data-loss

Model and units: every case has 601 ticks over 0–6 seconds with a 10 ms period, using rate_next = rate + (u - 0.8 × rate) × dt and then angle_next = angle + rate_next × dt , where angle is in deg, rate in deg/s and u in deg/s² in the teaching equations, not an ESC/RPM command. The state value at tick start is an ideal sensor with no noise or acquisition latency. The model moves with the previous command throughout the interval dt actual before computing the new command

The PID uses Kp=4 s⁻², Ki=1 s⁻³, Kd=2.5 s⁻¹ and takes the derivative from the measured rate: u = Kp × error + Ki × integral - Kd × rate It limits the output to ±60 deg/s² and the integral to ±20 deg·s, stops accumulating when the candidate output saturates and the error pushes further in the same direction, but lets the integral relax. These bounds and gains belong to the exercise; if you study a real controller, read the structure and filtering of PX4 controller diagrams v1.16 separately from this equation

Graph of a synthetic one-axis controller's results, showing angle, data age, command limit, work delay and the STOP_SIM threshold

A graph from a log generated by the model; it is not an STM32 benchmark or a flight result. Open the full-size controller graph to enlarge the details

Case Variable changed Evidence to find
healthy Target 15° at 1 s; work 6 ms per tick missed deadline 0; the output touches the limit for 1 tick
overload Combined communication work makes the work take 12 ms at ticks 40, 80, …, 600 missed deadline 15; maximum delay 2 ms; dt in some intervals 12/8 ms
saturation Target increased to 30° the output touches the limit for 36 ticks and the integral holds for 36 ticks
data-loss No new sample from 3 s; the last value is at 2.99 s the age reaches 120 ms at 3.11 s and enters STOP_SIM

The scheduling ledger makes the next tick's work wait for the previous work to finish. The term missed deadline is used when it finishes after nominal start+10 ms; finishing exactly on the boundary still passes. The first row uses dt nominal 10 ms because there is no earlier start. The workload figures are assumptions, not times captured from a real CPU

STOP_SIM latches when the data age reaches 120 ms or more and makes u=0 only in the model while keeping the integral. New data does not start the run again by itself. This policy cannot replace a failsafe in flight. A real response must relate to the flight state and be checked separately in firmware/SITL. The practice-set pass criterion is being able to explain the time, units, limits and the reason for state changes from the CSV; do not use the graph or RMSE to certify flight

Practise reading PID and the stop reason from the log, step by step

Objective: explain the deadline, saturated commands and the reason for state changes from the evidence Prerequisites: read units/timestamps from the IMU and message practice kit Suggested time: 45–60 minutes, a recommended time not yet measured with real learners. You can use a calculator / CSV reader; no board or extra package is needed

A guide diagram: read the units and time, then look at the PID and the old data, with the model's STOP_SIM boundary

The guide figure accompanies the earlier graph and realistic image. The data are the already-published synthetic PC results, with no new firmware/SITL/hardware run

Download how to do it, the 8-question worksheet, the 20-row selected log, the totals of the four cases and protocol before opening the answer key with reasoning Check the source/SHA-256 in manifest evidence.csv It keeps the original column values, with the ZIP member position and a line number counting the header as 1; whole-run totals use the full CSV / existing summary

1. Read the units and the real time in the model · C1–C2

Write the units of angle/rate/u/integral and explain how u differs from an ESC command. In the overload case, trace ticks 40–42: when the work finishes, where the deadline is, and why dt is 12 then 8 ms even though the period is set to 10 ms. Hint: separate the scheduled start time (scheduled) from the actual start (start) and the finish boundary at scheduled+10 before counting missed

2. Check P/I/D and the command limits · C3–C4

Calculate the candidate integral at healthy tick 100 and saturation tick 100, then compare it with the integral actually stored and the u that was limited. Use the totals of the four cases to answer whether healthy can have output_at_limit and why you still need to read integral_held separately from the command. The units/gains and anti-windup belong to the exercise and do not certify a flight controller's tuning

3. Tie the data age to the stop reason · C5–C7

Use data-loss ticks 310/311 to calculate the age from the last sample at 2,990 ms, then check the boundary age≥120 . Try to answer whether, after setting u=0, the angle/rate becomes zero immediately, using ticks 311/312/600, and explain why the integral holds at 291 but STOP_SIM at 290. Hint: read mode/reason before interpreting P/I/D, because STOP_SIM forces u to 0 and keeps the integral without continuing to sum the PID

4. Write a conclusion with its limits · C8

Separate what the PC log confirms from CPU timing/IRQ/sensors/actuators and flight, which have not been measured. Then read the earlier ArduCopter SITL results below as another body of evidence. Selecting 20 rows helps point out the key places but does not replace the 601-row totals per case. Recovery of data is absent from the data-loss fixture, so do not claim that the trace tested restarting by itself

Self-check: 2 points per question proposed (1 answer + 1 reason/unit/limit), 16 in total; use the answer key to choose topics to review. There is no criterion certifying flight readiness and no real learner results. Continue to MCU and Sim activities when you can separate the teaching equations from the firmware results

Try a GCS failsafe with real ArduCopter in SITL

Download the SITL failsafe kit and logs (ZIP) · Worksheet (CSV) · Answer key (JSON) · Source build result · File list and SHA-256

Objective: check that the firmware changes from GUIDED to LAND when the GCS heartbeat is lost according to the setting, then separate the cause from the tester's command. This kit ran the official ArduCopter 4.7.1 Linux x86_64 with the quad model on real Ubuntu/WSL on 1 October 2026. Unlike the one-axis equations above, there is one run per case, using a network namespace that has only loopback and no connection to real devices

Source check: compiled the tag Copter-4.7.1 commit dbe792162d06cab66c3475fd5556bf7a120f119e with GCC 13.3.0 as SITL, and it passed, without modifying the source. This result is a Linux SITL build, not an STM32 target build. The experiments below use the official prebuilt binary and the SHA stated in protocol.json , separate from a binary built by ourselves. See release 4.7.1 and the build guide

  1. Check the log on a PC immediately: extract the ZIP, use the Python 3.11+ standard library, run the tests and the two commands below, and read README.md/protocol.json before comparing with the answer key. No STM32 or firmware is needed for the analysis step
  2. Check conditions before arming: the runner sets and reads back FS_GCS_ENABLE=5, FS_GCS_TIMEOUT=5, FS_OPTIONS=0 , checks ARMING_SKIPCHK=0 and MAV_GCS_SYSID=255 , waits for EKF/pre-arm readiness, uses a normal arm and takeoff to a 5 m target, and does not force arm
  3. Compare one factor at a time: once at least 4.5 m high, wait 10 s. In the baseline case, keep sending the heartbeat and then command LAND; in gcs-loss, stop the heartbeat while keeping the TCP connection to receive telemetry and not sending LAND. Check the mode/reason and wait until it lands and disarms
  4. Record the conclusion: use accepted COMMAND_ACK, HEARTBEAT, GLOBAL_POSITION_INT and STATUSTEXT to tie cause to effect, fill in the worksheet stating the clock and the trace row. To rerun, use WSL/Linux as in the README; the runner rejects a network that is not loopback-only and a binary whose SHA does not match
python -m unittest discover -s . -v
python analyze.py data/baseline.json
python analyze.py data/gcs-loss.json

Telemetry graph from ArduCopter 4.7.1 SITL comparing a baseline that commands LAND with the case where the heartbeat stops, where LAND and disarm are found

A graph from real firmware running with the model. The X-axis time is host observation counted from the observed arm, not the firmware's internal trigger clock. Open the full-size SITL graph

Case Cause created What the trace shows
baseline Keep sending the heartbeat, then command LAND GUIDED/armed → receives LAND command → LAND → disarm; no GCS failsafe found
gcs-loss Stop the heartbeat after hover without sending LAND LAND found, and GCS Failsafe from the firmware → lands and disarms

In the gcs-loss case, LAND was observed 4.679 s after the program stopped sending or 5.076 s after the last heartbeat the host sent because the heartbeat is sent about every 1 s, so the stopping point does not coincide with the last send. The figures still include scheduler/telemetry latency, so do not use them to certify a deadline inside the firmware or to subtract the host's t from the firmware's time_boot_ms directly. According to the GCS Failsafe guide , the selected value 5 is Always Land, and the timeout refers to the last heartbeat

Scope of the results: the source build and the two SITL cases passed, but STM32, ESC, IMU or real flight were not tested. Gains/estimator/actuator timing were not compared, and the results are not statistically reliable. The realistic image at the start of the lesson is a conceptual picture. GCS recovery or other forms of failsafe are follow-up exercises that need a written protocol and separately kept results

Next steps for firmware/SITL and reading logs

  1. Choose one question: for example, 'when control data is lost, does the system enter the configured mode?' Record the firmware/version, model, parameters and reference conditions
  2. Create a baseline: do a short mission in SITL using the method in the manual, and keep the log before changing gains or injecting a fault
  3. Change one variable at a time: repeat with controllable hypothetical data or conditions, recording which variable changed and why
  4. Compare the evidence: check the setpoint, measured attitude/rate, actuator command, timestamp, estimator status, mode/failsafe reason and reset reason if the chosen system has them

Similar oscillation may come from gain, vibration, old data, saturation or a wrong axis. Do not conclude from an animation alone. The outcome should be an experiment plan, a before–after table and a conclusion tied to the log. If there is not yet enough data, state what else must be checked

Link to missions and continue learning

Open DroneSim to practise assembling an aircraft, planning a mission and reading the Replay, then write what the system must measure/control to do that mission. The current DroneSim does not run PX4/ArduPilot or MCU code. Choose the tool that fits the question from the Simulator learning path

When you are ready to develop firmware, choose a board supported by the flight stack, read that model's build/port guide, and start from a small change with a clearly checkable effect. Pass criterion for this lesson: be able to explain the outer–inner loops, allocate a time budget, and use logs to separate hypotheses, without citing simulation results as confirmation of real flight

Continue learning and review

Review the origin and scope of the log · Back to the advanced overview

Activities linking MCU knowledge to simulation

Choose a DroneSim activity, reading a log, or studying firmware SITL results with objectives, steps, worksheets and a summary of events from the stored ArduCopter 4.7.1 results, separating what each tool can confirm

Practise reading the cause and time from firmware SITL results

Objective: separate LAND from the tester's command from a GCS failsafe, and separate the time the host observes from the trigger inside the firmware Prerequisites: the PID/STOP_SIM lessons and the origin/scope of the log Suggested time: 45–60 minutes, not yet measured with real learners. Read the stored results with CSV/JSON; no firmware needs to be installed or run again

Diagram separating the baseline that commands LAND from the gcs-loss case that stops the heartbeat, calculating the host interval at both boundaries, and separating the ACK from the disarm

The realistic image and the original telemetry graph are kept. The results in this kit come from the ArduCopter 4.7.1 quad SITL on 1 October 2026, one run per case. This round adds results-reading material, with no new SITL/build/board run

Download how to practise reading SITL results, the 8-question SITL worksheet, the original 11 events, the blank 7-interval time table, the protocol / build results / selected trace with sources and the blank report form and complete them before reading the answer key with reasoning and the 7-interval time answer key Check the source/SHA-256 from manifest

1. Identify the version and cause of each case · S1–S3

Compare the protocol with the PARAM_VALUE read back, then separate the SHA of the official binary used in the two runs from the binary that the source build passed. Read the ACK/mode/armed together with the events and the original runner code before concluding the cause. Hint: the index in the documents counts array members from 1, not the JSON line number, and land_command is recorded after the runner waits for the ACK to be accepted, so do not use this time in place of the time the command was sent

2. Choose the boundary and clock before calculating · S4–S6

Fill in the seven time intervals from the host clock in the same run, compare the stopping point with the last heartbeat, and explain why a LAND that the host sees before the GCS Failsafe message does not indicate the order of internal triggers. Hint: converting ms to s does not make the firmware clock match the host, and displaying six decimals does not guarantee microsecond accuracy

3. Separate accepted, mode and disarm · S7

Use the selected HEARTBEATs to compare mode/armed, then calculate LAND→disarm for both runs. Hint: an accepted ACK is not a completed landing. As stated in MAVLink Command Protocol , one run per case is for practising citing evidence, not for certifying reliability or real-board timing

4. Write the conclusion and a plan for follow-up questions · S8

Fill in the report form with what was observed → protocol/boundaries not yet known → plan for further checks . Cite the file, array index, field and SHA for every conclusion; the selected trace does not replace the full ZIP. Then write a plan for the question of the heartbeat returning, stating that it has not been run, and read the behaviour the documentation describes separately from the results of these two runs in ArduPilot GCS Failsafe . The protocol values are the original experimental values, not a recommendation to copy them to a real aircraft

Self-check: this kit proposes 2 per question (1 answer + 1 reason/unit/boundary), 16 in total, separate from the original Sim activity criteria, for choosing what to review and not real learner results. This round checked the sources/bytes/numbers and explanations; it did not execute the runner/analyzer or add new source-build/SITL/firmware/board results. When you can explain it, continue to Activities linking MCU and Sim

Choose the next practice kit or review

Back to the table of contents of the 10 MCU practice kits to choose a problem according to your goal and the prerequisites you should know, or take the 12-question comprehension assessment to find topics to review

After checking the answer key, record the answers you corrected, the reasons, and what the evidence still does not confirm, then choose the next kit that helps answer that question. The worksheet score and the assessment are separate; use them to choose your own review

Used in courses

How to cite this page

Drone Institute, Rangsit University. (2026). PID, failsafe and firmware. In UAS Technology Knowledge Hub (B.Tech.). https://rsu-uat.pk-research.work/en/kb/knowledge/microcontrollers/advanced/control-firmware/

Original from Drone-Hub: https://drone.pk-research.work/knowledge/microcontrollers/advanced/control-firmware/ · © PK-Research