准备说明

  FreeRTOS​ 是一个开源的、专为嵌入式系统设计的实时操作系统内核。它以其体积小、可裁剪性强、可靠性高的特点而闻名,非常适合在资源受限的微控制器上运行,是实现多任务应用的行业标准选择之一。
本次移植所使用的硬件平台为 STM32F103C8T6,软件层面采用 FreeRTOSv202406.01-LTS​ 版本,即最新的稳定版本,为应用程序提供多任务管理能力。
  为完成移植,需要准备以下资源:
    FreeRTOS 源码:操作系统内核源码,包含任务调度、队列、信号量等核心功能。
    STM32 标准外设库或HAL库:提供对 STM32 芯片硬件的底层操作接口。
    针对 Cortex-M3 架构的移植层代码:FreeRTOS 官方已提供,包含与处理器架构相关的上下文切换、系统时钟配置等关键例程。

FreeRTOS库下载
  官方渠道:
https://www.freertos.org/
  网盘备用地址: https://pan.baidu.com/s/1Mgny00UFzyvFX0YLbtz3XA?pwd=vu4b 提取码: vu4b

FreeRTOS源码的框架结构

  在v202406.01-LTS​ 版本中,存在许多额外的原生支持FreeRTOS的支持包。FreeRTOS从一个单一的操作系统内核,演进为一个针对物联网优化的完整软件生态系统。不过对于学习RTOS,开始只需要关注核心内核部分。其存在于文件夹\FreeRTOSv202406.01-LTS\FreeRTOS-LTS\FreeRTOS\FreeRTOS-Kernel下,目录结构如下:
在目录FreeRTOS-Kernel下的六个c文件就是FreeRTOS的核心文件:
在这里插入图片描述
  在include文件夹包含了所有我们需要的头文件(除去配置文件,移植过程讲):
在这里插入图片描述
  在portable文件夹存在针对不同硬件的移植文件,其中圈出来的是需要的文件:
在这里插入图片描述

  在MemMang文件夹中存放内存管理相关的文件:
在这里插入图片描述
  FreeRTOS 提供五种内存管理方案:heap_1 仅分配不释放,适用于初始化后不再动态创建对象的场景;heap_2 支持分配释放但易产生内存碎片,已过时不推荐;heap_3 是对标准库 malloc/free 的线程安全封装;heap_4 在支持分配释放的基础上增加了相邻空闲块合并功能,能有效减少碎片,是通用性最强的选择;heap_5 具备 heap_4 所有功能并支持将不连续的物理内存组合使用。
对于绝大多数应用,强烈推荐直接选用 heap_4.c。它在功能完整性、碎片控制能力和性能开销上取得了最佳平衡,能够安全、高效地满足任务、队列等内核对象频繁创建与删除的动态内存需求,是 FreeRTOS 社区验证最充分、最可靠的默认方案。

  由于STM32F103属于ARM Cortex-M3架构,所以在\RVDS\ARM_CM3目录下有其对应的移植层文件(port.c和portmacro.h):
在这里插入图片描述

移植过程

文件准备

  在工程创建FreeRTOS文件夹并在内部按上述目录结构创建如下三个文件夹:
在这里插入图片描述
  其中include存放\FreeRTOSv202406.01-LTS\FreeRTOS-LTS\FreeRTOS\FreeRTOS-Kernel\include文件夹下所有头文件。
  portable存放 heap_4.c和ARM_CM3文件夹下的port.c和portmacro.h。
  source存放上述六个内核核心c文件。

  并将所有c文件添加到工程中管理,如下:
在这里插入图片描述
  同时记得将所有头文件路径包含到工程头文件路径中。

配置文件准备

  在\FreeRTOSv202406.01-LTS\FreeRTOS-LTS\FreeRTOS\FreeRTOS-Kernel\examples\template_configuration路径下存在我们需要的配置文件FreeRTOSConfig.h:
在这里插入图片描述
  将其复制工程路径下,并加入工程方便管理:
在这里插入图片描述
  由于这个配置文件是官方提供的一个通用模板配置文件,包含了可能使用的配置,在实际应用中还需要根据自己所需的功能进行裁剪等操作。下面提供一个可以直接使用的版本,该版本尽量保持了原文件的结构不变并尽量对各个配置参数提供了说明:

/*
 * FreeRTOS Kernel V11.1.0
 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * SPDX-License-Identifier: MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * https://www.FreeRTOS.org
 * https://github.com/FreeRTOS
 *
 */

/*******************************************************************************
 * This file provides an example FreeRTOSConfig.h header file, inclusive of an
 * abbreviated explanation of each configuration item.  Online and reference
 * documentation provides more information.
 * https://www.freertos.org/a00110.html
 *
 * Constant values enclosed in square brackets ('[' and ']') must be completed
 * before this file will build.
 *
 * Use the FreeRTOSConfig.h supplied with the RTOS port in use rather than this
 * generic file, if one is available.
 ******************************************************************************/

#ifndef FREERTOS_CONFIG_H
#define FREERTOS_CONFIG_H

/******************************************************************************/
/* Hardware description related definitions. **********************************/
/******************************************************************************/

/* In most cases, configCPU_CLOCK_HZ must be set to the frequency of the clock
 * that drives the peripheral used to generate the kernels periodic tick interrupt.
 * The default value is set to 20MHz and matches the QEMU demo settings.  Your
 * application will certainly need a different value so set this correctly.
 * This is very often, but not always, equal to the main system clock frequency. */
#include <stdint.h>
extern uint32_t SystemCoreClock;
  
#define configCPU_CLOCK_HZ    ( SystemCoreClock ) //系统时钟

/* configSYSTICK_CLOCK_HZ is an optional parameter for ARM Cortex-M ports only.
 *
 * By default ARM Cortex-M ports generate the RTOS tick interrupt from the
 * Cortex-M SysTick timer. Most Cortex-M MCUs run the SysTick timer at the same
 * frequency as the MCU itself - when that is the case configSYSTICK_CLOCK_HZ is
 * not needed and should be left undefined. If the SysTick timer is clocked at a
 * different frequency to the MCU core then set configCPU_CLOCK_HZ to the MCU clock
 * frequency, as normal, and configSYSTICK_CLOCK_HZ to the SysTick clock
 * frequency.  Not used if left undefined.
 * The default value is undefined (commented out).  If you need this value bring it
 * back and set it to a suitable value. */

