Tutorials

AI-generated illustration of a two-axis camera gimbal mounted under a compact drone, with a translucent attitude sphere and gyro rings. Simulation only.
Tutorial

How I built a two-axis camera gimbal simulator with cascaded PID, a complementary attitude filter, and a simplified EKF

A portfolio, simulation-only walkthrough of sim-gimbal-stabilizer: a two-axis pitch and yaw camera gimbal sim with a fixed-step no-heap C++17 controller core, cascaded PID, a complementary attitude filter, a simplified EKF, and a WASM browser demo. How to build it, run the tests, and what the results actually show.

Arpan Bom13 min read
ShareXLinkedIn

This is a simulation only

This is a portfolio demo, not production gimbal firmware. It has never been flown or flight-tested, it is not certified, and it does not implement FOC or a BLDC drive. I built it to show a two-axis pitch and yaw camera-gimbal loop on a simplified torque plant, with deterministic tests behind the numbers I quote below. A two-axis mount also cannot reject roll about the optical axis. Residual roll is unactuated, and the tests do not hide that.

Try the live demo

The fastest way to see it working is the browser demo: https://applycoding.github.io/sim-gimbal-stabilizer/

The page loads the same C++ controller through a WASM module, not a TypeScript rewrite of the control law. You get two gain sliders (boresight (k_p) and rate (k_p)), a 10 degree pitch-step button, and a Canvas plot of boresight pitch error. The WASM module records at most 8192 samples, or 8.192 simulated seconds, and then the plot stops updating. Reloading the page restarts the trace. Clicking the step button more than once keeps the same 10 degree target; it does not queue additional steps.

Browser demo of sim-gimbal-stabilizer, showing the WASM UI after a 10 degree pitch step, with boresight and rate gain sliders and a Canvas plot of boresight pitch error. Simulation only.

Image: the GitHub Pages demo after a 10 degree pitch step, with boresight (k_p) set to 15. Simulation only. applycoding.com.

What the project is

sim-gimbal-stabilizer (repo: applycoding/sim-gimbal-stabilizer, commit 3f52e6a) is a two-axis camera gimbal simulator. The stack, from the README, is:

Layer Role
sgs_core C++17, no heap, MCU-shaped controller and estimators
sgs_sim Host and WASM plant, sensors, and scenario runner
web/ TypeScript UI and Canvas 2D, running the same C++ through WASM

The core is an original implementation of well-known methods: a discrete PID with back-calculation anti-windup, a complementary attitude filter, and a small error-state estimator. Those ideas are inspired by the projects credited in REFERENCES.md and the README. I did not invent the algorithms.

