当前位置: 首页 > news >正文

【STM32】CubeMX(十二):FreeRTOS消息队列

📘 【STM32】CubeMX(十二):FreeRTOS 消息队列数据收发详解

这篇文章主要介绍 使用 STM32 + HAL 库 + FreeRTOS 消息队列 实现任务间通信的完整过程。

在freeRTOS除了多线程之外,主要就是辅助单核的CPU解决任务之间的交互的问题。针对不同的应用场景,freeRTOS提供了4种不同的交互方式:消息队列,任务通知,信号量和互斥锁。我们这里主要介绍消息队列的使用方式。

一、什么是 FreeRTOS 消息队列?

FreeRTOS 消息队列(Message Queue)是一种任务间通信机制,这种机制主要用于:

功能说明
任务间传递数据类似邮箱或信箱,一个任务放入数据,另一个读取
实现异步事件处理比如按键中断 → 发送队列 → 任务中处理
支持中断发送可在中断中使用 xQueueSendFromISR
多任务安全内核自动调度,无需手动加锁

FreeRTOS中的消息队列机制:
请添加图片描述
在这里插入图片描述

FreeRTOS 提供的功能的详细说明也都可以在官方文档手册上找到

在这里插入图片描述

🛠️ 二、CubeMX 配置流程说明

✅ 步骤 1:启用 FreeRTOS

在【Software Packs】中勾选 X-CUBE-FREERTOS
选择 CMSIS_V1 接口

请添加图片描述

✅ 步骤 2:配置消息队列

在**【Tasks and Queues → Queues】**中添加两个队列:

Queue 名称队列长度单个元素大小
myQueue012uint8_t
myQueue022uint8_t
✅ 步骤 3:配置任务
  • StartDefaultTask → 发送 myQueue01 数据
  • myTask01 → 接收 myQueue01 / myQueue02 数据

请添加图片描述

🧩 三、代码结构说明(按模块分类)(提供完整代码示例)

✅ 1️⃣ 消息队列创建(freertos.c
osMessageQDef(myQueue01, 2, uint8_t);
myQueue01Handle = osMessageCreate(osMessageQ(myQueue01), NULL);osMessageQDef(myQueue02, 2, uint8_t);
myQueue02Handle = osMessageCreate(osMessageQ(myQueue02), NULL);
✅ 2️⃣ 任务发送 myQueue01(StartDefaultTask
if (Trg_Flag == 1)
{xQueueSend(myQueue01Handle, &Trg, 10);printf("myQueue01 is Send!\r\n");Trg_Flag = 0;
}

触发条件:读取 GPIO(PC1)按键状态变化。

✅ 3️⃣ 中断中发送 myQueue02(stm32f1xx_it.c)
xQueueSendFromISR(myQueue02Handle, &SendKey, &pxHigherPriorityTaskWoken);

触发条件:PA0 外部中断
作用:在中断中向队列发送数据(无需等待)

✅ 4️⃣ 任务接收(myTask01)
if(xQueueReceive(myQueue01Handle, &Key, 10) == pdPASS)
{printf("Recv Queue01 Key = %d\r\n", Key);
}if(xQueueReceive(myQueue02Handle, &Key_PA0, 10) == pdPASS)
{printf("Recv Queue01 Key_PA0 = %d\r\n", Key_PA0);
}

效果:只要有按键触发,中断或任务就能向队列发送,任务 myTask01 就能收到。

完整代码

📄 main.c

/* USER CODE BEGIN Header */
/********************************************************************************* @file           : main.c* @brief          : Main program body******************************************************************************* @attention** Copyright (c) 2025 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"
#include "cmsis_os.h"
#include "usart.h"
#include "gpio.h"/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "string.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);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP *//* USER CODE END PFP *//* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 *//* 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();MX_USART1_UART_Init();/* USER CODE BEGIN 2 */HAL_UARTEx_ReceiveToIdle_IT(  &huart1 , U1RxData, U1RxDataSize);/* USER CODE END 2 *//* Call init function for freertos objects (in freertos.c) */MX_FREERTOS_Init();/* Start scheduler */osKernelStart();/* We should never get here as control is now taken by the scheduler *//* 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};/** 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.HSEPredivValue = RCC_HSE_PREDIV_DIV1;RCC_OscInitStruct.HSIState = RCC_HSI_ON;RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;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_DIV2;RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK){Error_Handler();}
}/* USER CODE BEGIN 4 *//* 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 */

📄 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) 2025 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 "stm32f1xx_hal.h"/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "FreeRTOS.h"
#include "task.h"#include "cmsis_os.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 -----------------------------------------------------------*/
#define Key_UP_Pin GPIO_PIN_1
#define Key_UP_GPIO_Port GPIOC
#define PA0_Key_Pin GPIO_PIN_0
#define PA0_Key_GPIO_Port GPIOA
#define PA0_Key_EXTI_IRQn EXTI0_IRQn
#define LED_B_Pin GPIO_PIN_6
#define LED_B_GPIO_Port GPIOC
#define LED_G_Pin GPIO_PIN_7
#define LED_G_GPIO_Port GPIOC
#define LED_R_Pin GPIO_PIN_8
#define LED_R_GPIO_Port GPIOC
#define BEEP_Pin GPIO_PIN_9
#define BEEP_GPIO_Port GPIOC/* USER CODE BEGIN Private defines */extern osMessageQId myQueue01Handle;
extern osMessageQId myQueue02Handle;
/* USER CODE END Private defines */#ifdef __cplusplus
}
#endif#endif /* __MAIN_H */