/*
 #define configSYSTICK_CLOCK_HZ                  [Platform specific]
 */

/******************************************************************************/
/* Scheduling behaviour related definitions. **********************************/
/******************************************************************************/

/* configTICK_RATE_HZ sets frequency of the tick interrupt in Hz, normally
 * calculated from the configCPU_CLOCK_HZ value. */
#define configTICK_RATE_HZ                         1000 //tick定时器频率

/* Set configUSE_PREEMPTION to 1 to use pre-emptive scheduling.  Set
 * configUSE_PREEMPTION to 0 to use co-operative scheduling.
 * See https://www.freertos.org/single-core-amp-smp-rtos-scheduling.html. */
#define configUSE_PREEMPTION                       1 //1为抢占式调度,0为合作式调度

/* Set configUSE_TIME_SLICING to 1 to have the scheduler switch between Ready
 * state tasks of equal priority on every tick interrupt.  Set
 * configUSE_TIME_SLICING to 0 to prevent the scheduler switching between Ready
 * state tasks just because there was a tick interrupt.  See
 * https://freertos.org/single-core-amp-smp-rtos-scheduling.html. */
#define configUSE_TIME_SLICING                     1 //时间片调度,当优先级相同时执行

/* Set configUSE_PORT_OPTIMISED_TASK_SELECTION to 1 to select the next task to
 * run using an algorithm optimised to the instruction set of the target hardware -
 * normally using a count leading zeros assembly instruction.  Set to 0 to select
 * the next task to run using a generic C algorithm that works for all FreeRTOS
 * ports.  Not all FreeRTOS ports have this option.  Defaults to 0 if left
 * undefined. */
 
/*
 * 某些运行FreeRTOs的硬件有两种方法选择下一个要执行的任务:
 *
 * 通用方法和特定于硬件的方法(以下简称"特殊方法")。
 * 通用方法:
 * 1.configUSE_PORT_OPTIMISED_TASK_SELECTION为О或者硬件不支持这种特殊方法。
 * 2.可以用于所有FreeRTOS支持的硬件
 * 3.完全用c实现,效率略低于特殊方法。
 * 4.不强制要求限制最大可用优先级数目

 * 特殊方法:
 * 1.必须将configUSE_PORT_OPTIMISED_TASK_SELECTION设置为1。
 * 2.依赖一个或多个特定架构的汇编指令(一般是类似计算前导零[CLZ]指令)。
 * 3.比通用方法更高效
 * 4.一般强制限定最大可用优先级数目为32
 * 一般是硬件计算前导零指令,如果所使用的,MCU没有这些硬件指令的话此宏应该设置为0 !
*/
#define configUSE_PORT_OPTIMISED_TASK_SELECTION    1

/* Set configUSE_TICKLESS_IDLE to 1 to use the low power tickless mode.  Set to
 * 0 to keep the tick interrupt running at all times.  Not all FreeRTOS ports
 * support tickless mode. See https://www.freertos.org/low-power-tickless-rtos.html
 * Defaults to 0 if left undefined. */
#define configUSE_TICKLESS_IDLE                    0 //置1:使能低功耗tickless模式;置0:保持系统节拍(tick)中断一直运行

/* configMAX_PRIORITIES Sets the number of available task priorities.  Tasks can
 * be assigned priorities of 0 to (configMAX_PRIORITIES - 1).  Zero is the lowest
 * priority. */
#define configMAX_PRIORITIES                       32  //可使用的最大优先级

/* configMINIMAL_STACK_SIZE defines the size of the stack used by the Idle task
 * (in words, not in bytes!).  The kernel does not use this constant for any other
 * purpose.  Demo applications use the constant to make the demos somewhat portable
 * across hardware architectures. */
 //空闲任务使用的堆栈的大小
#define configMINIMAL_STACK_SIZE                   128 //是128字,并非字节 即128*4个字节,堆栈大小以字为单位

/* configMAX_TASK_NAME_LEN sets the maximum length (in characters) of a task's
 * human readable name.  Includes the NULL terminator. */
#define configMAX_TASK_NAME_LEN                    16 //任务名称的最大长度

/* Time is measured in 'ticks' - which is the number of times the tick interrupt
 * has executed since the RTOS kernel was started.
 * The tick count is held in a variable of type TickType_t.
 *
 * configTICK_TYPE_WIDTH_IN_BITS controls the type (and therefore bit-width) of TickType_t:
 *
 * Defining configTICK_TYPE_WIDTH_IN_BITS as TICK_TYPE_WIDTH_16_BITS causes
 * TickType_t to be defined (typedef'ed) as an unsigned 16-bit type.
 *
 * Defining configTICK_TYPE_WIDTH_IN_BITS as TICK_TYPE_WIDTH_32_BITS causes
 * TickType_t to be defined (typedef'ed) as an unsigned 32-bit type.
 *
 * Defining configTICK_TYPE_WIDTH_IN_BITS as TICK_TYPE_WIDTH_64_BITS causes
 * TickType_t to be defined (typedef'ed) as an unsigned 64-bit type. */
#define configTICK_TYPE_WIDTH_IN_BITS              TICK_TYPE_WIDTH_32_BITS //TickType_t 类型位宽

/* Set configIDLE_SHOULD_YIELD to 1 to have the Idle task yield to an
 * application task if there is an Idle priority (priority 0) application task that
 * can run.  Set to 0 to have the Idle task use all of its timeslice.  Default to 1
 * if left undefined. */
#define configIDLE_SHOULD_YIELD                    1 //空闲任务可让出CPU给同等级任务

/* Each task has an array of task notifications.
 * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array.
 * See https://www.freertos.org/RTOS-task-notifications.html  Defaults to 1 if
 * left undefined. */
#define configTASK_NOTIFICATION_ARRAY_ENTRIES      1 //任务通知

/* configQUEUE_REGISTRY_SIZE sets the maximum number of queues and semaphores
 * that can be referenced from the queue registry.  Only required when using a
 * kernel aware debugger.  Defaults to 0 if left undefined. */
#define configQUEUE_REGISTRY_SIZE                  10 //队列和信号量的最大个数

/* Set configENABLE_BACKWARD_COMPATIBILITY to 1 to map function names and
 * datatypes from old version of FreeRTOS to their latest equivalent.  Defaults to
 * 1 if left undefined. */
#define configENABLE_BACKWARD_COMPATIBILITY        1 //映射函数名和从旧版本的FreeRTOS到其最新等效版本的数据类型

/* Each task has its own array of pointers that can be used as thread local
 * storage.  configNUM_THREAD_LOCAL_STORAGE_POINTERS set the number of indexes in
 * the array.  See https://www.freertos.org/thread-local-storage-pointers.html
 * Defaults to 0 if left undefined. */
#define configNUM_THREAD_LOCAL_STORAGE_POINTERS    0 //每个任务都有自己的指针数组

/* When configUSE_MINI_LIST_ITEM is set to 0, MiniListItem_t and ListItem_t are
 * both the same. When configUSE_MINI_LIST_ITEM is set to 1, MiniListItem_t contains
 * 3 fewer fields than ListItem_t which saves some RAM at the cost of violating
 * strict aliasing rules which some compilers depend on for optimization. Defaults
 * to 1 if left undefined. */
#define configUSE_MINI_LIST_ITEM                   1 //设置为1节省RAM

/* Sets the type used by the parameter to xTaskCreate() that specifies the stack
 * size of the task being created.  The same type is used to return information
 * about stack usage in various other API calls.  Defaults to size_t if left
 * undefined. */
#define configSTACK_DEPTH_TYPE                     size_t

/* configMESSAGE_BUFFER_LENGTH_TYPE sets the type used to store the length of
 * each message written to a FreeRTOS message buffer (the length is also written to
 * the message buffer.  Defaults to size_t if left undefined - but that may waste
 * space if messages never go above a length that could be held in a uint8_t. */
#define configMESSAGE_BUFFER_LENGTH_TYPE           size_t

/* If configHEAP_CLEAR_MEMORY_ON_FREE is set to 1, then blocks of memory allocated
 * using pvPortMalloc() will be cleared (i.e. set to zero) when freed using
 * vPortFree(). Defaults to 0 if left undefined. */
#define configHEAP_CLEAR_MEMORY_ON_FREE            1 //分配内存块

/* vTaskList and vTaskGetRunTimeStats APIs take a buffer as a parameter and assume
 * that the length of the buffer is configSTATS_BUFFER_MAX_LENGTH. Defaults to
 * 0xFFFF if left undefined.
 * New applications are recommended to use vTaskListTasks and
 * vTaskGetRunTimeStatistics APIs instead and supply the length of the buffer
 * explicitly to avoid memory corruption. */
#define configSTATS_BUFFER_MAX_LENGTH              1024 //统计功能函数缓冲区

/* Set configUSE_NEWLIB_REENTRANT to 1 to have a newlib reent structure
 * allocated for each task.  Set to 0 to not support newlib reent structures.
 * Default to 0 if left undefined.
 *
 * Note Newlib support has been included by popular demand, but is not used or
 * tested by the FreeRTOS maintainers themselves. FreeRTOS is not responsible for
 * resulting newlib operation. User must be familiar with newlib and must provide
 * system-wide implementations of the necessary stubs. Note that (at the time of
 * writing) the current newlib design implements a system-wide malloc() that must
 * be provided with locks. */
#define configUSE_NEWLIB_REENTRANT                 0 //Newlib结构

/******************************************************************************/
/* Software timer related definitions. ****************************************/
/******************************************************************************/

/* Set configUSE_TIMERS to 1 to include software timer functionality in the
 * build.  Set to 0 to exclude software timer functionality from the build.  The
 * FreeRTOS/source/timers.c source file must be included in the build if
 * configUSE_TIMERS is set to 1.  Default to 0 if left undefined.  See
 * https://www.freertos.org/RTOS-software-timer.html. */
#define configUSE_TIMERS                1 //启用软件定时器

/* configTIMER_TASK_PRIORITY sets the priority used by the timer task.  Only
 * used if configUSE_TIMERS is set to 1.  The timer task is a standard FreeRTOS
 * task, so its priority is set like any other task.  See
 * https://www.freertos.org/RTOS-software-timer-service-daemon-task.html  Only used
 * if configUSE_TIMERS is set to 1. */
#define configTIMER_TASK_PRIORITY       ( configMAX_PRIORITIES - 1 ) //软件定时器优先级

/* configTIMER_TASK_STACK_DEPTH sets the size of the stack allocated to the
 * timer task (in words, not in bytes!).  The timer task is a standard FreeRTOS
 * task.  See https://www.freertos.org/RTOS-software-timer-service-daemon-task.html
 * Only used if configUSE_TIMERS is set to 1. */
#define configTIMER_TASK_STACK_DEPTH    configMINIMAL_STACK_SIZE //软件定时器任务堆栈大小

/* configTIMER_QUEUE_LENGTH sets the length of the queue (the number of discrete
 * items the queue can hold) used to send commands to the timer task.  See
 * https://www.freertos.org/RTOS-software-timer-service-daemon-task.html  Only used
 * if configUSE_TIMERS is set to 1. */
#define configTIMER_QUEUE_LENGTH        10 //软件定时器队列长度

/******************************************************************************/
/* Event Group related definitions. *******************************************/
/******************************************************************************/

/* Set configUSE_EVENT_GROUPS to 1 to include event group functionality in the
 * build. Set to 0 to exclude event group functionality from the build. The
 * FreeRTOS/source/event_groups.c source file must be included in the build if
 * configUSE_EVENT_GROUPS is set to 1. Defaults to 1 if left undefined. */

#define configUSE_EVENT_GROUPS    1 //启用事件组功能

/******************************************************************************/
/* Stream Buffer related definitions. *****************************************/
/******************************************************************************/

/* Set configUSE_STREAM_BUFFERS to 1 to include stream buffer functionality in
 * the build. Set to 0 to exclude event group functionality from the build. The
 * FreeRTOS/source/stream_buffer.c source file must be included in the build if
 * configUSE_STREAM_BUFFERS is set to 1. Defaults to 1 if left undefined. */

#define configUSE_STREAM_BUFFERS    1 //流缓冲区功能,和事件组相关

/******************************************************************************/
/* Memory allocation related definitions. *************************************/
/******************************************************************************/