The no-heap rule is specific. tools/check_no_heap.py scans cpp/src/core and the headers under cpp/include/sgs/*.hpp for containers and allocation. The host and WASM plant in sgs_sim is allowed to use the heap (scenario traces use std::vector). Do not read "no heap" as a claim about the whole demo binary.

Optional Python bindings ship in cpp/src/python/bindings.cpp when SGS_BUILD_PYTHON=ON. The module is small: it exposes default_gains, default_limits, and two helpers that run a pitch-step scenario (run_step_pitch_max_error, trace_len_after_step_pitch). It is not a full wrap of the controller or estimator API. The ROS 2 workflow is still a placeholder: it builds the core with SGS_BUILD_ROS=OFF and does not run colcon.

Frames and the two-axis limit

World coordinates are north-east-down (NED). The camera frame is forward-right-down (FRD). Rotations use Hamilton quaternions. Joint order is base yaw, then pitch. Positive pitch moves the optical axis (+x) toward world -z (up in FRD).

The controlled objective is optical-axis, or boresight, hold. Because there is no roll actuator, a disturbance about the optical axis is residual roll. The ResidualRollTransmissibility test requires that transmissibility stay between 0.70 and 1.30, which is the honesty check: the loop does not reject roll.

At rest, a level camera IMU reports specific force [0, 0, -g] in FRD, with g_ned = [0, 0, +g].

How the controller is structured

Each control step is fixed-rate. Controller::step in cpp/src/core/controller.cpp rejects a time step outside (0, 0.002]. The plant and the WASM demo both advance at 1 ms.

There is no v1 base-rate feed-forward in the controller. The plant can inject a base motion, but the controller does not cancel it with a feed-forward term.

Cascaded PID: boresight then inertial rate

The outer loop is a boresight PID. It takes the camera-frame boresight error and commands a pitch and yaw rate, clipped to 2 rad/s. The inner loop is an inertial-rate PID. It uses the camera gyro, minus the estimator's gyro bias, mapped into joint rates, and commands pitch and yaw torques. Torque is limited to 0.15 N-m, with a 0.001 N-m dead-zone. If |θ| exceeds 75 degrees, a latch freezes the yaw integrator until the pitch angle falls 2 degrees back inside that warning band.

The locked default gains, from cpp/src/core/defaults.cpp and the README, are:

Loop (k_p) (k_i) (k_d)
Rate (inner) 0.05 0.40 2e-4
Boresight (outer) 10 2.0 0.10

The shared derivative filter time constant is tau_d = 5 ms. The discrete PID in cpp/src/core/pid.cpp uses measurement-derivative on a first-order filter, then back-calculation anti-windup:

const double k_aw = gains.kp != 0.0 ? gains.ki / gains.kp : 0.0;
// ...
const double u_raw = gains.kp * e + st->integ - gains.kd * st->d_filt;
// saturate, then apply the torque dead-zone
if (!freeze_integ) {
  st->integ += dt * (gains.ki * e + k_aw * (u_applied - u_raw));
}

The plant is a teaching model, not FOC. Per joint, from the README:

J * alpha = tau - b * omega - tau_c * tanh(omega / 0.05) - k_spring * q

with frozen J = 1.5e-4, b = 2.0e-4, tau_c = 1.0e-3, and k_spring = 0.02 (cpp/include/sgs/sim/plant.hpp). Integration is semi-implicit Euler at 1 ms: update rate, then angle, then clamp pitch at 80 degrees.

Complementary filter

cpp/src/core/complementary.cpp first applies a proportional accelerometer correction for tilt, and, when the magnetometer flag is valid, a yaw correction, to the gyro angular velocity. It then integrates that corrected rate into the attitude quaternion. Default gains are comp_kp_acc = 2.0 and comp_kp_mag = 0.5.

Two honesty points from the README and tests matter in use. The complementary filter does not estimate gyro bias, so a biased-gyro run is expected to settle at a small residual tilt (the BiasedGyroEquilibrium test). Accelerometer updates do not observe yaw; if the magnetometer is off, yaw is not corrected.

The simplified EKF

The optional estimator keeps a 6-state error-state layout: attitude error and gyro bias, with a row-major 6x6 P, plus inject and reset hooks. That is not the same thing as a full coupled 6x6 error-state Kalman filter. DEVIATIONS.md and a comment in cpp/src/core/ekf.cpp are explicit.

Accelerometer tilt updates and magnetometer yaw updates are decoupled scalar Kalman corrections (kalman_update_scalar). Magnetometer yaw uses the shared mag_heading_error_rad innovation with a body-frame horizontal magnitude gate of 5.0 uT. That gate is reachable at this commit: the reference field is [25, 0, 40] uT, so a level measurement has 25 uT in the body horizontal plane. Default ekf_sigma_mag is 1.0 uT, and ekf_init_state starts the attitude and bias P diagonals at 0.02 and 1e-5, as documented in DEVIATIONS.md.

An unused helper named joseph_update exists in the file; it is not called on the v1 path, and despite the name it does not implement the Joseph covariance form. Yaw-bias convergence on the static bench is still a stationary-gate first-order blend of the gyro onto the bias state, and only when both the accelerometer and magnetometer flags are valid. It is not a Kalman update of b_gz from the magnetometer innovation. With the magnetometer off, yaw bias is not observed, which is what Ekf.MagOffNoYawObserve checks.

The hand example in Ekf.KalmanHandExample is a one-state update: starting from x = 0, P = 1, z = R = H = 1, the gain, posterior state, and covariance are all 0.5 within 1e-12.

The controller defaults to this estimator (ControllerState::EstimatorSelect::Ekf). The WASM API exposes sgs_set_estimator to switch to the complementary filter, but the v1 web UI does not wire that switch. The page you see on GitHub Pages is running the EKF path.

Build the C++ core and run the tests

From the repository root, the README build is:

cmake -S . -B build -DCMAKE_CXX_COMPILER=g++-13 -DCMAKE_BUILD_TYPE=Release \
  -DSGS_BUILD_PYTHON=OFF -DSGS_BUILD_ROS=OFF -DSGS_BUILD_WASM=OFF
cmake --build build -j
ctest --test-dir build --output-on-failure
python3 tools/check_no_heap.py

The core GitHub Actions workflow at commit 3f52e6a ran that sequence on Ubuntu 24.04 with g++-13 and reported 100% tests passed, 0 tests failed out of 29. Those 29 ctest entries are the 27 discovered GoogleTest cases, one additional sgs_gtests entry that runs the same binary as a single test, and noheap_link.

Optional Python bindings, from the README:

cmake -S . -B build -DCMAKE_CXX_COMPILER=g++-13 -DCMAKE_BUILD_TYPE=Release   -DSGS_BUILD_PYTHON=ON
# after the build:
PYTHONPATH=build/python python3 -m pytest -q python/tests

The python job in the same core workflow uses a separate build directory, build-py, with SGS_BUILD_PYTHON=ON and SGS_BUILD_TESTS=OFF, then runs PYTHONPATH=build-py/python python3 -m pytest -q python/tests. On commit 3f52e6a that job reported 1 passed.

Run the browser demo locally

The README's web path is:

bash scripts/build_wasm.sh
cd web && npm ci && npm run dev

scripts/build_wasm.sh installs and activates Emscripten 7.0.0, configures the tree with -DSGS_BUILD_WASM=ON, and copies sgs.js and sgs.wasm into web/public/. The preview alternative in the README is npm run build && npm run preview. web/package.json serves the preview on 127.0.0.1:4173. The Vite base path, and the Pages URL, is /sim-gimbal-stabilizer/.

The web workflow on 3f52e6a uses Node 26.13.0 and npm ci --legacy-peer-deps, then tsc, Vitest, the production build, and Playwright. If a plain npm ci fails on peer dependencies, that is the command CI actually used. The web/ tree and docs/demo.png did not change in this commit, so the two gain sliders, the single error plot, and the lead screenshot are the same as before.

In the UI, moving the boresight (k_p) slider updates the status line. The rate (k_p) slider is also live. The WASM API sgs_set_gains can write both integral gains, but the TypeScript shell always passes the defaults (0.40 and 2.0) for those two arguments, so the integral gains stay fixed. The plot shows boresight pitch error, not a full set of traces, and the recorder stops after 8192 samples (8.192 simulated seconds). Clicking "10° pitch step" arms a step that is applied once the simulation clock reaches 0.5 s. Later clicks keep that same 10 degree target rather than queuing a new step.

After any cd web, later repository commands need to be run from the repo root again.

Results from the tests

Thresholds below are from cpp/test/ at commit 3f52e6a. The 29/29 figure is from the core GitHub Actions run on that commit. Where I quote a measured magnetometer or static-boresight value, it is from a local run of the same test fixture; the CI log only records that those tests passed.

On a 10 degree boresight step (pitch or yaw, 4 s, seed 1), the scenario tests require overshoot at most 25%, rise time at most 0.40 s, and a settled error at most 0.5 degrees. Settled error is the peak error in the 1.5 to 3.0 s window. The zero-gain pitch step is a negative control: the boresight error should barely move.

At 0.5 Hz base motion, closed-loop transmissibility must be at most 0.35 in pitch and in yaw, and the same run with gains zeroed must stay at least 0.90. That closed versus open pair is the feedback proof. At 10 Hz the tests only check that closed-loop transmissibility is at most 0.35. The README is clear that 10 Hz isolation is largely the passive spring and inertia, and that the claim is pitch and yaw only.

The combined disturbance run (7 s, noisy sensors, seed 2) requires RMS boresight error at most 1.5 degrees, measured over the 1 to 6 s window. A separate determinism test uses the same scenario kind and seed with the default 5 s duration, and requires the host traces to match to 1e-9 rad. Residual roll transmissibility must stay between 0.70 and 1.30.

On the estimator benches, the complementary filter must recover a 20 degree static tilt within 1 degree, and the EKF yaw-bias test requires the estimated b_gz to be within 0.003 rad/s of a 0.01 rad/s gyro bias by 8 s, when both accelerometer and magnetometer flags are valid.

Ekf.MagYawCorrection starts at 22 degrees of heading error and requires that the error fall, end below 8 degrees after 8 s, and leave the mag-weak flag clear. A local run of that same fixture at 3f52e6a ended at 7.3 degrees. Ekf.StaticBoresightMagOn requires static boresight error below 1 degree with the magnetometer on; a local run of that fixture measured 0.51 degrees.

License and references

The project is Apache-2.0. See LICENSE and NOTICE. The controller and estimator source in this repo was written for this demo. No third-party controller source is vendored.

Idea references, with licenses, as listed in REFERENCES.md and the README (conceptual only, no source copied):

Joan Sola's error-state Kalman filter notes, arXiv:1711.02508, are a mathematical reference only.

I also looked at several GPL or LGPL projects as idea-only references, including ArduPilot, Betaflight, iNav, imu_filter_madgwick (GPL-3.0-or-later, in the same imu_tools repo), and morgil/madgwick_py (LGPL-3.0). No code was derived from those. That matters because this repo's outbound license is Apache-2.0.

How this was verified

I ran the standard portfolio-tutorial checks against commit 3f52e6a on main.

  • The GitHub repo is not a fork. gh api repos/applycoding/sim-gimbal-stabilizer reports "fork": false.
  • All 3 commits on main have author and committer Arpan Bom (applycoding@gmail.com). Pre-merge topic branches are also authored and committed by Arpan Bom. The successful core (including the python job), web, ros2-humble, and pages workflows on 3f52e6a were triggered by the GitHub user applycoding.
  • A search of the tree found no third_party, vendor, or external directories, and no "ported from", "adapted from", or "copied from" markers in the authored source. NOTICE states that no third-party controller source is vendored or translated. The generated Emscripten glue in web/public/sgs.js is build output, not vendored controller code.
  • This is an original implementation of well-known methods (cascaded PID with anti-windup, a complementary attitude filter, and a simplified error-state estimator), inspired by the projects credited above. I did not invent these algorithms.
  • At 3f52e6a, NOTICE names the primary idea references with licenses (PX4, SimpleFOC, Fusion, Mayitzin/ahrs, TinyEKF, control_toolbox, imu_complementary_filter, and robot_localization) and the build and test dependencies actually used, with matching versions: GoogleTest v1.18.0 (BSD-3-Clause), pybind11 v3.1.0 (BSD-style), pytest 9.2.0 (MIT), CMake (BSD-3-Clause), Emscripten SDK 7.0.0, and the web devDependencies Vite 8.3.7 (MIT), Vitest 5.1.0 (MIT), TypeScript 7.0.2 (Apache-2.0), Playwright Test 1.65.0 (Apache-2.0), and @types/node 22.10.2 (MIT). Unused nlohmann/json was removed from NOTICE. The Valenti paper, Joan Sola's arXiv notes, and the GPL or LGPL idea-only projects remain cited in REFERENCES.md and in this tutorial; NOTICE points at REFERENCES.md for full citations and notes that GPL Madgwick was excluded.
  • The repo license is Apache-2.0.
  • Commands, paths, APIs, and the test thresholds in this tutorial were checked against the repo at 3f52e6a. The 29/29 figure is from core GitHub Actions run 42943225884 on that commit. The live demo at https://applycoding.github.io/sim-gimbal-stabilizer/ returned HTTP 200.
  • This project is simulation only, has never been flown, is not FOC, and does not reject roll.

Limits

This is simulation only, on a simplified per-joint torque plant, with a single two-axis camera. It is not firmware, it has not been tested on hardware, and it is not a FOC motor controller. The estimator is still not a full coupled 6x6 error-state Kalman filter: measurement updates stay decoupled and scalar, and yaw-bias convergence on the static bench is still an IIR blend, not a Kalman update from the magnetometer innovation. The 10 Hz isolation result is not the same kind of proof as the 0.5 Hz closed versus open-loop pair. The browser demo is the C++ core compiled to WASM, with a small TypeScript shell, and the v1 page exposes only two gain sliders and one error plot.