本文主要是介绍AP_HAL 再分析, 以pixhawk-fmuv2为硬件平台,ChibiOS为底层操作系统:,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
AP_HAL.h 分析
#include <stdint.h>#include "AP_HAL_Namespace.h"
#include "AP_HAL_Boards.h" --->>> 板子选择比如 HAL_BOARD_CHIBIOS
#include "AP_HAL_Macros.h"
#include "AP_HAL_Main.h"/**< hal 模块的类集合,所有的类都是纯虚类<接口类>,* 也就是应用层不依赖于具体的底层类,而是依赖于抽象* 即:面向接口编程*/
/* HAL Module Classes (all pure virtual) */
#include "UARTDriver.h" /* --->>> Pure virtual UARTDriver class 纯虚UARTDriver类, 只定义接口, 在具体的四大系统软硬件平台中进行实现 */
#include "AnalogIn.h" /* --->>> 代表模拟输入器件,比如声纳等,fanout一定范围内的电压值, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "Storage.h" /* --->>> 储存类块设备, 比如sd等, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "GPIO.h" /* --->>> GPIO, 及其对应的中断触发方式, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "RCInput.h" /* --->>> 接收机输入, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "RCOutput.h" /* --->>> 接收机输出, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "Scheduler.h" /* --->>> 调度器, 提供线程创建等功能 只定义接口,在具体的四大系统软硬件平台中进行实现 */*/
#include "Semaphores.h" /* --->>> 信号量相关操作, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "Util.h" /* --->>> 一些辅助性,配置性,工具 比如log存储位置,snprintf等 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "OpticalFlow.h"/* --->>> 光流,chibios、linux都平台没有实现 */
#include "Flash.h" /* --->>> flash 页、块操作相关接口 只定义接口,在具体的四大系统软硬件平台中进行实现 */#if HAL_WITH_UAVCAN
#include "CAN.h" /* --->>> 定义can总线协议需要实现的相关接口 只定义接口,在具体的四大系统软硬件平台中进行实现 */*/
#endif#include "utility/BetterStream.h" /* --->>> 流操作相关接口printf,write,read..., UARTDriver继承了此接口类 *//* HAL Class definition */
/**< --->>> 包含了当前目录下的HAL.h, 主要定义了 AP_HAL::HAL 接口类,聚合了系统硬件的几乎所有接口,比如* uart, spi, i2c, scheduler等, 该类在四大系统软硬件平台中进行实现 */
#include "HAL.h"
#include "system.h"
```cINS_Generic.cpp```c++
//
// Simple test for the AP_InertialSensor driver.
//#include <AP_HAL/AP_HAL.h> --->>> 硬件接口
#include <AP_BoardConfig/AP_BoardConfig.h>
#include <AP_InertialSensor/AP_InertialSensor.h>const AP_HAL::HAL &hal = AP_HAL::get_HAL(); --->>> 在四大系统软硬件平台中实现,如HAL_ChibiOS中const AP_HAL::HAL& AP_HAL::get_HAL() {static const HAL_ChibiOS hal_chibios; --->>> 定义一个静态HAL_ChibiOS对象,并返回其引用,依然是面向接口return hal_chibios;}static AP_InertialSensor ins; --->>> 静态对象static void display_offsets_and_scaling();
static void run_test();// board specific config
static AP_BoardConfig BoardConfig; --->>> 静态对象void setup(void); --->>> 框架方法setup
void loop(void); --->>> 框架方法loopvoid setup(void)
{// setup any board specific driversBoardConfig.init();hal.console->printf("AP_InertialSensor startup...\n");ins.init(100);// display initial valuesdisplay_offsets_and_scaling();// display number of detected accels/gyroshal.console->printf("\n");hal.console->printf("Number of detected accels : %u\n", ins.get_accel_count());hal.console->printf("Number of detected gyros : %u\n\n", ins.get_gyro_count());hal.console->printf("Complete. Reading:\n");
}void loop(void) --->>> 读取用户输入,并且响应,这里脉络是很清晰的,我们暂不进入具体函数的实现细节
{int16_t user_input;hal.console->printf("\n");hal.console->printf("%s\n","Menu:\n"" d) display offsets and scaling\n"" l) level (capture offsets from level)\n"" t) test\n"" r) reboot");// wait for user inputwhile (!hal.console->available()) {hal.scheduler->delay(20);}// read in user inputwhile (hal.console->available()) {user_input = hal.console->read();if (user_input == 'd' || user_input == 'D') {display_offsets_and_scaling();}if (user_input == 't' || user_input == 'T') { ---> 测试方法run_test();}if (user_input == 'r' || user_input == 'R') {hal.scheduler->reboot(false);}}
}static void display_offsets_and_scaling()
{const Vector3f &accel_offsets = ins.get_accel_offsets();const Vector3f &accel_scale = ins.get_accel_scale();const Vector3f &gyro_offsets = ins.get_gyro_offsets();// display resultshal.console->printf("\nAccel Offsets X:%10.8f \t Y:%10.8f \t Z:%10.8f\n",(double)accel_offsets.x,(double)accel_offsets.y,(double)accel_offsets.z);hal.console->printf("Accel Scale X:%10.8f \t Y:%10.8f \t Z:%10.8f\n",(double)accel_scale.x,(double)accel_scale.y,(double)accel_scale.z);hal.console->printf("Gyro Offsets X:%10.8f \t Y:%10.8f \t Z:%10.8f\n",(double)gyro_offsets.x,(double)gyro_offsets.y,(double)gyro_offsets.z);
}static void run_test()
{Vector3f accel;Vector3f gyro;uint8_t counter = 0;static uint8_t accel_count = ins.get_accel_count(); ---> 获取acc和gyro轴数static uint8_t gyro_count = ins.get_gyro_count();static uint8_t ins_count = MAX(accel_count, gyro_count);// flush any user inputwhile (hal.console->available()) {hal.console->read();}// clear out any existing samples from ins 刷新采样值ins.update(); // loop as long as user does not press a keywhile (!hal.console->available()) {// wait until we have a sampleins.wait_for_sample();// read samples from insins.update();// print each accel/gyro result every 50 cyclesif (counter++ % 50 != 0) {continue;}// loop and print each sensorfor (uint8_t ii = 0; ii < ins_count; ii++) {char state;if (ii > accel_count - 1) {// No accel presentstate = '-';} else if (ins.get_accel_health(ii)) {// Healthy accelstate = 'h';} else {// Accel present but not healthystate = 'u';}accel = ins.get_accel(ii); ---> 获取acc hal.console->printf("%u - Accel (%c) : X:%6.2f Y:%6.2f Z:%6.2f norm:%5.2f",ii, state, (double)accel.x, (double)accel.y, (double)accel.z,(double)accel.length());gyro = ins.get_gyro(ii); ---> 获取gyroif (ii > gyro_count - 1) {// No gyro presentstate = '-';} else if (ins.get_gyro_health(ii)) {// Healthy gyrostate = 'h';} else {// Gyro present but not healthystate = 'u';}hal.console->printf(" Gyro (%c) : X:%6.2f Y:%6.2f Z:%6.2f\n",state, (double)gyro.x, (double)gyro.y, (double)gyro.z);auto temp = ins.get_temperature(ii);hal.console->printf(" t:%6.2f\n", (double)temp);}}// clear user inputwhile (hal.console->available()) {hal.console->read();}
}AP_HAL_MAIN(); --->>> 位于 /libraries/AP_HAL/AP_HAL_Main.h#include "HAL.h"#ifndef AP_MAIN
#define AP_MAIN main
#endif#define AP_HAL_MAIN() \AP_HAL::HAL::FunCallbacks callbacks(setup, loop); \ --->>> class HAL 中定义的嵌套类,只是承载setup和loop这两个函数指针extern "C" { \int AP_MAIN(int argc, char* const argv[]); \ --->>> main 函数声明 和 实现int AP_MAIN(int argc, char* const argv[]) { \ hal.run(argc, argv, &callbacks); \ --->>> run方法多态到四大平台的具体实现,如HAL_ChibiOS,后面分析return 0; \} \}#define AP_HAL_MAIN_CALLBACKS(CALLBACKS) extern "C" { \int AP_MAIN(int argc, char* const argv[]); \int AP_MAIN(int argc, char* const argv[]) { \hal.run(argc, argv, CALLBACKS); \return 0; \} \}void HAL_ChibiOS::run(int argc, char * const argv[], Callbacks* callbacks) const
{/** System initializations.* - ChibiOS HAL initialization, this also initializes the configured device drivers* and performs the board-specific initializations.* - Kernel initialization, the main() function becomes a thread and the* RTOS is active.*/#ifdef HAL_USB_PRODUCT_IDsetup_usb_strings();
#endif#ifdef HAL_STDOUT_SERIAL//STDOUT InitialistionSerialConfig stdoutcfg ={HAL_STDOUT_BAUDRATE,0,USART_CR2_STOP1_BITS,0};sdStart((SerialDriver*)&HAL_STDOUT_SERIAL, &stdoutcfg);
#endifassert(callbacks);g_callbacks = callbacks; --->>> static AP_HAL::HAL::Callbacks* g_callbacks;//Takeover main --->>> 接管mainmain_loop();
}static void main_loop()
{daemon_task = chThdGetSelfX();/*switch to high priority for main loop*/chThdSetPriority(APM_MAIN_PRIORITY);#ifdef HAL_I2C_CLEAR_BUS// Clear all I2C Buses. This can be needed on some boards which// can get a stuck I2C peripheral on bootChibiOS::I2CBus::clear_all();
#endif#if STM32_DMA_ADVANCEDChibiOS::Shared_DMA::init();
#endifperipheral_power_enable();hal.uartA->begin(115200);#ifdef HAL_SPI_CHECK_CLOCK_FREQ// optional test of SPI clock frequenciesChibiOS::SPIDevice::test_clock_freq();
#endif hal.uartB->begin(38400);hal.uartC->begin(57600);hal.analogin->init();hal.scheduler->init();/*run setup() at low priority to ensure CLI doesn't hang thesystem, and to allow initial sensor read loops to run*/hal_chibios_set_priority(APM_STARTUP_PRIORITY);if (stm32_was_watchdog_reset()) {// load saved watchdog datastm32_watchdog_load((uint32_t *)&utilInstance.persistent_data, (sizeof(utilInstance.persistent_data)+3)/4);}schedulerInstance.hal_initialized();g_callbacks->setup(); --->>> 回调前述setup框架方法#ifdef IOMCU_FWstm32_watchdog_init();
#elif !defined(HAL_BOOTLOADER_BUILD)// setup watchdog to reset if main loop stopsif (AP_BoardConfig::watchdog_enabled()) {stm32_watchdog_init();}if (hal.util->was_watchdog_reset()) {AP::internalerror().error(AP_InternalError::error_t::watchdog_reset);const AP_HAL::Util::PersistentData &pd = hal.util->persistent_data;AP::logger().WriteCritical("WDOG", "TimeUS,Task,IErr,IErrCnt,MavMsg,MavCmd,SemLine", "QbIIHHH",AP_HAL::micros64(),pd.scheduler_task,pd.internal_errors,pd.internal_error_count,pd.last_mavlink_msgid,pd.last_mavlink_cmd,pd.semaphore_line);}
#endifschedulerInstance.watchdog_pat();hal.scheduler->system_initialized();thread_running = true;chRegSetThreadName(SKETCHNAME);/*switch to high priority for main loop*/chThdSetPriority(APM_MAIN_PRIORITY);while (true) {g_callbacks->loop(); --->>> 回调前述loop框架方法/*give up 50 microseconds of time if the INS loop hasn'tcalled delay_microseconds_boost(), to ensure low prioritydrivers get a chance to run. Callingdelay_microseconds_boost() means we have already given uptime from the main loop, so we don't need to do it againhere*/
#ifndef HAL_DISABLE_LOOP_DELAYif (!schedulerInstance.check_called_boost()) {hal.scheduler->delay_microseconds(50);}
#endifschedulerInstance.watchdog_pat();}thread_running = false;
}
战略层次的总结:
-
系统平台和硬件由 class HAL 提供接口抽象, 四大系统软硬件平台分别进行了实现:HAL_ChibiOS, HAL_Linux, HAL_Empty, HAL_SITL,这样,将具体应用和底层系统硬件进行了解耦,具体应用只需操作HAL 接口类提供的硬件抽象接口,而当应用部署到具体的系统硬件平台时,具体系统硬件平台将实现该抽象接口,从而多态到具体的硬件,如此,我们可以将应用部署到真实系统硬件平台,或者部署到模拟的系统硬件平台来实现应用仿真;
-
class HAL 提供run的接口,用来启动应用,同时给系统平台提供封装了setup方法和loop方法的FunCallbacks接口类,系统平台实现run方法,并且在run方法中回调setup和loop;
-
应用的入口由AP_HAL_Main中的 AP_HAL_MAIN系列的宏函数提供,其使用应用实现的setup和loop方法,多态到具体系统软硬件平台实现run方法,也就是上面第二点;
-
应用比如大的:AntennaTracker, APMRover2, ArduCopter, ArduPlane, 等都提供setup和loop两个框架方法的实现, 并调用AP_HAL_MAIN入口来启动,小到一个传感器的测试用例比如AP_Compass_test也是如此;也就是应用层均使用面向接口编程,而这里的接口主要有以setup和loop为代表的启动运行接口,以及系统硬件平台的HAL接口。来看看具体的比如APMRover2: 其脉络非常清晰
class Rover : public AP_HAL::HAL::Callbacks --->>> 1.直接从封装接口框架setup和loop的抽象类CallBack进行派生,实现了setup和loop方法
const AP_HAL::HAL& hal = AP_HAL::get_HAL(); --->>> 2.获取具体的系统硬件平台实例, 比如在board pixhawk2.6+ChibiOS系统硬件平台上运行
Rover rover; --->>> 3.实例化一个rover
AP_HAL_MAIN_CALLBACKS(&rover); --->>> 4.调用入口宏main函数启动应用
这篇关于AP_HAL 再分析, 以pixhawk-fmuv2为硬件平台,ChibiOS为底层操作系统:的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!