| Master The ESP32 WiFi: Practical Tasks |
| Written by Harry Fairhead and Mike James | |||
| Wednesday, 07 January 2026 | |||
Page 2 of 2
First To FinishAnother requirement is to wait for one of a group of tasks to finish. This is very easy using a semaphore, again assuming two cores, folder First: #include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_random.h"
SemaphoreHandle_t xSemaphore;
void task0(void *arg)
{
uint32_t delay = (esp_random() % 500) + 1;
vTaskDelay(delay);
printf("task0\n");
xSemaphoreGive(xSemaphore);
vTaskDelete(NULL);
}
void task1(void *arg)
{
uint32_t delay = (esp_random() % 500) + 1;
vTaskDelay(delay);
printf("task1\n");
xSemaphoreGive(xSemaphore);
vTaskDelete(NULL);
}
void app_main()
{
xSemaphore=xSemaphoreCreateBinary();
xTaskCreatePinnedToCore(task0,"task0", 4000,
In this case each task takes a random amount of time to complete and when it does it signals the app_main task that it has finished. The final task eventually completes, but it could be terminated by the app_main task.
All FinishedTo detect when a set of tasks has finished is a little more complicated, but the semaphore still does the job very well. The idea is that if you need to wait for N tasks to complete you need to Take the semaphore N times. To allow for all of the tasks to complete at exactly the same time the semaphore has to be able to store a count of N. Each task simply gives the semaphore when it has completed and the tasks waiting count the tasks off using a for loop, assuming two cores, folder All: #include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_random.h"
SemaphoreHandle_t xCountingSemaphore;
void task0(void *arg)
{
uint32_t delay = (esp_random() % 500) + 1;
vTaskDelay(delay);
printf("task0\n");
xSemaphoreGive(xCountingSemaphore);
vTaskDelete(NULL);
}
void task1(void *arg)
{
uint32_t delay = (esp_random() % 500) + 1;
vTaskDelay(delay);
printf("task1\n");
xSemaphoreGive(xCountingSemaphore);
vTaskDelete(NULL);
}
void app_main()
{
xCountingSemaphore = xSemaphoreCreateCounting(2, 0);
xTaskCreatePinnedToCore(task0, "task0", 4000,
The semaphore is set to 0 with a maximum count of 2 as there are only two tasks to monitor. In Chapter but not in this extract
Summary
MasterThe ESP32In C:
|
|||
| Last Updated ( Wednesday, 07 January 2026 ) |


