#include <Arduino_FreeRTOS.h>
#include <semphr.h>
// Semaphore handle
SemaphoreHandle_t xSemaphore;
// Task 1
void Task1(void *pvParameters) {
while (1) {
// Wait for the semaphore to be free
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
Serial.println("Task 1: Acquired semaphore");
// Simulate task processing
vTaskDelay(pdMS_TO_TICKS(1000));
Serial.println("Task 1: Released semaphore");
// Release the semaphore
xSemaphoreGive(xSemaphore);
// Delay before next iteration
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
}
// Task 2
void Task2(void *pvParameters) {
while (1) {
// Wait for the semaphore to be free
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
Serial.println("Task 2: Acquired semaphore");
// Simulate task processing
vTaskDelay(pdMS_TO_TICKS(1000));
Serial.println("Task 2: Released semaphore");
// Release the semaphore
xSemaphoreGive(xSemaphore);
// Delay before next iteration
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
}
void setup() {
Serial.begin(115200);
// Create the semaphore
xSemaphore = xSemaphoreCreateMutex();
if (xSemaphore != NULL) {
// Create tasks
xTaskCreate(Task1, "Task 1", 128, NULL, 1, NULL);
xTaskCreate(Task2, "Task 2", 128, NULL, 1, NULL);
}
// Start the scheduler
vTaskStartScheduler();
}
void loop() {
// Do nothing
}