#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/semphr.h>
// Define the mutex
SemaphoreHandle_t mutex = NULL;
// Function prototypes
void Task1(void *pvParameters);
void Task2(void *pvParameters);
void setup() {
// Create Mutex
mutex = xSemaphoreCreateMutex();
// Create Task 1
xTaskCreate(Task1, "Task1", 10000, NULL, 1, NULL);
// Create Task 2
xTaskCreate(Task2, "Task2", 10000, NULL, 1, NULL);
}
void loop() {
// Empty, tasks are running independently
}
void Task1(void *pvParameters) {
while (1) {
// Take Mutex
if (xSemaphoreTake(mutex, portMAX_DELAY) == pdTRUE) {
// Call Task 2
xTaskCreate(Task2, "Task2", 10000, NULL, 1, NULL);
// Release Mutex
xSemaphoreGive(mutex);
}
// Delay for demonstration purposes
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void Task2(void *pvParameters) {
// Request Mutex
if (xSemaphoreTake(mutex, portMAX_DELAY) == pdTRUE) {
// Call library function such as printf
printf("Task 2 executed.\n");
// Release Mutex
xSemaphoreGive(mutex);
}
// Delete self after execution
vTaskDelete(NULL);
}