freertos-porting.md 3.0 KB


type: concept title: FreeRTOS 移植指南 tags: [freertos, rtos, porting, stm32, hal, config, concept]

created: 2026-07-12

FreeRTOS 移植指南

源码结构

FreeRTOS/
├── Demo/           演示例程(多芯片架构)
├── License/        许可
├── Source/         核心源码
│   ├── include/    头文件(通用)
│   ├── portable/   移植文件(编译器相关)
│   │   ├── Keil/  → 指向 RVDS
│   │   ├── RVDS/  不同内核芯片移植文件
│   │   │   └── ARM_CM3/   port.c + portmacro.h
│   │   └── MemMang/heap_1~5.c
│   ├── tasks.c     任务管理
│   ├── queue.c     队列
│   ├── timers.c    软件定时器
│   ├── event_groups.c
│   ├── stream_buffer.c
│   └── list.c      列表
└── Test/           测试代码

port.c:上下文切换等核心汇编代码,由 FreeRTOS 官方为各内核编写。portmacro.h:数据类型和宏定义。

移植步骤(HAL 库)

1. 目录添加源码

Project/
├── FreeRTOS/
│   ├── portable/   (Keil + RVDS + MemMang)
│   └── source/     (7 个 .c 文件)
└── Core/Inc/FreeRTOSConfig.h

2. 工程添加文件

  • 新建 Group FreeRTOS/SourceFreeRTOS/Portable
  • Source 组添加 7 个 .c 文件
  • Portable 组添加 port.c + heap_4.c
  • 添加头文件路径:include/RVDS/ARM_CM3/

3. 修改 FreeRTOSConfig.h

#define xPortPendSVHandler    PendSV_Handler
#define vPortSVCHandler       SVC_Handler
#define INCLUDE_xTaskGetSchedulerState   1

4. 修改 stm32f1xx_it.c

  • include "FreeRTOS.h""task.h"
  • 注释掉 SVC_Handler()PendSV_Handler()
  • 添加 SysTick 中断服务函数:

    extern void xPortSysTickHandler(void);
    
    void SysTick_Handler(void) {
    if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
        xPortSysTickHandler();
    }
    }
    

注意:HAL 和 FreeRTOS 都默认依赖 SysTick,建议在 CubeMX SYS 配置中将 HAL 时基换成其他定时器。

系统配置文件 FreeRTOSConfig.h

配置项分三类:

类别 格式 说明
函数使能 INCLUDE_函数名 1=可用,0=禁用
功能配置 configXXX 基本/内存/钩子/中断配置
其他 宏定义 PendSV/SVC 映射

关键配置项

#define configUSE_PREEMPTION           1   // 抢占式调度
#define configCPU_CLOCK_HZ             SystemCoreClock
#define configTICK_RATE_HZ             1000  // 系统节拍频率
#define configMAX_PRIORITIES           32
#define configMINIMAL_STACK_SIZE       128
#define configTOTAL_HEAP_SIZE          ((size_t)(10 * 1024))
#define configUSE_MUTEXES              1
#define configUSE_COUNTING_SEMAPHORES  1
#define configUSE_TIMERS               1
#define configUSE_TICKLESS_IDLE        0

相关页面

  • [[source-freertos|尚硅谷 FreeRTOS 教程 - 资料页]]
  • [[freertos-system-services|系统服务(定时器、低功耗、内存)]]