FreeRTOS消息队列

好久没有写代码了,有很多都忘记了,今天重新复习一下消息队列,使用标准库和hal库分别完成消息队列的实验

1.消息队列的使用

1.1 首先创建消息队列的句柄

QueueHandle_t queue_key;

1.2使用api函数xQueueCreate( uxQueueLength, uxItemSize ) 进行队列的创建

queue_key = xQueueCreate(2,sizeof(uint8_t));
	  if(queue_key != NULL)
		{
				printf("queue_key队列创建成功 \r\n");
		}
		else
		{
				printf("queue_key队列创建失败 \r\n");
		}

通过第一步创建的队列句柄queue_key接收队列创建函数的返回值,并进行判断

1.3使用xQueueSend( xQueue, pvItemToQueue, xTicksToWait )进行写入操作,运用如下例子所示

void task1(void *parameters)
{
	 uint16_t key = 0;
	 BaseType_t rev = 0;
	 char * buff;
	 buff = &buf[0];
	 for(;;)
	 {
			key = Key_GetNum();
		  if(key == 1)
			{
					printf("key_1 按下,将小数据写入数组 \r\n");
				  rev = xQueueSend(queue_key, &key, portMAX_DELAY );
				  if(rev!=pdTRUE)
					{
							printf("queue_key发送失败! \r\n");
					}
				  LED1_Turn();
			}
			else if(key==2)
			{
					printf("key_11 按下,将大据写入地址数组 \r\n");
				  xQueueSend(queue_2, &buff, portMAX_DELAY );
				  LED2_Turn();
			}
	 }
	 vTaskDelay(10);
}

1.4BaseType_t xQueueReceive( QueueHandle_t xQueue,void * const pvBuffer, TickType_t xTicksToWait )进行出队列操作,也即从队列接收数据(取数据)

void task2(void *parameters)
{
	  BaseType_t rev = 0;
	  uint8_t key_val = 0;
	  for(;;)
		{
			 rev = xQueueReceive(queue_key,&key_val,portMAX_DELAY);
			 if(rev != pdTRUE)
			 {
					printf("读取queue_key 失败!\r\n");
			 }
			 else
			 {
				 printf("读取queue_key 成功,键值为%d \r\n",key_val);
			 }
		}
}

2.实验

实验目的:实现队列的入队和出队操作

实验设计:将四个任务:start_task、task1、task2、task3

start_task:用来创建task1-task3任务

task1:当key_0按下,将键值拷贝到队列queue_key;当key_1按下,将传输字符串数据,这里通过拷贝字符串的首地址入队(queue_strdata)实现传输字符串

task2: 读取queue_key队列的数据

task3: 读取queue_strdata的数据

2.1标准库

main.c

#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "OLED.h"
#include "Serial.h"
#include "FreeRTOS.h"
#include "task.h"
#include "LED.h"
#include "FreeRTOSConfig.h"
#include "timers.h"
#include "freertos_demo.h"
#include "Key.h"
#include "queue.h"
uint8_t RxData;			//定义用于接收串口数据的变量


int main(void)
{

	LED_Init();
	Key_Init();
	/*串口初始化*/
	Serial_Init();		//串口初始化
	freertos_demo();

	return 0;

}

其中freertos_demo()包含所有队列的操作

#include "freertos_demo.h"
#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "OLED.h"
#include "Serial.h"
#include "FreeRTOS.h"
#include "task.h"
#include "LED.h"
#include "FreeRTOSConfig.h"
#include "timers.h"
#include "stdio.h"
#include "Key.h"
#include "queue.h"


#define START_TASK_PRIO         1
#define START_TASK_STACK_SIZE   128
TaskHandle_t    start_task_handler;
void start_task( void * pvParameters );

//vtask1 实现入队
#define TASK1_STACK_SIZE  128
#define TASK1_PRIO 2
TaskHandle_t task1_handler;
void task1(void *parameters);

//vtask2 实现小数据出队
#define TASK2_STACK_SIZE  128
#define TASK2_PRIO 3
TaskHandle_t task2_handler;
void task2(void *parameters);

//vtask3 实现大数据出队
#define TASK3_STACK_SIZE  128
#define TASK3_PRIO 4
TaskHandle_t task3_handler;
void task3(void *parameters);


//	ctreate queue
QueueHandle_t queue_key;/*小数据*/
QueueHandle_t queue_2;/*大数据*/

