MAVLINKHUD

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_HAL classes 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 use sdPut(&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:

  1. Kernel Init: chSysInit() is called (typically in the startup code).
  2. HAL Init: halInit() sets up drivers defined in mcuconf.h.
  3. Daemon Task: The main function becomes the Main Thread (daemon_task).
  4. 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

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.