/* Set configSUPPORT_STATIC_ALLOCATION to 1 to include FreeRTOS API functions
 * that create FreeRTOS objects (tasks, queues, etc.) using statically allocated
 * memory in the build.  Set to 0 to exclude the ability to create statically
 * allocated objects from the build.  Defaults to 0 if left undefined.  See
 * https://www.freertos.org/Static_Vs_Dynamic_Memory_Allocation.html. */
#define configSUPPORT_STATIC_ALLOCATION              1 //支持静态创建函数

/* Set configSUPPORT_DYNAMIC_ALLOCATION to 1 to include FreeRTOS API functions
 * that create FreeRTOS objects (tasks, queues, etc.) using dynamically allocated
 * memory in the build.  Set to 0 to exclude the ability to create dynamically
 * allocated objects from the build.  Defaults to 1 if left undefined.  See
 * https://www.freertos.org/Static_Vs_Dynamic_Memory_Allocation.html. */
#define configSUPPORT_DYNAMIC_ALLOCATION             1 //支持动态内存申请

/* Sets the total size of the FreeRTOS heap, in bytes, when heap_1.c, heap_2.c
 * or heap_4.c are included in the build.  This value is defaulted to 4096 bytes but
 * it must be tailored to each application.  Note the heap will appear in the .bss
 * section.  See https://www.freertos.org/a00111.html. */
#define configTOTAL_HEAP_SIZE                        4096 //堆大小,字节单位

/* Set configAPPLICATION_ALLOCATED_HEAP to 1 to have the application allocate
 * the array used as the FreeRTOS heap.  Set to 0 to have the linker allocate the
 * array used as the FreeRTOS heap.  Defaults to 0 if left undefined. */
#define configAPPLICATION_ALLOCATED_HEAP             0 //0让链接器自动分配堆内存,1为手动

/* Set configSTACK_ALLOCATION_FROM_SEPARATE_HEAP to 1 to have task stacks
 * allocated from somewhere other than the FreeRTOS heap.  This is useful if you
 * want to ensure stacks are held in fast memory.  Set to 0 to have task stacks
 * come from the standard FreeRTOS heap.  The application writer must provide
 * implementations for pvPortMallocStack() and vPortFreeStack() if set to 1.
 * Defaults to 0 if left undefined. */
#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP    0      /* 1: 用户自行实现任务创建时使用的内存申请与释放函数, 默认: 0 */

/* Set configENABLE_HEAP_PROTECTOR to 1 to enable bounds checking and obfuscation
 * to internal heap block pointers in heap_4.c and heap_5.c to help catch pointer
 * corruptions. Defaults to 0 if left undefined. */
#define configENABLE_HEAP_PROTECTOR                  0

/******************************************************************************/
/* Interrupt nesting behaviour configuration. *********************************/
/******************************************************************************/

/* configKERNEL_INTERRUPT_PRIORITY sets the priority of the tick and context
 * switch performing interrupts.  Not supported by all FreeRTOS ports.  See
 * https://www.freertos.org/RTOS-Cortex-M3-M4.html for information specific to
 * ARM Cortex-M devices. */
 
/* 中断嵌套行为配置 */
#ifdef __NVIC_PRIO_BITS
    #define configPRIO_BITS __NVIC_PRIO_BITS
#else
    #define configPRIO_BITS 4
#endif


#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY         15                  /* 中断最低优先级 */
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY    5                   /* FreeRTOS可管理的最高中断优先级 */


#define configKERNEL_INTERRUPT_PRIORITY          ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )

/* configMAX_SYSCALL_INTERRUPT_PRIORITY sets the interrupt priority above which
 * FreeRTOS API calls must not be made.  Interrupts above this priority are never
 * disabled, so never delayed by RTOS activity.  The default value is set to the
 * highest interrupt priority (0).  Not supported by all FreeRTOS ports.
 * See https://www.freertos.org/RTOS-Cortex-M3-M4.html for information specific to
 * ARM Cortex-M devices. */
#define configMAX_SYSCALL_INTERRUPT_PRIORITY     ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )

/* Another name for configMAX_SYSCALL_INTERRUPT_PRIORITY - the name used depends
 * on the FreeRTOS port. */
#define configMAX_API_CALL_INTERRUPT_PRIORITY    configMAX_SYSCALL_INTERRUPT_PRIORITY

/******************************************************************************/
/* Hook and callback function related definitions. ****************************/
/******************************************************************************/

/* Set the following configUSE_* constants to 1 to include the named hook
 * functionality in the build.  Set to 0 to exclude the hook functionality from the
 * build.  The application writer is responsible for providing the hook function
 * for any set to 1.  See https://www.freertos.org/a00016.html. */
/* 钩子函数相关定义 */

#define configUSE_IDLE_HOOK                   0         /* 1: 使能空闲任务钩子函数, 无默认需定义  */
#define configUSE_TICK_HOOK                   0         /* 1: 使能系统时钟节拍中断钩子函数, 无默认需定义 */
#define configUSE_MALLOC_FAILED_HOOK          0         /* 1: 使能动态内存申请失败钩子函数, 默认: 0 */
#define configUSE_DAEMON_TASK_STARTUP_HOOK    0         /* 1: 使能定时器服务任务首次执行前的钩子函数, 默认: 0 */

/* Set configUSE_SB_COMPLETED_CALLBACK to 1 to have send and receive completed
 * callbacks for each instance of a stream buffer or message buffer. When the
 * option is set to 1, APIs xStreamBufferCreateWithCallback() and
 * xStreamBufferCreateStaticWithCallback() (and likewise APIs for message
 * buffer) can be used to create a stream buffer or message buffer instance
 * with application provided callbacks. Defaults to 0 if left undefined. */
#define configUSE_SB_COMPLETED_CALLBACK       0         /* 允许为每个流缓冲区或消息缓冲区实例单独设置发送/接收完成回调函数 */

/* Set configCHECK_FOR_STACK_OVERFLOW to 1 or 2 for FreeRTOS to check for a
 * stack overflow at the time of a context switch.  Set to 0 to not look for a
 * stack overflow.  If configCHECK_FOR_STACK_OVERFLOW is 1 then the check only
 * looks for the stack pointer being out of bounds when a task's context is saved
 * to its stack - this is fast but somewhat ineffective.  If
 * configCHECK_FOR_STACK_OVERFLOW is 2 then the check looks for a pattern written
 * to the end of a task's stack having been overwritten.  This is slower, but will
 * catch most (but not all) stack overflows.  The application writer must provide
 * the stack overflow callback when configCHECK_FOR_STACK_OVERFLOW is set to 1.
 * See https://www.freertos.org/Stacks-and-stack-overflow-checking.html  Defaults
 * to 0 if left undefined. */
#define configCHECK_FOR_STACK_OVERFLOW        0       /* 1: 使能栈溢出检测方法1, 2: 使能栈溢出检测方法2, 默认: 0 */

/******************************************************************************/
/* Run time and task stats gathering related definitions. *********************/
/******************************************************************************/

/* Set configGENERATE_RUN_TIME_STATS to 1 to have FreeRTOS collect data on the
 * processing time used by each task.  Set to 0 to not collect the data.  The
 * application writer needs to provide a clock source if set to 1.  Defaults to 0
 * if left undefined.  See https://www.freertos.org/rtos-run-time-stats.html. */
#define configGENERATE_RUN_TIME_STATS           0           /* 1: 使能任务运行时间统计功能, 默认: 0 */

/* Set configUSE_TRACE_FACILITY to include additional task structure members
 * are used by trace and visualisation functions and tools.  Set to 0 to exclude
 * the additional information from the structures. Defaults to 0 if left
 * undefined. */
#define configUSE_TRACE_FACILITY                0           /* 1: 使能可视化跟踪调试, 默认: 0 */

/* Set to 1 to include the vTaskList() and vTaskGetRunTimeStats() functions in
 * the build.  Set to 0 to exclude these functions from the build.  These two
 * functions introduce a dependency on string formatting functions that would
 * otherwise not exist - hence they are kept separate.  Defaults to 0 if left
 * undefined. */
#define configUSE_STATS_FORMATTING_FUNCTIONS    0           /* 1: configUSE_TRACE_FACILITY为1时,会编译vTaskList()和vTaskGetRunTimeStats()函数, 默认: 0 */

//定时器的初始化和定时需要自己实现
#if configGENERATE_RUN_TIME_STATS
    #include "./BSP/TIMER/btim.h"
    #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS()        ConfigureTimeForRunTimeStats()
    extern uint32_t FreeRTOSRunTimeTicks;
    #define portGET_RUN_TIME_COUNTER_VALUE()                FreeRTOSRunTimeTicks
#endif

/******************************************************************************/
/* Co-routine related definitions. ********************************************/
/******************************************************************************/

/* Set configUSE_CO_ROUTINES to 1 to include co-routine functionality in the
 * build, or 0 to omit co-routine functionality from the build. To include
 * co-routines, croutine.c must be included in the project. Defaults to 0 if left
 * undefined. */
 
/* 协程相关定义 */
 
#define configUSE_CO_ROUTINES              0            /* 1: 启用协程, 默认: 0 */

/* configMAX_CO_ROUTINE_PRIORITIES defines the number of priorities available
 * to the application co-routines. Any number of co-routines can share the same
 * priority. Defaults to 0 if left undefined. */
#define configMAX_CO_ROUTINE_PRIORITIES    1            /* 定义协程的最大优先级, 最大优先级=configMAX_CO_ROUTINE_PRIORITIES-1, 无默认configUSE_CO_ROUTINES为1时需定义 */

/******************************************************************************/
/* Debugging assistance. ******************************************************/
/******************************************************************************/

/* configASSERT() has the same semantics as the standard C assert().  It can
 * either be defined to take an action when the assertion fails, or not defined
 * at all (i.e. comment out or delete the definitions) to completely remove
 * assertions.  configASSERT() can be defined to anything you want, for example
 * you can call a function if an assert fails that passes the filename and line
 * number of the failing assert (for example, "vAssertCalled( __FILE__, __LINE__ )"
 * or it can simple disable interrupts and sit in a loop to halt all execution
 * on the failing line for viewing in a debugger. */
#define configASSERT( x )         \
    if( ( x ) == 0 )              \
    {                             \
        taskDISABLE_INTERRUPTS(); \
        for( ; ; )                \
        ;                         \
    }

/******************************************************************************/
/* FreeRTOS MPU specific definitions. *****************************************/
/******************************************************************************/

/* If configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS is set to 1 then
 * the application writer can provide functions that execute in privileged mode.
 * See: https://www.freertos.org/a00110.html#configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS
 * Defaults to 0 if left undefined.  Only used by the FreeRTOS Cortex-M MPU ports,
 * not the standard ARMv7-M Cortex-M port. */
#define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS    0

/* Set configTOTAL_MPU_REGIONS to the number of MPU regions implemented on your
 * target hardware.  Normally 8 or 16.  Only used by the FreeRTOS Cortex-M MPU
 * ports, not the standard ARMv7-M Cortex-M port.  Defaults to 8 if left
 * undefined. */
#define configTOTAL_MPU_REGIONS                                   8

/* configTEX_S_C_B_FLASH allows application writers to override the default
 * values for the for TEX, Shareable (S), Cacheable (C) and Bufferable (B) bits for
 * the MPU region covering Flash.  Defaults to 0x07UL (which means TEX=000, S=1,
 * C=1, B=1) if left undefined.  Only used by the FreeRTOS Cortex-M MPU ports, not
 * the standard ARMv7-M Cortex-M port. */
#define configTEX_S_C_B_FLASH                                     0x07UL

/* configTEX_S_C_B_SRAM allows application writers to override the default
 * values for the for TEX, Shareable (S), Cacheable (C) and Bufferable (B) bits for
 * the MPU region covering RAM. Defaults to 0x07UL (which means TEX=000, S=1, C=1,
 * B=1) if left undefined.  Only used by the FreeRTOS Cortex-M MPU ports, not
 * the standard ARMv7-M Cortex-M port. */
#define configTEX_S_C_B_SRAM                                      0x07UL

/* Set configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY to 0 to prevent any privilege
 * escalations originating from outside of the kernel code itself.  Set to 1 to
 * allow application tasks to raise privilege.  Defaults to 1 if left undefined.
 * Only used by the FreeRTOS Cortex-M MPU ports, not the standard ARMv7-M Cortex-M
 * port. */
#define configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY               1

/* Set configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS to 1 to allow unprivileged
 * tasks enter critical sections (effectively mask interrupts). Set to 0 to
 * prevent unprivileged tasks entering critical sections.  Defaults to 1 if left
 * undefined.  Only used by the FreeRTOS Cortex-M MPU ports, not the standard
 * ARMv7-M Cortex-M port. */
#define configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS                0

/* FreeRTOS Kernel version 10.6.0 introduced a new v2 MPU wrapper, namely
 * mpu_wrappers_v2.c. Set configUSE_MPU_WRAPPERS_V1 to 0 to use the new v2 MPU
 * wrapper. Set configUSE_MPU_WRAPPERS_V1 to 1 to use the old v1 MPU wrapper
 * (mpu_wrappers.c). Defaults to 0 if left undefined. */
#define configUSE_MPU_WRAPPERS_V1                                 0

/* When using the v2 MPU wrapper, set configPROTECTED_KERNEL_OBJECT_POOL_SIZE to
 * the total number of kernel objects, which includes tasks, queues, semaphores,
 * mutexes, event groups, timers, stream buffers and message buffers, in your
 * application. The application will not be able to have more than
 * configPROTECTED_KERNEL_OBJECT_POOL_SIZE kernel objects at any point of
 * time. */
#define configPROTECTED_KERNEL_OBJECT_POOL_SIZE                   10

/* When using the v2 MPU wrapper, set configSYSTEM_CALL_STACK_SIZE to the size
 * of the system call stack in words. Each task has a statically allocated
 * memory buffer of this size which is used as the stack to execute system
 * calls. For example, if configSYSTEM_CALL_STACK_SIZE is defined as 128 and
 * there are 10 tasks in the application, the total amount of memory used for
 * system call stacks is 128 * 10 = 1280 words. */
#define configSYSTEM_CALL_STACK_SIZE                              128

/* When using the v2 MPU wrapper, set configENABLE_ACCESS_CONTROL_LIST to 1 to
 * enable Access Control List (ACL) feature. When ACL is enabled, an
 * unprivileged task by default does not have access to any kernel object other
 * than itself. The application writer needs to explicitly grant the
 * unprivileged task access to the kernel objects it needs using the APIs
 * provided for the same. Defaults to 0 if left undefined. */
#define configENABLE_ACCESS_CONTROL_LIST                          1

/******************************************************************************/
/* SMP( Symmetric MultiProcessing ) Specific Configuration definitions. *******/
/******************************************************************************/

/* Set configNUMBER_OF_CORES to the number of available processor cores. Defaults
 * to 1 if left undefined. */

/*
* 定义处理器核心数量。若未定义,默认为1(单核)
 #define configNUMBER_OF_CORES                     [Num of available cores]
 */
 

/* When using SMP (i.e. configNUMBER_OF_CORES is greater than one), set
 * configRUN_MULTIPLE_PRIORITIES to 0 to allow multiple tasks to run
 * simultaneously only if they do not have equal priority, thereby maintaining
 * the paradigm of a lower priority task never running if a higher priority task
 * is able to run. If configRUN_MULTIPLE_PRIORITIES is set to 1, multiple tasks
 * with different priorities may run simultaneously - so a higher and lower
 * priority task may run on different cores at the same time. */
#define configRUN_MULTIPLE_PRIORITIES             0                 /* 控制是否允许多个不同优先级的任务在不同核心上并行运行 */

/* When using SMP (i.e. configNUMBER_OF_CORES is greater than one), set
 * configUSE_CORE_AFFINITY to 1 to enable core affinity feature. When core
 * affinity feature is enabled, the vTaskCoreAffinitySet and vTaskCoreAffinityGet
 * APIs can be used to set and retrieve which cores a task can run on. If
 * configUSE_CORE_AFFINITY is set to 0 then the FreeRTOS scheduler is free to
 * run any task on any available core. */
#define configUSE_CORE_AFFINITY                   0                 /* 1: 允许通过 vTaskCoreAffinitySet() 限制任务运行在指定核心, 默认: 0 */

/* When using SMP with core affinity feature enabled, set
 * configTASK_DEFAULT_CORE_AFFINITY to change the default core affinity mask for
 * tasks created without an affinity mask specified. Setting the define to 1 would
 * make such tasks run on core 0 and setting it to (1 << portGET_CORE_ID()) would
 * make such tasks run on the current core. This config value is useful, if
 * swapping tasks between cores is not supported (e.g. Tricore) or if legacy code
 * should be controlled. Defaults to tskNO_AFFINITY if left undefined. */
#define configTASK_DEFAULT_CORE_AFFINITY          tskNO_AFFINITY    /* 未指定绑定时任务的默认核心 */

/* When using SMP (i.e. configNUMBER_OF_CORES is greater than one), if
 * configUSE_TASK_PREEMPTION_DISABLE is set to 1, individual tasks can be set to
 * either pre-emptive or co-operative mode using the vTaskPreemptionDisable and
 * vTaskPreemptionEnable APIs. */
#define configUSE_TASK_PREEMPTION_DISABLE         0                 /* 1: 允许通过 vTaskPreemptionDisable() 临时禁止任务被抢占, 默认: 0 */

/* When using SMP (i.e. configNUMBER_OF_CORES is greater than one), set
 * configUSE_PASSIVE_IDLE_HOOK to 1 to allow the application writer to use
 * the passive idle task hook to add background functionality without the overhead
 * of a separate task. Defaults to 0 if left undefined. */
#define configUSE_PASSIVE_IDLE_HOOK               0                 /* 启用空闲核心的钩子函数 */

/* When using SMP (i.e. configNUMBER_OF_CORES is greater than one),
 * configTIMER_SERVICE_TASK_CORE_AFFINITY allows the application writer to set
 * the core affinity of the RTOS Daemon/Timer Service task. Defaults to
 * tskNO_AFFINITY if left undefined. */
#define configTIMER_SERVICE_TASK_CORE_AFFINITY    tskNO_AFFINITY    /* 设置定时器服务任务(Daemon Task)的核心绑定 */


/******************************************************************************/
/* ARMv8-M secure side port related definitions. ******************************/
/******************************************************************************/

/* secureconfigMAX_SECURE_CONTEXTS define the maximum number of tasks that can
 *  call into the secure side of an ARMv8-M chip.  Not used by any other ports. */
#define secureconfigMAX_SECURE_CONTEXTS        5

/* Defines the kernel provided implementation of
 * vApplicationGetIdleTaskMemory() and vApplicationGetTimerTaskMemory()
 * to provide the memory that is used by the Idle task and Timer task respectively.
 * The application can provide it's own implementation of
 * vApplicationGetIdleTaskMemory() and vApplicationGetTimerTaskMemory() by
 * setting configKERNEL_PROVIDED_STATIC_MEMORY to 0 or leaving it undefined. */
#define configKERNEL_PROVIDED_STATIC_MEMORY    1

/******************************************************************************/
/* ARMv8-M port Specific Configuration definitions. ***************************/
/******************************************************************************/

/* Set configENABLE_TRUSTZONE to 1 when running FreeRTOS on the non-secure side
 * to enable the TrustZone support in FreeRTOS ARMv8-M ports which allows the
 * non-secure FreeRTOS tasks to call the (non-secure callable) functions
 * exported from secure side. */
#define configENABLE_TRUSTZONE            0                     /* TrustZone安全扩展 */

/* If the application writer does not want to use TrustZone, but the hardware does
 * not support disabling TrustZone then the entire application (including the FreeRTOS
 * scheduler) can run on the secure side without ever branching to the non-secure side.
 * To do that, in addition to setting configENABLE_TRUSTZONE to 0, also set
 * configRUN_FREERTOS_SECURE_ONLY to 1. */
#define configRUN_FREERTOS_SECURE_ONLY    0                     /* TrustZone */

/* Set configENABLE_MPU to 1 to enable the Memory Protection Unit (MPU), or 0
 * to leave the Memory Protection Unit disabled. */
#define configENABLE_MPU                  0                     /* 内存保护单元 */

/* Set configENABLE_FPU to 1 to enable the Floating Point Unit (FPU), or 0
 * to leave the Floating Point Unit disabled. */
#define configENABLE_FPU                  0                     /* 硬件浮点单元 */

/* Set configENABLE_MVE to 1 to enable the M-Profile Vector Extension (MVE) support,
 * or 0 to leave the MVE support disabled. This option is only applicable to Cortex-M55
 * and Cortex-M85 ports as M-Profile Vector Extension (MVE) is available only on
 * these architectures. configENABLE_MVE must be left undefined, or defined to 0
 * for the Cortex-M23,Cortex-M33 and Cortex-M35P ports. */
#define configENABLE_MVE                  0                     /* M-Profile向量扩展(MVE)仅适用于Cortex-M55等架构 */

/******************************************************************************/
/* ARMv7-M and ARMv8-M port Specific Configuration definitions. ***************/
/******************************************************************************/

/* Set configCHECK_HANDLER_INSTALLATION to 1 to enable additional asserts to verify
 * that the application has correctly installed FreeRTOS interrupt handlers.
 *
 * An application can install FreeRTOS interrupt handlers in one of the following ways:
 *   1. Direct Routing  -  Install the functions vPortSVCHandler and xPortPendSVHandler
 *                         for SVC call and PendSV interrupts respectively.
 *   2. Indirect Routing - Install separate handlers for SVC call and PendSV
 *                         interrupts and route program control from those handlers
 *                         to vPortSVCHandler and xPortPendSVHandler functions.
 * The applications that use Indirect Routing must set configCHECK_HANDLER_INSTALLATION to 0.
 *
 * Defaults to 1 if left undefined. */
#define configCHECK_HANDLER_INSTALLATION    1                /* 确保中断处理程序正确安装的安全机制 */

/* FreeRTOS中断服务函数相关定义 */
#define xPortPendSVHandler                              PendSV_Handler
#define vPortSVCHandler                                 SVC_Handler


/******************************************************************************/
/* Definitions that include or exclude functionality. *************************/
/******************************************************************************/

/* Set the following configUSE_* constants to 1 to include the named feature in
 * the build, or 0 to exclude the named feature from the build. */
#define configUSE_TASK_NOTIFICATIONS           1            /* 1: 使能任务间直接的消息传递,包括信号量、事件标志组和消息邮箱, 默认: 1 */
#define configUSE_MUTEXES                      1            /* 1: 使能互斥信号量, 默认: 0 */
#define configUSE_RECURSIVE_MUTEXES            1            /* 1: 使能递归互斥信号量, 默认: 0 */
#define configUSE_COUNTING_SEMAPHORES          1            /* 1: 使能计数信号量, 默认: 0 */
#define configUSE_QUEUE_SETS                   0            /* 1: 使能队列集, 默认: 0 */
#define configUSE_APPLICATION_TASK_TAG         0            /* 1: 使能任务标签, 默认: 0 */

/* Set the following INCLUDE_* constants to 1 to incldue the named API function,
 * or 0 to exclude the named API function.  Most linkers will remove unused
 * functions even when the constant is 1. */
 
/* 可选函数, 1: 使能 */
#define INCLUDE_vTaskPrioritySet               1            /* 设置任务优先级 */
#define INCLUDE_uxTaskPriorityGet              1            /* 获取任务优先级 */
#define INCLUDE_vTaskDelete                    1            /* 删除任务 */
#define INCLUDE_vTaskSuspend                   1            /* 挂起任务 */
#define INCLUDE_xResumeFromISR                 1            /* 恢复在中断中挂起的任务 */
#define INCLUDE_vTaskDelayUntil                1            /* 任务绝对延时 */
#define INCLUDE_vTaskDelay                     1            /* 任务延时 */
#define INCLUDE_xTaskGetSchedulerState         1            /* 获取任务调度器状态 */
#define INCLUDE_xTaskGetCurrentTaskHandle      1            /* 获取当前任务的任务句柄 */
#define INCLUDE_uxTaskGetStackHighWaterMark    0            /* 获取任务堆栈历史剩余最小值 */
#define INCLUDE_xTaskGetIdleTaskHandle         0            /* 获取空闲任务的任务句柄 */
#define INCLUDE_eTaskGetState                  0            /* 获取任务状态 */
#define INCLUDE_xEventGroupSetBitFromISR       1            /* 在中断中设置事件标志位 */
#define INCLUDE_xTimerPendFunctionCall         0            /* 将函数的执行挂到定时器服务任务 */
#define INCLUDE_xTaskAbortDelay                0            /* 中断任务延时 */
#define INCLUDE_xTaskGetHandle                 0            /* 通过任务名获取任务句柄 */
#define INCLUDE_xTaskResumeFromISR             1            /* 恢复在中断中挂起的任务 */

