06_FreeRTOS队列(结构体队列)
如果要发送不同的数据类型,则必须使用结构体队列。
xQueueHandle St_Queue_Handler;
定义结构体:
typedef struct {
char *str;
int counter;
uint16_t large_value;
} my_struct;
创造队列:
/***** create QUEUE *****/
osMessageQDef(Queue01, 1, my_struct);
Queue01Handle = osMessageCreate(osMessageQ(Queue01), NULL);
if (Queue01Handle == 0) // Queue not created
{
printf("Unable to create Integer Queue\n");
}else{
printf("Integer Queue Created successfully\n");
}
线程的优先级:
/* definition and creation of Task1 */
osThreadDef(Task1, Task1_init, 2, 0, 512);
Task1Handle = osThreadCreate(osThread(Task1), NULL);
/* definition and creation of Task2 */
osThreadDef(Task2, Task2_init, 2, 0, 512);
Task2Handle = osThreadCreate(osThread(Task2), NULL);
/* definition and creation of Task3 */
osThreadDef(Task3, Task3_init, 1, 0, 512);
Task3Handle = osThreadCreate(osThread(Task3), NULL);
然后通过这个Task把数据传输到队列中去:
void Task1_init(void const * argument)
{
/* USER CODE BEGIN 5 */
my_struct *ptrtostruct;
uint32_t TickDelay = pdMS_TO_TICKS(2000);
/* Infinite loop */
for(;;)
{
printf("Entered Task1\n");
/****** 给结构体指针分配内存 ********/
ptrtostruct = pvPortMalloc(sizeof (my_struct));
/********** 向结构体中填充数据 ***********/
ptrtostruct->counter = 1+indx1;
ptrtostruct->large_value = 1000 + indx1*100;
ptrtostruct->str = "Task1 entered ";
/***** 把数据发送到队列 ****/
if (xQueueSend(Queue01Handle, &ptrtostruct, portMAX_DELAY) == pdPASS)
{
printf("Successfully sent from Task1\n");
}
indx1 = indx1+1;
vTaskDelay(TickDelay);
}
/* USER CODE END 5 */
}
void Task2_init(void const * argument)
{
/* USER CODE BEGIN Task2_init */
my_struct *ptrtostruct;
uint32_t TickDelay = pdMS_TO_TICKS(2000);
/* Infinite loop */
for(;;)
{
printf("Entered task2\n");
/**** 为结构体指针分配内存****/
ptrtostruct = pvPortMalloc(sizeof(my_struct));
/**** 把结构体中填充数据 ****/
ptrtostruct->str = "Task2 entered!!!";
ptrtostruct->large_value = 2000 + 200*indx2;
ptrtostruct->counter = 1+indx2;
if (xQueueSend(Queue01Handle,&ptrtostruct,portMAX_DELAY) == pdPASS)
{
printf(" Successfully sent from Task2 \n");
}
indx2 = indx2+1;
vTaskDelay(TickDelay);
}
/* USER CODE END Task2_init */
}
在将数据发送到队列之前,我们必须将内存分配给该结构。为此,我们使用函数pvPortMALLOC
分配内存后,将数据加载到指向该结构的指针中。
接下来,我们将通过在参数中传递其地址,将该数据发送到Queue。
我们将在Task3函数中创建另一个指向struct的指针,以存储接收到的数据。接收到数据后,我们将使用vPortFREE功能释放发送方Task分配的内存。
void Task3_init(void const * argument)
{
/* USER CODE BEGIN Task3_init */
my_struct *Rptrtostruct;
uint32_t TickDelay = pdMS_TO_TICKS(1000);
/* Infinite loop */
for(;;)
{
printf("Enter task3\n-----------\n");
/**** 接收队列数据 *****/
if (xQueueReceive(Queue01Handle, &Rptrtostruct, portMAX_DELAY) == pdPASS)
{
printf ("Received from QUEUE:\n COUNTER = %d LARGE VALUE = %u STRING = %s\n",Rptrtostruct->counter,Rptrtostruct->large_value, Rptrtostruct->str);
}
vPortFree(Rptrtostruct); //使用vPortFree 释放结构体内存
vTaskDelay(TickDelay);
}
/* USER CODE END Task3_init */
}
结果: