记得参加电赛那会单片机编程还是裸机编程(也就只会这个),后来接触到ucos,工作以后主要是linux开发,再后来在智能语音设备项目中涉及到的嵌入式MCU开发工作都是基于RTOS的。
目前市场上比较火的RTOS当属FreeRTOS,乐鑫的ESP32芯片的SDK就是在FreeRTOS的基础上构建的。当前国内也有比较有名的国产实时操作系统,例如上海瑞赛德公司的RT-thread(如果要快速做项目并且使用的芯片已经有了移植我这边还是强烈推荐使用RT-thread的)。
最近淘了一块STM32H750XBH6_ArtPi开发板(就是RT-thread出品),开发者完全可以基于此开发板提供的SDK进行开发(已经完全适配rtthread),但是本人还是想自己移植一下FreeRTOS。
说干就干,让我们开始吧。
关于FreeRTOS的资料也是一大堆,本人还是比较习惯于使用官网的资料(考虑到初学者可能刚接触FreeRTOS,对RTOS的概念可能也不太清楚,所以我这边计划后面专门出一个栏目介绍FreeRTOS系列)。
首先从官网下载FreeRTOS源码并解压如下(我下载的是202107的版本,可能你下载时版本已经更新,不用担心直接用即可)
我们关注FreeRTOS文件夹即可(FreeRTOS-Plus里面是一些高级功能暂时用不上)
上图中的include目录以及所有的.c文件就是FreeRTOS源代码,然后我们移植的时候需要这些。
其中,
croutine.c是协程的实现(基本不用);
event_group.c是事件组的实现用于线程间、线程与中断间同步;
list.c是其内部链表的实现;
queue.c是消息队列的实现用于线程间、线程与中断间同步;其中也实现了二值信号量和计数型信号量;
stream_buffer.c用于线程间、线程与中断间的数据通信;
tasks.c就是任务和调度器的实现(很重要)。
另外我们也需要portable目录下的一些文件,这些文件主要做了不同平台的适配,例如中断时的部分压栈出栈处理(有些寄存器的值是硬件自动进行的),portable文件夹里面内容如下,我们发现基于不同的编译器有对应的实现
其中MemMang里面包含了不同的动态内存分配,根据不同的场景我们需要选择合适的实现。本文我们着重讲解如何在Keil MDK下移植FreeRTOS,故需要Keil目录的内容,但其实RVDS只是Keil的别名,所以我们需要的文件在RVDS目录下。
我们的芯片为STM32H750XBH6,其是CM7内核,故我们需要如下文件
FreeRTOSv202107.00
Keil MDK V5.34
STM32CubeMX V6.3.0
下面我们来创建一个工程,使用STM32CubeMX生成一个Keil MDK工程,在这个工程中我们添加板载的LED的GPIO配置。然后我们创建两个任务(在RTOS的世界里任务可以理解为linux系统上的进程,可以完全独立,也可以相关之间有同步,这个后面我会出FreeRTOS指南来讲解)。
参考《手把手系列--使用STM32CubeMX生成代码工程》
为方便学习,这边提供的已经准备好的工程给大家下载。
我们通过STM32CubeMX生成工程为STM32H750XBH6_FreeRTOS_LED,在其目录下我们添加FreeRTOS文件夹,里面的内容即上面提到的FreeRTOS的源码部分。
下面我们打开Keil工程,如下
通过STM32CubeMX生成的工程没有任何问题。那下面我们在工程内加入FreeRTOS
相关内容。
首先我们需要添加分组FreeRTOS/kernal/src、FreeRTOS/kernal/port、FreeRTOS/heap
然后我们需要添加头文件路径
如果这个时候我们直接编译,则会报告如下错误
错误信息指明FreeRTOSConfig.h文件不存在。
由于FreeRTOS是一个可裁剪的OS,那我们在使用时就需要做一些配置,这个文件就是用来配置FreeRTOS的,那FreeRTOS下载包里面肯定有这个配置文件。
从FreeRTOS源码目录拷贝这个文件到工程目录下并添加到Keil MDK分组中,因为STM32H750属于CM7类型,所以我们直接使用STM32F7系列的也可以。
看错误信息很好理解,因为我们使用的H7系列,所以需要改成 #include "stm32h7xx_hal.h"
此处我们这样修改,将下图中的黄色框内的删除掉,在文件的头部添加#include "stm32h7xx_hal.h"
然后我们再次编译,输出如下错误
上面的错误是说有三个函数重复定义了,这个是因为FreeRTOS依赖这三个函数执行系统调度,但是我们使用STM32CubeMX生成的工程中也有这样的函数实现,那就需要我们进行简单修改:
我们注释掉FreeRTOSConfig.h中这一行#define xPortSysTickHandler SysTick_Handler
修改stm32h7xx_it.c文件,注释掉PendSV_Handler、SVC_Handler函数,并在Systick_Handler中添加截图中的代码
然后我们再次编译,然后我们再次如下错误
vApplicationStackOverflowHook、 vApplicationTickHook、 vApplicationMallocFailedHook这个函数分别是指栈溢出、Tick中断、内存分配失败时的钩子函数,我们暂时先禁用这些功能,只需要按照下图操作即可
完整的文件如下
/*
* FreeRTOS V202107.00
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
#ifndef FREERTOS_CONFIG_H
#define FREERTOS_CONFIG_H
/*-----------------------------------------------------------
* Application specific definitions.
*
* These definitions should be adjusted for your particular hardware and
* application requirements.
*
* THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
* FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
*
* See http://www.freertos.org/a00110.html
*----------------------------------------------------------*/
#include "stm32h7xx_hal.h"
#define configUSE_PREEMPTION 1
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1
#define configUSE_QUEUE_SETS 1
#define configUSE_IDLE_HOOK 0
#define configUSE_TICK_HOOK 0
#define configCPU_CLOCK_HZ ( SystemCoreClock )
#define configTICK_RATE_HZ ( 1000 )
#define configMAX_PRIORITIES ( 5 )
#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 130 )
#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 46 * 1024 ) )
#define configMAX_TASK_NAME_LEN ( 10 )
#define configUSE_TRACE_FACILITY 1
#define configUSE_16_BIT_TICKS 0
#define configIDLE_SHOULD_YIELD 1
#define configUSE_MUTEXES 1
#define configQUEUE_REGISTRY_SIZE 8
#define configCHECK_FOR_STACK_OVERFLOW 0
#define configUSE_RECURSIVE_MUTEXES 1
#define configUSE_MALLOC_FAILED_HOOK 0
#define configUSE_APPLICATION_TASK_TAG 0
#define configUSE_COUNTING_SEMAPHORES 1
/* The full demo always has tasks to run so the tick will never be turned off.
The blinky demo will use the default tickless idle implementation to turn the
tick off. */
#define configUSE_TICKLESS_IDLE 0
/* Run time stats gathering definitions. */
#define configGENERATE_RUN_TIME_STATS 0
/* This demo makes use of one or more example stats formatting functions. These
format the raw data provided by the uxTaskGetSystemState() function in to human
readable ASCII form. See the notes in the implementation of vTaskList() within
FreeRTOS/Source/tasks.c for limitations. */
#define configUSE_STATS_FORMATTING_FUNCTIONS 1
/* Co-routine definitions. */
#define configUSE_CO_ROUTINES 0
#define configMAX_CO_ROUTINE_PRIORITIES ( 2 )
/* Software timer definitions. */
#define configUSE_TIMERS 1
#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 )
#define configTIMER_QUEUE_LENGTH 5
#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 )
/* Set the following definitions to 1 to include the API function, or zero
to exclude the API function. */
#define INCLUDE_vTaskPrioritySet 1
#define INCLUDE_uxTaskPriorityGet 1
#define INCLUDE_vTaskDelete 1
#define INCLUDE_vTaskCleanUpResources 1
#define INCLUDE_vTaskSuspend 1
#define INCLUDE_vTaskDelayUntil 1
#define INCLUDE_vTaskDelay 1
#define INCLUDE_eTaskGetState 1
#define INCLUDE_xTimerPendFunctionCall 1
/* Cortex-M specific definitions. */
#ifdef __NVIC_PRIO_BITS
/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */
#define configPRIO_BITS __NVIC_PRIO_BITS
#else
#define configPRIO_BITS 4 /* 15 priority levels */
#endif
/* The lowest interrupt priority that can be used in a call to a "set priority"
function. */
#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 15
/* The highest interrupt priority that can be used by any interrupt service
routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL
INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER
PRIORITY THAN THIS! (higher priorities are lower numeric values. */
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 4
/* Interrupt priorities used by the kernel port layer itself. These are generic
to all Cortex-M ports, and do not rely on any particular library functions. */
#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */
#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS
standard names. */
#define xPortPendSVHandler PendSV_Handler
#define vPortSVCHandler SVC_Handler
//#define xPortSysTickHandler SysTick_Handler
#endif /* FREERTOS_CONFIG_H */
再次编译 后,我们发现没有错误。
接下来,我们在main.c里面添加业务代码以及运行FreeRTOS调度器。
上面代码的意思是,创建两个LED任务,任务优先级为2,一个任务一秒闪烁一次,另外一个0.5秒闪烁一次。
完整代码如下
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* © Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "freertos.h"
#include "task.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
static void led1_task(void *args) {
while (1)
{
HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_15);
vTaskDelay(1000);
}
//vTaskDelete(NULL);
}
static void led2_task(void *args) {
while (1)
{
HAL_GPIO_TogglePin(GPIOI, GPIO_PIN_8);
vTaskDelay(500);
}
//vTaskDelete(NULL);
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
/* USER CODE BEGIN 2 */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOI, GPIO_PIN_8, GPIO_PIN_SET);
SystemClock_Config();
xTaskCreate(led1_task, "led", configMINIMAL_STACK_SIZE, NULL, 2, NULL );
xTaskCreate(led2_task, "led", configMINIMAL_STACK_SIZE, NULL, 2, NULL );
vTaskStartScheduler();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Supply configuration update enable
*/
HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);
/** Configure the main internal regulator output voltage
*/
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);
while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 5;
RCC_OscInitStruct.PLL.PLLN = 192;
RCC_OscInitStruct.PLL.PLLP = 2;
RCC_OscInitStruct.PLL.PLLQ = 2;
RCC_OscInitStruct.PLL.PLLR = 2;
RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_2;
RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
RCC_OscInitStruct.PLL.PLLFRACN = 0;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
|RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOI_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOI, GPIO_PIN_8, GPIO_PIN_RESET);
/*Configure GPIO pin : PC15 */
GPIO_InitStruct.Pin = GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : PI8 */
GPIO_InitStruct.Pin = GPIO_PIN_8;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOI, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
编译后下载,我们可以看到板载LED按照我们代码的逻辑进行闪烁,至此我们就完成了FreeRTOS的基本移植。
关于FreeRTOS的知识,后面我会出FreeRTOS系列文章帮助大家进行学习掌握。
完整工程下载地址
链接:https://pan.baidu.com/s/1OuXvAUmIxGLkTd6HT6tfmA
提取码:xdgq