MAVLINKHUD

Customizing Features

Executive Summary

ArduPilot is designed to be modified. There are two primary ways to inject custom logic: User Hooks (for simple logic) and Build Configuration (for hardware/driver changes).

The UserCode.cpp file provides predefined entry points into the main loop, allowing you to run custom code at 100Hz, 50Hz, 10Hz, etc., without altering the complex scheduler.

Theory & Concepts

1. User Hooks

The main vehicle scheduler (e.g., Copter.cpp) calls specific functions like userhook_FastLoop() at fixed intervals. By default, these functions are empty.

  • Compilation: You must define macros like USERHOOK_FASTLOOP in your ap_config.h or via a custom header to enable these calls.

2. Feature Stripping

To run ArduPilot on smaller boards (1MB Flash), you often need to disable features.

  • hwdef.dat: The hardware definition file allows you to exclude drivers (define HAL_OSD_ENABLED 0).
  • wscript: You can disable entire subsystems like Scripting or OSD via command line flags.

Codebase Investigation

1. The User Hooks: ArduCopter/UserCode.cpp

Located in ArduCopter/UserCode.cpp.

  • Contains empty implementations of:
    • userhook_init(): Called once at startup.
    • userhook_FastLoop(): Called at 100Hz (or main loop rate).
    • userhook_MediumLoop(): Called at 10Hz.
    • userhook_SlowLoop(): Called at 3.3Hz.

2. Enabling Hooks

To actually use these, you create a file named UserVariables.h (which is included by Copter.h but git-ignored) and add:

#define USERHOOK_FASTLOOP 1
#include "UserVariables.h"

Source Code Reference

Practical Guide: Adding a Custom Feature

1. The "Blinking LED" Hello World

  1. Create ArduCopter/UserVariables.h.
  2. Add: #define USERHOOK_SLOWLOOP
  3. In UserCode.cpp, modify userhook_SlowLoop():
    void Copter::userhook_SlowLoop() {
        hal.gpio->toggle(HAL_GPIO_A_LED_PIN);
    }
    
  4. Compile and upload.

2. Saving Flash Space

If your build fails with "region 'flash' overflowed":

  1. Edit your board's hwdef.dat in libraries/AP_HAL_ChibiOS/hwdef/.
  2. Add lines to disable unused features:
    define HAL_MOUNT_ENABLED 0
    define HAL_CAMERA_ENABLED 0
    define HAL_OSD_ENABLED 0
    
  3. Reconfigure and build: ./waf configure --board=YourBoard && ./waf copter.