📄 stm32f1xx_it.c

/* USER CODE BEGIN Header */
/********************************************************************************* @file    stm32f1xx_it.c* @brief   Interrupt Service Routines.******************************************************************************* @attention** Copyright (c) 2025 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"
#include "stm32f1xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "usart.h"#include "FreeRTOS.h"
#include "task.h"#include "cmsis_os.h"
/* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD *//* USER CODE END TD *//* 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 -----------------------------------------------*/
/* USER CODE BEGIN PFP *//* USER CODE END PFP *//* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 *//* USER CODE END 0 *//* External variables --------------------------------------------------------*/
extern UART_HandleTypeDef huart1;
extern TIM_HandleTypeDef htim6;/* USER CODE BEGIN EV *//* USER CODE END EV *//******************************************************************************/
/*           Cortex-M3 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/*** @brief This function handles Non maskable interrupt.*/
void NMI_Handler(void)
{/* USER CODE BEGIN NonMaskableInt_IRQn 0 *//* USER CODE END NonMaskableInt_IRQn 0 *//* USER CODE BEGIN NonMaskableInt_IRQn 1 */while (1){}/* USER CODE END NonMaskableInt_IRQn 1 */
}/*** @brief This function handles Hard fault interrupt.*/
void HardFault_Handler(void)
{/* USER CODE BEGIN HardFault_IRQn 0 *//* USER CODE END HardFault_IRQn 0 */while (1){/* USER CODE BEGIN W1_HardFault_IRQn 0 *//* USER CODE END W1_HardFault_IRQn 0 */}
}/*** @brief This function handles Memory management fault.*/
void MemManage_Handler(void)
{/* USER CODE BEGIN MemoryManagement_IRQn 0 *//* USER CODE END MemoryManagement_IRQn 0 */while (1){/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 *//* USER CODE END W1_MemoryManagement_IRQn 0 */}
}/*** @brief This function handles Prefetch fault, memory access fault.*/
void BusFault_Handler(void)
{/* USER CODE BEGIN BusFault_IRQn 0 *//* USER CODE END BusFault_IRQn 0 */while (1){/* USER CODE BEGIN W1_BusFault_IRQn 0 *//* USER CODE END W1_BusFault_IRQn 0 */}
}/*** @brief This function handles Undefined instruction or illegal state.*/
void UsageFault_Handler(void)
{/* USER CODE BEGIN UsageFault_IRQn 0 *//* USER CODE END UsageFault_IRQn 0 */while (1){/* USER CODE BEGIN W1_UsageFault_IRQn 0 *//* USER CODE END W1_UsageFault_IRQn 0 */}
}/*** @brief This function handles Debug monitor.*/
void DebugMon_Handler(void)
{/* USER CODE BEGIN DebugMonitor_IRQn 0 *//* USER CODE END DebugMonitor_IRQn 0 *//* USER CODE BEGIN DebugMonitor_IRQn 1 *//* USER CODE END DebugMonitor_IRQn 1 */
}/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f1xx.s).                    */
/******************************************************************************//*** @brief This function handles EXTI line0 interrupt.*/
void EXTI0_IRQHandler(void)
{/* USER CODE BEGIN EXTI0_IRQn 0 *//* USER CODE END EXTI0_IRQn 0 */HAL_GPIO_EXTI_IRQHandler(PA0_Key_Pin);/* USER CODE BEGIN EXTI0_IRQn 1 *//* USER CODE END EXTI0_IRQn 1 */
}/*** @brief This function handles USART1 global interrupt.*/
void USART1_IRQHandler(void)
{/* USER CODE BEGIN USART1_IRQn 0 *//* USER CODE END USART1_IRQn 0 */HAL_UART_IRQHandler(&huart1);/* USER CODE BEGIN USART1_IRQn 1 *//* USER CODE END USART1_IRQn 1 */
}/*** @brief This function handles TIM6 global interrupt.*/
void TIM6_IRQHandler(void)
{/* USER CODE BEGIN TIM6_IRQn 0 *//* USER CODE END TIM6_IRQn 0 */HAL_TIM_IRQHandler(&htim6);/* USER CODE BEGIN TIM6_IRQn 1 *//* USER CODE END TIM6_IRQn 1 */
}/* USER CODE BEGIN 1 */
BaseType_t pxHigherPriorityTaskWoken;void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{uint8_t SendKey = 0;if(GPIO_Pin == PA0_Key_Pin){if( HAL_GPIO_ReadPin( PA0_Key_GPIO_Port, PA0_Key_Pin) ==  GPIO_PIN_RESET){SendKey = HAL_GPIO_ReadPin( PA0_Key_GPIO_Port, PA0_Key_Pin);xQueueSendFromISR(myQueue02Handle,&SendKey,&pxHigherPriorityTaskWoken);printf("myQueue02 is Send ! \r\n");if(pxHigherPriorityTaskWoken){portYIELD_FROM_ISR(pxHigherPriorityTaskWoken); //任务切换}
//			HAL_GPIO_TogglePin( LED_G_GPIO_Port, LED_G_Pin );}}
}void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{U1RxLen = Size;HAL_UARTEx_ReceiveToIdle_IT(  &huart1 , U1RxData, U1RxDataSize);U1RxFlag = 1;
}/* USER CODE END 1 */

📄 freertos.c

/* USER CODE BEGIN Header */
/********************************************************************************* File Name          : freertos.c* Description        : Code for freertos applications******************************************************************************* @attention** Copyright (c) 2025 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 "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "usart.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 Variables *//* USER CODE END Variables */
osThreadId StartTaskHandle;
osThreadId myTask01Handle;
osMessageQId myQueue01Handle;
osMessageQId myQueue02Handle;/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes *//* USER CODE END FunctionPrototypes */void StartDefaultTask(void const * argument);
void StartTask01(void const * argument);void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) *//* GetIdleTaskMemory prototype (linked to static allocation support) */
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize );/* USER CODE BEGIN GET_IDLE_TASK_MEMORY */
static StaticTask_t xIdleTaskTCBBuffer;
static StackType_t xIdleStack[configMINIMAL_STACK_SIZE];void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize )
{*ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer;*ppxIdleTaskStackBuffer = &xIdleStack[0];*pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;/* place for user code */
}
/* USER CODE END GET_IDLE_TASK_MEMORY *//*** @brief  FreeRTOS initialization* @param  None* @retval None*/
void MX_FREERTOS_Init(void) {/* USER CODE BEGIN Init *//* USER CODE END Init *//* USER CODE BEGIN RTOS_MUTEX *//* add mutexes, ... *//* USER CODE END RTOS_MUTEX *//* USER CODE BEGIN RTOS_SEMAPHORES *//* add semaphores, ... *//* USER CODE END RTOS_SEMAPHORES *//* USER CODE BEGIN RTOS_TIMERS *//* start timers, add new ones, ... *//* USER CODE END RTOS_TIMERS *//* Create the queue(s) *//* definition and creation of myQueue01 */osMessageQDef(myQueue01, 2, uint8_t);myQueue01Handle = osMessageCreate(osMessageQ(myQueue01), NULL);/* definition and creation of myQueue02 */osMessageQDef(myQueue02, 2, uint8_t);myQueue02Handle = osMessageCreate(osMessageQ(myQueue02), NULL);/* USER CODE BEGIN RTOS_QUEUES *//* add queues, ... *//* USER CODE END RTOS_QUEUES *//* Create the thread(s) *//* definition and creation of StartTask */osThreadDef(StartTask, StartDefaultTask, osPriorityNormal, 0, 128);StartTaskHandle = osThreadCreate(osThread(StartTask), NULL);/* definition and creation of myTask01 */osThreadDef(myTask01, StartTask01, osPriorityHigh, 0, 128);myTask01Handle = osThreadCreate(osThread(myTask01), NULL);/* USER CODE BEGIN RTOS_THREADS *//* add threads, ... *//* USER CODE END RTOS_THREADS */}/* USER CODE BEGIN Header_StartDefaultTask */
/*** @brief  Function implementing the StartTask thread.* @param  argument: Not used* @retval None*/
/* USER CODE END Header_StartDefaultTask */
void StartDefaultTask(void const * argument)
{/* USER CODE BEGIN StartDefaultTask */
//	static	uint16_t KeyTime  = 0;
//	static	bool KeyFlag  = 0;printf("StartDefaultTask is Run ! \r\n");static	unsigned char Trg = 0;static	unsigned char Cont = 0xFF;uint8_t Trg_Flag = 0;/* Infinite loop */for(;;){unsigned char ReadData = HAL_GPIO_ReadPin( GPIOC, GPIO_PIN_1)^0xff;   // 1Trg = ReadData & (ReadData ^ Cont);      															// 2Cont = ReadData; if( Trg == 1){Trg_Flag = 1;}if(Trg_Flag == 1){xQueueSend(myQueue01Handle,&Trg,(TickType_t) 10);printf("myQueue01 is Send ! \r\n");Trg_Flag = 0;}osDelay(1);}/* USER CODE END StartDefaultTask */
}/* USER CODE BEGIN Header_StartTask01 */
/**
* @brief Function implementing the myTask01 thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask01 */
void StartTask01(void const * argument)
{/* USER CODE BEGIN StartTask01 */printf("StartTask01 is Run ! \r\n");uint8_t Key = 0;uint8_t Key_PA0 = 0;/* Infinite loop */for(;;){if(xQueueReceive( myQueue01Handle,&(Key),(TickType_t) 10) == pdPASS){printf("Recv Queue01 Key = %d  \r\n",Key);
//			HAL_GPIO_TogglePin(LED_B_GPIO_Port, LED_B_Pin);}if(xQueueReceive( myQueue02Handle,&(Key_PA0),(TickType_t) 10) == pdPASS){printf("Recv Queue01 Key_PA0 = %d  \r\n",Key_PA0);
//			HAL_GPIO_TogglePin(LED_B_GPIO_Port, LED_B_Pin);}osDelay(1);}/* USER CODE END StartTask01 */
}/* Private application code --------------------------------------------------*/
/* USER CODE BEGIN Application *//* USER CODE END Application */

四、串口调试效果

在这里插入图片描述

输出内容示例:

StartDefaultTask is Run!
StartTask01 is Run!
myQueue02 is Send!
Recv Queue01 Key_PA0 = 0
myQueue01 is Send!
Recv Queue01 Key = 1

✅ 说明:

myQueue01 → 来自轮询任务的按键输入
myQueue02 → 来自中断的按键输入
myTask01 → 成功接收到并打印

五、FreeRTOS 消息队列使用总结

操作函数说明
创建队列osMessageCreate()CubeMX 自动生成
发送数据xQueueSend()普通任务中使用
发送(中断)xQueueSendFromISR()中断中使用
接收数据xQueueReceive()通常在任务中阻塞接收
队列满返回 errQUEUE_FULL可设置超时
队列空返回 pdFALSE可设置阻塞等待时间

队列结构:

[任务A] --xQueueSend()--> [消息队列] --xQueueReceive()--> [任务B][中断] --xQueueSendFromISR()--> [消息队列] --> [任务B]

队列就像一个 “中转仓库” ,异步解耦任务之间通信。

以上。这便是 FreeRTOS 消息队列是 STM32 多任务系统中最常用的通信机制,适用于任务间、任务与中断之间的安全、可靠、非阻塞数据传输。

以上,欢迎有从事同行业的电子信息工程、互联网通信、嵌入式开发的朋友共同探讨与提问,我可以提供实战演示或模板库。希望内容能够对你产生帮助!

http://www.dtcms.com/a/350914.html

相关文章:

  • vue3+typescript:为表格生成唯一的Key/No
  • 二分|组合|旋转数组
  • SET FOREIGN_KEY_CHECKS=0
  • CentOS 部署 Prometheus 并用 systemd 管理
  • 似然函数对数似然函数负对数似然函数
  • 项目1:异步邮件发送系统实战
  • 自由学习记录(88)
  • 设计一个完整可用的 Spring Boot Starter
  • 深入浅出 ArrayList:从基础用法到底层原理的全面解析(下)
  • 2025职场进阶:低门槛技能实用手册
  • 编写Linux下usb设备驱动方法:probe函数中要进行的工作
  • css新特性
  • openharmony之DRM开发:数字知识产权保护揭秘
  • 智能体框架CAMEL-第三章
  • 学习嵌入式的第二十五天——哈希表和内核链表
  • 基于SpringBoot的物资管理系统【2026最新】
  • Linux网络服务(六)——iptables Forward实现内网服务暴露与访问外网
  • 直播美颜SDK技术解析:人脸美型功能的算法原理与实现方案
  • linux环境下 - 如何干净地卸载掉nvidia驱动
  • 工业通信协议综合调研报告
  • 深入浅出 ArrayList:从基础用法到底层原理的全面解析(上)
  • vue-Router中通过路由地址path中的数据转换为props传参,不建议添加多个可选参数
  • More Effective C++ 条款07:不要重载、和,操作符
  • linux的conda配置与应用阶段的简单指令备注
  • Typora + PicList + Gitee 图床完整配置教程
  • 《P1656 炸铁路》
  • C++ 编译链接杂谈——前向声明
  • JavaScript 类中静态变量与私有变量的区别及用法
  • eniac:世界上第一台通用电子计算机的传奇
  • 开发避坑指南(36):Java字符串Base64编码实战指南