char buf[100] = "这是一个大数组,12345n";
void freertos_demo(void)
{
		
	  queue_key = xQueueCreate(2,sizeof(uint8_t));
	  if(queue_key != NULL)
		{
				printf("queue_key队列创建成功 \r\n");
		}
		else
		{
				printf("queue_key队列创建失败 \r\n");
		}
		
		queue_2 = xQueueCreate(2,sizeof(char *));
	  if(queue_2 != NULL)
		{
				printf("queue_2队列创建成功 \r\n");
		}
		else
		{
				printf("queue_2队列创建失败 \r\n");
		}
		
		xTaskCreate((TaskFunction_t         )   start_task,
                (char *                 )   "start_task",
                (configSTACK_DEPTH_TYPE )   START_TASK_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   START_TASK_PRIO,
                (TaskHandle_t *         )   &start_task_handler );
    vTaskStartScheduler();
}

void start_task(void *parameters)
{
	//进入临界区
	taskENTER_CRITICAL();
	xTaskCreate((TaskFunction_t         )   task1,
                (char *                 )   "task1",
                (configSTACK_DEPTH_TYPE )   TASK1_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   TASK1_PRIO,
                (TaskHandle_t *         )   &task1_handler );
	xTaskCreate((TaskFunction_t         )   task2,
                (char *                 )   "task2",
                (configSTACK_DEPTH_TYPE )   TASK2_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   TASK2_PRIO,
                (TaskHandle_t *         )   &task2_handler );
	xTaskCreate((TaskFunction_t         )   task3,
                (char *                 )   "task3",
                (configSTACK_DEPTH_TYPE )   TASK3_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   TASK3_PRIO,
                (TaskHandle_t *         )   &task3_handler );
	//退出临界区
	vTaskDelete(NULL);
	taskEXIT_CRITICAL();
}

void task1(void *parameters)
{
	 uint16_t key = 0;
	 BaseType_t rev = 0;
	 char * buff;
	 buff = &buf[0];
	 for(;;)
	 {
			key = Key_GetNum();
		  if(key == 1)
			{
					printf("key_1 按下,将小数据写入数组 \r\n");
				  rev = xQueueSend(queue_key, &key, portMAX_DELAY );
				  if(rev!=pdTRUE)
					{
							printf("queue_key发送失败! \r\n");
					}
				  LED1_Turn();
			}
			else if(key==2)
			{
					printf("key_11 按下,将大据写入地址数组 \r\n");
				  xQueueSend(queue_2, &buff, portMAX_DELAY );
				  LED2_Turn();
			}
	 }
	 vTaskDelay(10);
}

void task2(void *parameters)
{
	  BaseType_t rev = 0;
	  uint8_t key_val = 0;
	  for(;;)
		{
			 rev = xQueueReceive(queue_key,&key_val,portMAX_DELAY);
			 if(rev != pdTRUE)
			 {
					printf("读取queue_key 失败!\r\n");
			 }
			 else
			 {
				 printf("读取queue_key 成功,键值为%d \r\n",key_val);
			 }
		}
}

void task3(void *parameters)
{
		BaseType_t rev = 0;
		char* buff;
	  for(;;)
		{
			rev = xQueueReceive(queue_2,&buff,portMAX_DELAY);
			 if(rev != pdTRUE)
			 {
					printf("读取queue_2 失败!\r\n");
			 }
			 else
			 {
				 printf("读取queue_2 成功,键值为 %s\r\n",buff);
			 }
			
		}
}

实验结果:

2.2hal库

main.c

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 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.
  *
  ******************************************************************************
  */

#include <stdio.h>
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "Key.h"
#include "led.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define LED1_GPIO_Port GPIOB
#define LED1_Pin GPIO_PIN_1
#define LED2_GPIO_Port GPIOB
#define LED2_Pin GPIO_PIN_11


/* 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);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE BEGIN 0 */
#include <stdio.h>

 #ifdef __GNUC__
     #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 USART.
     *@param  None
     *@retval None
 ******************************************************************/
 PUTCHAR_PROTOTYPE
 {
     HAL_UART_Transmit(&huart1, (uint8_t *)&ch,1,0xFFFF);
     return ch;
 }
 
 
#define START_TASK_PRIO         1
#define START_TASK_STACK_SIZE   128
TaskHandle_t    start_task_handler;
void start_task( void * pvParameters );

//vtask1 实现入队
#define TASK1_STACK_SIZE  128
#define TASK1_PRIO 2
TaskHandle_t task1_handler;
void task1(void *parameters);

//vtask2 实现小数据出队
#define TASK2_STACK_SIZE  128
#define TASK2_PRIO 3
TaskHandle_t task2_handler;
void task2(void *parameters);
 
 
//vtask3 实现大数据出队
#define TASK3_STACK_SIZE  128
#define TASK3_PRIO 4
TaskHandle_t task3_handler;
void task3(void *parameters);


QueueHandle_t queue_key;
QueueHandle_t queue_strdata;

char buff[100] = "this is a test for transmmit a data to queue!";
 
void start_task(void *parameters)
{
	//进入临界
	taskENTER_CRITICAL();
	xTaskCreate((TaskFunction_t         )   task1,
                (char *                 )   "task1",
                (configSTACK_DEPTH_TYPE )   TASK1_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   TASK1_PRIO,
                (TaskHandle_t *         )   &task1_handler );
	xTaskCreate((TaskFunction_t         )   task2,
                (char *                 )   "task2",
                (configSTACK_DEPTH_TYPE )   TASK2_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   TASK2_PRIO,
                (TaskHandle_t *         )   &task2_handler );
	xTaskCreate((TaskFunction_t         )   task3,
                (char *                 )   "task3",
                (configSTACK_DEPTH_TYPE )   TASK3_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   TASK3_PRIO,
                (TaskHandle_t *         )   &task3_handler );
	//出临界区
	vTaskDelete(NULL);
	taskEXIT_CRITICAL();
}

void task1(void *parameters)
{
	  BaseType_t rev = 0 ;
	  uint8_t key = 0;
	  char *buf;
	  buf = buff;
		while(1)
		{
			  key = Key_GetNum();
			  if(key == 1)
				{
						printf("Key0被按下 \r\n");
						rev = xQueueSend( queue_key, &key, portMAX_DELAY );
					  if(rev != pdTRUE)
						{
								printf("queue_key写入队列失败! \r\n");
						}
					LED1_Turn();
				}
				if(key == 2)
				{
						printf("Key1被按下 \r\n");
						rev = xQueueSend( queue_strdata, &buf, portMAX_DELAY );
					  if(rev != pdTRUE)
						{
								printf("queue_strdata写入队列失败! \r\n");
						}
						LED2_Turn();
				}
		}
		vTaskDelay(10);
}


void task2(void *parameters)
{
	  BaseType_t rev = 0;
	  uint8_t key_val = 0;
		while(1)
		{
			 rev = xQueueReceive(queue_key,&key_val,portMAX_DELAY);
			 if(rev != pdTRUE)
			 {
					printf("读取queue_key 失败!\r\n");
			 }
			 else
			 {
				 printf("读取queue_key 成功,键值为%d \r\n",key_val);
			 }
		}
		//vTaskDelay(500);
}
void task3(void *parameters)
{
	  BaseType_t rev = 0;
	  char* buf  = 0;
		while(1)
		{
				rev = xQueueReceive(queue_strdata,&buf,portMAX_DELAY);
			 if(rev != pdTRUE)
			 {
					printf("读取queue_strdata 失败!\r\n");
			 }
			 else
			 {
				 printf("读取queue_strdata 成功,键值为 %s\r\n",buf);
			 }
		}

}
void freertos_demo(void)
{
	/*创建队列*/
	queue_key = xQueueCreate(2,sizeof(uint8_t));
	if(queue_key!=NULL)
	{
			printf("queue_key队列创建成功 \r\n");
	}
	else
		printf("queue_key队列创建失败 \r\n");
	
	queue_strdata = xQueueCreate(2,sizeof(char *));
	if(queue_strdata!=NULL)
	{
			printf("queue_strdata队列创建成功 \r\n");
	}
	else
		printf("queue_strdata队列创建失败 \r\n");
	
	xTaskCreate((TaskFunction_t         )   start_task,
                (char *                 )   "start_task",
                (configSTACK_DEPTH_TYPE )   START_TASK_STACK_SIZE,
                (void *                 )   NULL,
                (UBaseType_t            )   START_TASK_PRIO,
                (TaskHandle_t *         )   &start_task_handler );
	vTaskStartScheduler();
	
}
/* 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 */
	freertos_demo();
	
	return 0;
  /* 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};

  /** 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 TIM2 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 == TIM2) {
    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 */

实验结果:

ps:完整工程访问FreeRTOS消息队列实验-hal库资源-CSDN下载FreeRTOS消息队列-标准库资源-CSDN下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值