Lazy loaded image
🛩️ APM源码分析
AP系列05-传感器驱动 Sensor Drivers
Words 662Read Time 2 min
2024-8-13
2025-4-16
type
date
slug
category
icon
password
💡
本节配图基于官方教程,与最新固件(当前4.6.0)代码有些许出入。

传感器支持接口

  1. I2C
  1. SPI
  1. Serial/UART
  1. CAN bus with UAVCAN

前后端分离架构

FrontEnd / BackEnd Split
传感器驱动采用前后端分离架构。飞行器代码调用前端代码,前端自动检测或根据类型,创建单个或多个后端。前端代码会维护后端驱动数组_drivers[]
notion image
 

驱动代码工作方式

notion image
  1. 传感器后端驱动运行在背景线程(background thread),完成原始数据采集,转化标准单位后,存储在缓存中。
  1. 主线程运行在固定频率,从传感器驱动前端获取最新数据。
 

示例1:测距仪前端

Vehicle Code and Front-End Example - range finder (aka sonar, lidar) drivers
  1. 调度器周期调用 Copter::read_rangefinder() 方法(20Hz);
    1. notion image
  1. Rangefinder 前端框架数据更新方法 ,在内部遍历所有驱动实例 drivers[i]→update
    1. notion image
 

示例2:测距仪串口后端

  1. 配置串口参数;
    1. notion image
  1. 根据参数设置,使用串口管理器,查找 uart ;
    1. notion image
  1. 调用后端更新方法void AP_RangeFinder_Backend_Serial::update(void)时,get_reading 方法检查接收字符并解码。(特别的对于串口驱动,接收到的数据存储在缓存中,实际数据处理在主线程中。而 I2C 和 SPI 驱动,则register_periodic_callback,在周期回调中完成数据更新。)
    1. notion image
      notion image
 

示例3:测距仪 I2C 后端

  1. 前端获取I2C总线设备 _dev,初始化时传递给后端;
  1. 后端初始化时,注册回调函数,20Hz 周期执行AP_RangeFinder_LightWareI2C:timer
  1. AP_RangeFinder_LightWareI2C:timer中调用 get_reading 方法,完成传感器数据读取,单位转化。
notion image

示例4:惯导 SPI 后端

  1. 前端获取SPI 总线,初始化时传递给后端;
    1. notion image
  1. 后端初始化时,配置 SPI 通讯参数,注册周期回调(AP_InertialSensor_MPU9250::_read_sample,1000 Hz);
  1. SPI读取数据并解码转换,由于_read_sample 在周期调用代码里,因此不需要信号量做保护。
    1. notion image

额外建议

在编写传感器驱动时,不要包含任何等待或休眠代码,因为这将延迟主线程或与正在使用的总线相关的后台线程。
如果编写了一个新的库,必须将其添加到车辆目录中的wscript文件(例如/ardupilot/ArduCopter/wscript),以便将其链接到最终的二进制文件中。
 

引用

  1. Sensor Drivers — Dev documentation (ardupilot.org)
上一篇
AP系列04-库范例 Library Example Sketches
下一篇
AP系列07-Mavlink 协议

Comments
Loading...