FreeRTOS之二值信号量实验

1、 介绍二值信号量 ①在嵌入式操作系统中,二值信号量是任务间、任务与终端间同步的重要手段。 ②使用二值信号要包含#include "semphr.h"头文件 ③可以将二值信号量看做只有一个消息的队列,因此这个队列只能为空或满。 ④结构体简单介绍

typedef struct QueueDefinition
{
          
   
。。。
    List_t xTasksWaitingToSend;(1)
	List_t xTasksWaitingToReceive;(2)
    volatile UBaseType_t uxMessagesWaiting;(3)
。。。
 
} Queue_t;

(1)表示有效信号量的个数 (2)表示最大信号量 (3)恒定为0

2、 创建任务和二值信号量

void m_create_binary_sem(void)
{
          
   
    BinarySem_Handle = xSemaphoreCreateBinary();
    //BinarySem_Handle = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE );
    if(NULL != BinarySem_Handle)
    {
          
   
        LOG_BLE("BinarySem_Handle = NULL
");
    }
    xTaskCreate(send_task, "send_task", configMINIMAL_STACK_SIZE + 200, NULL, 2, &send_task_handle);
    xTaskCreate(receive_task, "receive_task", configMINIMAL_STACK_SIZE + 200, NULL, 2, &receive_task_handle);
}

3、 编写内存的测试任务入口函数

#include "semphr.h"

#ifndef TAG_BLE
#define LOG_BLE(...)
#endif

static QueueHandle_t BinarySem_Handle =NULL;
static TaskHandle_t  send_task_handle;
static TaskHandle_t  receive_task_handle;

static void send_task (void * pvParameter)
{
          
   
    BaseType_t xReturn = pdPASS;
    uint8_t button1_sta=0;
    while (true)
    {
          
   

        if (READ_BUTTON1_P11() == BUTTON_PUSH)
        {
          
   
            if (button1_sta==0)
            {
          
   
                xReturn = xSemaphoreGive( BinarySem_Handle );
                //xReturn = xQueueGenericSend( ( QueueHandle_t ) ( BinarySem_Handle ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK );
                if(pdPASS == xReturn)
				{
          
   
                    LOG_BLE("send binary sem ok
");
				} else
				{
          
   
					LOG_BLE("send binary sem error
");
				}
                button1_sta = 1;
            }
        } else
        {
          
   
            button1_sta = 0;
        }

        vTaskDelay(20);
    }
}

static void receive_task (void * pvParameter)
{
          
   
    BaseType_t xReturn = pdTRUE;
    while (true)
    {
          
   

        xReturn = xSemaphoreTake(BinarySem_Handle,portMAX_DELAY);
        if(pdTRUE == xReturn)
        {
          
   
            LOG_BLE("receive binary sem ok
");
            TOGGLE_LED13();
            TOGGLE_LED14();
            TOGGLE_LED15();
            TOGGLE_LED16();
        }
    }
}

3、实验说明和现象 ①发送任务检查到按键按下,将发送一个二值信号量。 ②接受任务阻塞等待二值信号,接受到二值信号时打印接受成功且LED反转电平。

经验分享 程序员 微信小程序 职场和发展