STM32G431+Segger embos: 检测CPU使用率
SEGGER的实时操作系统(RTOS)embOS 已经集成到适用于基于Arm Cortex-M的MCU的STM32Cube扩展包中。
极大的方便用户评估embOS的性能及特性。
下面我将使用STM32CUBEMXIDE 配置embos。
MCU: STM32G431RBT6
IDE : STM32CUBEMXIDE Version: 1.19.0
G4CubePack :

embOS Pack:

首先需要安装G4CubePack 和 embOS Pack。
打开配置界面,进行基本的SYS,RCC等配置
1. SYS中选用TIM6作为HAL库的时间基,因为Systick将用于embOS, 采用2线Debug。

2.根据硬件实际的晶振配置:外部晶振16Mhz

3.使能RTOS embOS,使用默认配置参数。
这里我配置task和software timer后发现STM32CUBEMX 无法自动生成相关代码。不过无所谓,可以自己使用RTOS原生态接口去自己写代码。
可以参考embOS用户手册:https://www.segger.cn/downloads/embos/UM01001


4. NVIC

5. Clock 配置

6 生成代码,然后添加Segger RTT相关文件

7.配置debuger : JLINK

我在代码将使用RTT打印log, 先创建Task0,这个任务的主要是用来监控CPU使用率。
在Task0中创建Task1,Task1使用HAL_Delay模拟耗时操作,观察CPU使用率的变化。
main.h
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.h * @brief : Header for main.c file. * This file contains the common defines of the application. ****************************************************************************** * @attention * * Copyright (c) 2026 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MAIN_H #define __MAIN_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include <stdio.h> #include "SEGGER_RTT.h" /* USER CODE END Includes */ /* Exported types ------------------------------------------------------------*/ /* USER CODE BEGIN ET */ /* USER CODE END ET */ /* Exported constants --------------------------------------------------------*/ /* USER CODE BEGIN EC */ /* USER CODE END EC */ /* Exported macro ------------------------------------------------------------*/ /* USER CODE BEGIN EM */ /* USER CODE END EM */ /* Exported functions prototypes ---------------------------------------------*/ void Error_Handler(void); /* USER CODE BEGIN EFP */ /* USER CODE END EFP */ /* Private defines -----------------------------------------------------------*/ /* USER CODE BEGIN Private defines */ /* USER CODE END Private defines */ #ifdef __cplusplus } #endif #endif /* __MAIN_H */
main.c
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2026 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Scheduler includes. */ #include "RTOS.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* 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 */ volatile uint32_t cpuLoad = 0; static OS_STACKPTR int MeasureStack[256]; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ #ifdef __GNUC__ /* With GCC, small printf (option LD Linker->Libraries->Small printf set to 'Yes') calls __io_putchar() */ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #endif /* __GNUC__ */ /** * @brief Retargets the C library printf function to the RTT. * @param None * @retval None */ PUTCHAR_PROTOTYPE { /* Place your implementation of fputc here */ /* e.g. write a character to the RTT and Loop until the end of transmission */ #if defined(USE_ST_LINK) ITM_SendChar(ch); //ST-LINK #else SEGGER_RTT_PutChar(0,ch); //JLINK #endif return ch; } void Debug_Printf(char *format, ...) { #define DEBUG_ON 1 #if(DEBUG_ON == 1) char buf_str[256]; va_list v_args; va_start(v_args, format); (void)vsnprintf((char *)&buf_str[0], (size_t ) sizeof(buf_str), (char const *) format, v_args); va_end(v_args); printf("%s", buf_str); #endif } static OS_TASK TaskCB0; // Control block for Task0 static OS_STACKPTR int Stack0[256]; // Stack for Task0 static OS_TASK TaskCB1; // Control block for Task1 static OS_STACKPTR int Stack1[256]; // Stack for Task1 static void Task0(void); static void Task1(void); /* 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 */ SEGGER_RTT_Init(); SEGGER_RTT_printf(0, "Hello world!\r\n"); /* USER CODE END 2 */ /* Initialize the embOS kernel and configure the hardware parameters for embOS */ OS_Init(); OS_InitHW(); OS_TASK_Create(&TaskCB0, "Task0", 100, Task0, Stack0, sizeof(Stack0), 2); // Create Task0 /* Start embOS */ OS_Start(); /* 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}; /** Configure the main internal regulator output voltage */ HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST); /** 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 = RCC_PLLM_DIV4; RCC_OscInitStruct.PLL.PLLN = 85; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; 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_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /** * @brief Function implementing Task0. * @retval None */ void Task0(void) { /**************cpu load measurement**************************************/ OS_I32 DefaultMax; OS_TASK_Delay(500); DefaultMax = OS_IdleCnt; /* This value can be used as DefaultMaxValue. */ /* Now other tasks can be created and started. */ OS_STAT_AddLoadMeasurementEx(500, 0, DefaultMax, MeasureStack, 256); /**************cpu load measurement**************************************/ OS_TASK_Create(&TaskCB1, "Task1", 100, Task1, Stack1, sizeof(Stack1), 2); // Create Task1 while (1) { // // Application code // cpuLoad = OS_STAT_GetLoadMeasurement(); Debug_Printf("Task0 monitor CPU usage: %d%%\n", cpuLoad); /* The global variable OS_IdleCnt is implemented as a 32-bit signed integer value. embOS * internally calculates the delta between two OS_IdleCnt values. The delta must not exceed 0x7FFFFFFF. * If your CPU increments OS_IdleCnt too fast, you might need to choose a shorter time period */ OS_TASK_Delay(500u); } } /* USER CODE END Task0 */ /* USER CODE BEGIN Task1 */ /** * @brief Function implementing Task1. * @retval None */ void Task1(void) { while (1) { // // Application code // HAL_Delay(5); Debug_Printf("Task1 is running!\r\n"); OS_TASK_Delay(50); } } /* USER CODE END 4 */ /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM6 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM6) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ /* USER CODE END Callback 1 */ } /** * @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 */
测试效果:


浙公网安备 33010602011771号