Create a binary semaphore with xSemaphoreCreateBinary
Create a FreeRTOS binary semaphore with xSemaphoreCreateBinary to signal a task from another task, and check for a NULL handle.
A binary semaphore is a one-slot flag that one task gives and another takes. It is the simplest way to say "the data is ready" between tasks. xSemaphoreCreateBinary() allocates it from the heap and returns NULL when there is no memory left.
static SemaphoreHandle_t ready;
static void producer(void *arg)
{
(void)arg;
vTaskDelay(pdMS_TO_TICKS(50));
printf("producer: data ready\n");
xSemaphoreGive(ready);
vTaskDelete(NULL);
}
static void consumer(void *arg)
{
(void)arg;
printf("consumer: waiting\n");
xSemaphoreTake(ready, portMAX_DELAY);
printf("consumer: got it\n");
vTaskDelete(NULL);
}
void app_start(void)
{
ready = xSemaphoreCreateBinary();
configASSERT(ready != NULL);
xTaskCreate(consumer, "cons", 256, NULL, 2, NULL);
xTaskCreate(producer, "prod", 256, NULL, 1, NULL);
}consumer: waiting
producer: data ready
consumer: got itThe consumer blocks on xSemaphoreTake() until the producer gives. A new binary semaphore starts empty, so the first take blocks, which is what you want for a signal and the opposite of a mutex. Giving it twice before a take still leaves one token: it does not count, which is the difference from a counting semaphore. If events can arrive faster than the consumer runs, you lose some, so use a counting semaphore or a queue.
The macro vSemaphoreCreateBinary() from older code created the semaphore full, which is why new code should use xSemaphoreCreateBinary() and its predictable empty start. Both exist in FreeRTOS Kernel 11.1. A binary semaphore does not give priority inheritance, so it is unsuitable for guarding a shared resource.