#endif /* FREERTOS_CONFIG_H */

中断管理文件修改

  在stm32f10x_it.c文件中定义了许多空的中断函数,在使用FreeRTOS后需要对其进行修改。
  首先需要注释掉SVC_Handler和PendSV_Handler函数。
在这里插入图片描述

  在port.c中有FreeRTOS的对应实现,即vPortSVCHandler和xPortPendSVHandler

  然后为了让程序可以正确进入这两个函数,在FreeRTOSConfig.h中需要存在如下定义(上一节提供的配置文件已包含):
在这里插入图片描述
  最后需要改写SysTick_Handler函数,其作用为处理时间基准中断:
在这里插入图片描述

extern void xPortSysTickHandler( void );

void SysTick_Handler(void)
{
    if(xTaskGetSchedulerState()!=taskSCHEDULER_NOT_STARTED)//如果开启了调度
    {
        xPortSysTickHandler();
    }
}

  xPortSysTickHandler即为port.c中实现的对系统时钟节拍中断服务程序的核心处理函数。使用xTaskGetSchedulerState()!=taskSCHEDULER_NOT_STARTED判断的原因是为了防止中断开启后到FreeRTOS初始化完成这段时间内产生该中断后产生不可预测的错误。

  最后需要在stm32f10x_it.c添加对应的头文件:

#include "FreeRTOS.h"
#include "task.h"

移植结果测试

  为了测试移植是否成功,采用STM32C8T6最小系统板上的LED闪烁来测试。
以下是测试代码:
  led.c

#include "led.h"

#include "FreeRTOS.h"
#include "task.h"


void LED_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); //使能时钟
    
    GPIO_WriteBit(GPIOC, GPIO_Pin_13, (BitAction)1); //默认拉高(在初始化GPIO前赋值,可以解决初始化后电平错误问题)
    
    GPIO_InitTypeDef GPIO_InitStructure; //GPIO配置
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
}

void LED_Turn(void)
{
    uint8_t val = GPIO_ReadOutputDataBit(GPIOC, GPIO_Pin_13);
    GPIO_WriteBit(GPIOC, GPIO_Pin_13, (BitAction)(!val));
}

void LEDTask(void *arg)
{
    LED_Init();
    while(1)
    {
        LED_Turn();
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

  led.h

#ifndef __LED_H
#define __LED_H

#include "stm32f10x.h"                  // Device header

void LED_Init(void);

void LED_Turn(void);

void LEDTask(void *arg);


#endif

  main.c

#include "stm32f10x.h"

#include "FreeRTOS.h"
#include "task.h"

#include "led.h"




int main(void)
{
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    
    xTaskCreate(LEDTask, "LEDTask", 128, NULL, 24, NULL);
    
    vTaskStartScheduler(); //开启任务调度
    

    while(1)
    {

    }

}

  最终代码的现象为LED一秒翻转一次。

FreeRTOS时间基准说明

参数配置

  首先在配置文件FreeRTOSConfig.h中我们就设置好了系统主频和系统节拍频率:
在这里插入图片描述
  当没有设置configSYSTICK_CLOCK_HZ时其值会默认采用configCPU_CLOCK_HZ,其在port.c中定义如下,这个定义同时将portNVIC_SYSTICK_CLK_BIT_CONFIG的值定义为了( 1UL << 2UL )。
在这里插入图片描述

设置函数

  同样在port.c中,我们来到vPortSetupTimerInterrupt函数:
在这里插入图片描述
  可以看到其设置了portNVIC_SYSTICK_LOAD_REG和portNVIC_SYSTICK_CTRL_REG,其定义位于port.c上方:

#define portNVIC_SYSTICK_CTRL_REG             ( *( ( volatile uint32_t * ) 0xe000e010 ) )
#define portNVIC_SYSTICK_LOAD_REG             ( *( ( volatile uint32_t * ) 0xe000e014 ) )

寄存器设置

  在《STM32F10xxx Cortex-M3编程手册》中可以看到System tiimer的基地址刚好为0xe000e010,其对应STK_CTRL寄存器,而偏移量为4后0xe000e014对应STK_LOAD寄存器。
在这里插入图片描述
1.CTRL寄存器
  portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );其中对于STK_CTRL寄存器的配置将低三位都配置成了1,根据下图可知:
  bit2:为时钟源配置,由于我们没有设置configSYSTICK_CLOCK_HZ,所以在定义其为系统主频的时候将代表时钟源配置的宏portNVIC_SYSTICK_CLK_BIT_CONFIG定义为1,即直接选择AHB的时钟为SyaTick的时钟源。
  bit1:systick中断使能控制,设置为1即开启了中断使能,从而给FreeRTOS提供了时间基准。
  bit0:该位控制计数器是否工作,当该位被设置为1时,计数器开始从重装载值(LOAD寄存器设置)递减计数(这也说明了必须先设置LOAD后设置CTRL)。
在这里插入图片描述
2.LOAD寄存器
  LOAD寄存器的作用就是配置systick的重装值,在代码中被配置成了portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
这种配置方式满足周期产生中断的方式,系统频率/系统节拍频率算出了一个系统节拍所需的计时数,然后在-1,即设置为周期产生的标准数值。
在这里插入图片描述
  通过上述配置,FreeRTOS时间基准配置完成,其根据系统主频和设置的系统节拍数完成对系统滴答定时器的配置,从而得到时间基准。

函数调用关系

  最后说明一下vPortSetupTimerInterrupt函数的调用关系:
  首先从vTaskStartSchedule()进入,再到xPortStartScheduler(),最后调用vPortSetupTimerInterrupt()即在开启任务调度的过程中完成了对时间基准的配置。

Logo

openvela 操作系统专为 AIoT 领域量身定制,以轻量化、标准兼容、安全性和高度可扩展性为核心特点。openvela 以其卓越的技术优势,已成为众多物联网设备和 AI 硬件的技术首选,涵盖了智能手表、运动手环、智能音箱、耳机、智能家居设备以及机器人等多个领域。

更多推荐