Skip to the content
FixTheRobot Explore Robotics / UAV / Module 6 / M6-T14

UAV Systems Engineering · Module 6

M6-T14: Software-in-the-Loop simulation

SITL runs your real flight stack against a simulated world. It verifies logic, not the hardware or the physics you did not model.

  • Lesson 14 of 16
  • UAV Software and Flight-Controller Integration
  • Implementation-specific
  • About 5 minutes to read

SITL is the cheapest, safest place to find bugs: you can crash a hundred times before lunch. Its value depends on knowing what is real (the flight code and your companion software) and what is a model (everything else), so that a pass means what you think it means.

Learning objectives

After this lesson, you should be able to:

  • Describe what is real and what is simulated in PX4 SITL.
  • Explain lockstep simulation and why it matters for repeatability.
  • Inject failures (sensor loss, wind, link loss) to exercise failsafes.
  • State what SITL cannot verify and which tests must follow on hardware.

Conceptual explanation

Implementation-specific Simulator choices, make targets and world files change between PX4 releases. The principles hold across them; use the simulation page of the documentation for your release.

In software-in-the-loop simulation PX4 is built for the host computer (a POSIX target) and runs as an ordinary process. A simulator provides the world: vehicle dynamics, sensor models (IMU, GNSS, barometer, magnetometer, cameras, lidar) and sometimes wind and obstacles. Sensor data flows into PX4, actuator outputs flow back. The ground station and ROS 2 nodes connect over MAVLink and DDS exactly as on a real vehicle.

What is real: the PX4 flight stack code (estimator, controllers, commander, navigator), the communication interfaces, and your companion-computer software. What is simulated: rigid-body physics and motors, sensor noise and failure models, the environment, the radio link, and the clock if lockstep is used.

PX4 SITLThe PX4 flight stack compiled for a PC runs as a normal process. A simulator (Gazebo or others) provides the vehicle physics and sensor models and exchanges sensor and actuator data with PX4. QGroundControl and the companion software connect over the same MAVLink and DDS links as on hardware.Simulatorphysics, sensorsBridgesensors / actuatorsPX4 SITLreal flight codeMAVLink / DDSsame as hardwareQGC / ROS 2ground + autonomyReal: the flight stack code. Simulated: physics, sensors, radio, wind, time.
Real flight code, simulated everything else. Know which is which when you read a result.
Animation of a simulation campaign. Seeded runs of a landing scenario are executed one after another and each is marked as a success or a failure. A chart shows the running success rate and the 95 percent lower confidence bound against the number of runs; the bound starts very low and climbs towards the true success rate as the runs accumulate, and the width of the uncertainty shrinks roughly with one over the square root of the number of runs.
A few runs prove little: the Clopper-Pearson lower bound on the success probability after ss successes in nn runs rises slowly with nn (with no failures it is 0.051/n0.05^{1/n}, so 300 runs only support about 99 %). Seeds make every run repeatable. Computed for a scenario with a true success probability of 0.97. (Looping, about 6 seconds; drawn and computed for this course with illustrative values.)

Engineering intuition

SITL answers “is the logic right?” and does not answer “is the world as I modelled it?”. A planner that works in SITL has shown it handles the modelled sensor and physics; it has not shown it handles real vibration, real latency jitter, real lighting or a real compass. It is an excellent filter for software bugs and logic errors, and a poor predictor of tuning and sensor performance unless the models have been validated against real data.

The simulator’s fidelity is a design choice with a cost. A simple point-mass sensor model runs fast and tests logic; a model with measured noise, latency and bias costs effort and tests more. Choose the fidelity to match the question.

Mathematical formulation

Lockstep couples simulator and PX4 time: the simulator advances its clock one step, sends sensor data, and waits for PX4 to run one control step before advancing again. Simulated time then no longer depends on how fast the computer is, which makes runs repeatable. With a physics step Δtsim\Delta t_{\text{sim}} and a real-time factor RTF:

Real-time factor
RTF=ΔtsimΔtwall,runtimewall=TsimRTF\mathrm{RTF} = \frac{\Delta t_{\text{sim}}}{\Delta t_{\text{wall}}}, \qquad \text{runtime}_{\text{wall}} = \frac{T_{\text{sim}}}{\mathrm{RTF}}

Reproducibility needs a fixed seed for every random model (sensor noise, wind) and fixed initial conditions; then the same inputs give the same outputs, which allows regression tests: assert on tracking error, time-to-goal or number of failsafe triggers. The statistical power of a simulation campaign comes from many runs with different seeds: with nn independent runs the standard error of a success rate p^\hat{p} is p^(1−p^)/n\sqrt{\hat{p}(1-\hat{p})/n}, so confirming a 98 % success rate to ±2 % needs about 50 runs, and distinguishing 99.9 % from 99 % needs several hundred.

RTF
real-time factor (simulated time per wall-clock time).
nn
number of independent runs.

Architecture and data flow

Simulator (physics, sensor models) → sensor messages (for example via the MAVLink HIL interface or a Gazebo transport plugin) → PX4 SITL (flight stack) → actuator messages → simulator. PX4’s MAVLink and DDS endpoints on UDP ports → QGroundControl and the companion software. Simulated camera and lidar data go directly to the companion via the simulator’s own transport (for example Gazebo topics bridged into ROS 2), not through PX4.

Real-world UAV applications

  • Developing and regression-testing autonomy software without hardware.
  • Exercising failsafes by injecting sensor failures, link loss and wind.
  • Training pilots and operators on mission procedures.
  • Collecting statistics over many randomised runs.

Implementation example

The standard start-up, run on a development machine (see the lab for the full set-up; targets and simulator names depend on the PX4 version). Shown for reference and not run by the tests.

git clone --recursive https://github.com/PX4/PX4-Autopilot.git
cd PX4-Autopilot && bash ./Tools/setup/ubuntu.sh        # toolchain and simulator dependencies
make px4_sitl gz_x500                                   # build and start PX4 SITL with a Gazebo x500 quadrotor (target names vary by version)
Starting PX4 SITL. Target names change between releases: use the documentation for yours.

This runs as shown. A small campaign driver for Monte Carlo SITL-style runs: seeded randomisation, a pass/fail criterion and a confidence statement. The “vehicle” is a stand-in function; replace it with a call to your simulation harness.

import numpy as np
from math import sqrt

def one_run(seed):
    rng = np.random.default_rng(seed)                       # every random model is seeded: the run is reproducible
    wind = rng.normal(0, 1.5); delay = rng.uniform(0.02, 0.12)
    miss = abs(0.15 * wind) + 3.0 * (delay - 0.02) + 0.05 * rng.standard_normal()       # stand-in for 'final position error' of a landing
    return miss < 0.6
assert one_run(7) == one_run(7)                             # same seed, same outcome
n = 400; passes = sum(one_run(s) for s in range(n)); p = passes / n
se = sqrt(p * (1 - p) / n); lo = p - 1.96 * se
print(f"success rate {p:.3f} +- {1.96 * se:.3f} (95 %), lower bound {lo:.3f}")
assert 0.9 < p < 1.0
need = lambda p0, half: int(np.ceil(1.96 ** 2 * p0 * (1 - p0) / half ** 2))
print("runs needed to confirm 98 % to +-2 %:", need(0.98, 0.02), "; 99.9 % to +-0.1 %:", need(0.999, 0.001))
A seeded Monte Carlo driver with a confidence bound. The vehicle model is a stand-in.

Common engineering mistakes

Treating SITL success as flight readiness

It proves logic against a model, not behaviour in the real world.

Using wall-clock time in tests

Use simulated (lockstep) time or results depend on computer load.

Unseeded randomness

Failures that cannot be reproduced cannot be fixed.

Perfect sensors

Add noise, bias, latency and dropouts from measurements or data sheets.

One run per scenario

Use enough seeds to say something about rates, not anecdotes.

Failure modes

Failure modes, symptoms and causes
Failure modeHow it shows upLikely cause
Passes in SITL, fails on hardwareNew behaviour in the fieldUnmodelled latency, vibration, sensor error or timing jitter
Run is not repeatableResults vary between runsUnseeded randomness or non-lockstep timing
Simulator very slowRTF far below 1Heavy sensors or physics; reduce rendering or use headless mode
Sensor topics missingCompanion sees no camera dataBridge not configured

Debugging approach

  1. Fix seeds and rerun the failing case; step through with logs.
  2. Check RTF and lockstep status.
  3. Compare simulated sensor streams to real recorded ones for noise and latency.
  4. Replay recorded real data into the companion to separate software from simulation issues.

Practical exercises

  1. Start PX4 SITL, fly a mission, and download the log; compare its estimator noise to that of a real log.
  2. Inject a GNSS failure mid-mission and record the failsafe.
  3. Run the same scenario with ten seeds and report the spread of landing error.
  4. List five effects your simulator does not model that matter for your vehicle.

Interview questions

Write an answer in your own words, then reveal the model answer. Nothing is sent anywhere.

Question 1

What is real and what is simulated in PX4 SITL?

Model answer

The flight stack code and your companion software are real; the physics, sensors, motors, environment, link and possibly the clock are models.

Question 2

Why use lockstep simulation?

Model answer

It ties simulated time to the control steps so results do not depend on computer speed, making runs repeatable and suitable for regression tests.

Question 3

What can SITL not verify?

Model answer

Hardware drivers and timing, real sensor behaviour, vibration, power and thermal effects, radio links and the accuracy of the physics model; these need hardware-in-the-loop, bench and flight tests.

References and further reading

Primary papers, official documentation and standards. Each claim above that is specific to a tool or version points here.

What’s next

Mark this lesson

Saved in this browser and synced to your account when you are signed in.

Practice this lesson

M6-L2: Run PX4 SITL

Launch SITL with Gazebo.

Next lesson

M6-T15: Hardware-in-the-Loop simulation

Set up hardware-in-the-loop simulation with a real flight controller, and explain what it verifies that SITL cannot.