ChibiOS & ArduPilot Architecture
Executive Summary
Since 2017, ArduPilot has run on top of ChibiOS/RT, a high-performance Real-Time Operating System (RTOS). This replaced the older "Flymaple" and custom scheduler approach for STM32 targets.
- ChibiOS/RT: Provides the kernel (threading, mutexes, semaphores).
- ChibiOS/HAL: Provides drivers for on-chip peripherals (UART, SPI, I2C, ADC).
- AP_HAL_ChibiOS: The "Glue Layer" that maps ArduPilot's generic
AP_HALclasses to the specific ChibiOS implementation.
Theory & Concepts
1. The Kernel (ChibiOS/RT)
ChibiOS/RT is a static, preemptive real-time kernel.
- Static: All kernel objects (threads, semaphores) are typically allocated at compile time (or from a static heap), avoiding dynamic allocation fragmentation.
- Preemptive: Higher priority threads immediately interrupt lower priority ones. This is critical for flight control where the gyro loop (Fast Loop) must run at precisely 400Hz/1kHz/4kHz regardless of what the logging thread is doing.
2. The HAL (Hardware Abstraction Layer)
ChibiOS provides a standardized API for accessing hardware.
- Instead of writing registers directly (e.g.,
UART1->DR = 'A'), we usesdPut(&SD1, 'A'). - This makes porting between STM32F4, F7, and H7 seamless, as ChibiOS handles the register differences.
Codebase Investigation
1. The Entry Point: main_loop()
Located in libraries/AP_HAL_ChibiOS/HAL_ChibiOS_Class.cpp.
When the board boots:
- Kernel Init:
chSysInit()is called (typically in the startup code). - HAL Init:
halInit()sets up drivers defined inmcuconf.h. - Daemon Task: The
mainfunction becomes the Main Thread (daemon_task). - Priority Boost:
chThdSetPriority(APM_MAIN_PRIORITY)sets the main loop priority (typically very high).
2. The Scheduler Wrapper
ArduPilot's AP_Scheduler is cooperative, but it runs inside the preemptive ChibiOS main thread.
- The Glue:
libraries/AP_HAL_ChibiOS/Scheduler.cpp - The
delay_microseconds(n)function yields the CPU to lower-priority threads (like Storage or USB) while waiting.
3. Priority Map
ArduPilot maps its abstract priorities to ChibiOS levels:
APM_MAIN_PRIORITY: High (Flight Code).APM_SPI_PRIORITY: Higher (Bus Drivers).APM_IO_PRIORITY: Low (Logging, SD Card).
Source Code Reference
- Integration Layer:
libraries/AP_HAL_ChibiOS/HAL_ChibiOS_Class.cpp - ChibiOS Upstream:
modules/ChibiOS(submodule in ArduPilot).
Practical Guide: Debugging HardFaults
If the OS crashes, ChibiOS provides a HardFault_Handler in system.cpp.
- Common Cause: Stack Overflow. Check
AP_HAL::util()->available_memory(). - Diagnosis: Connect a JTAG/SWD debugger (ST-Link). The handler saves the CPU registers (PC, LR) to
hal.util->persistent_data, which allows post-mortem analysis even after a watchdog reset.