// Include necessary libraries and headers
#include <Arduino.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
// Define LED pin numbers
#define ledPin_Blue 2
#define ledPin_Red 3
// Declare a handle for the binary semaphore
SemaphoreHandle_t myBinarySemaphore;
// Setup function to initialize serial communication, pins, semaphore, and tasks
void setup() {
// Begin serial communication at 9600 baud rate
Serial.begin(9600);
// Set LED pins as output
pinMode(ledPin_Blue, OUTPUT);
pinMode(ledPin_Red, OUTPUT);
// Create a binary semaphore and immediately give it
myBinarySemaphore = xSemaphoreCreateBinary();
xSemaphoreGive(myBinarySemaphore);
// Create two tasks with the same priority
xTaskCreate(serialTask1, "serialTask1", 2000, NULL, 1, NULL);
xTaskCreate(serialTask2, "serialTask2", 2000, NULL, 1, NULL);
}
// Task 1 function
void serialTask1(void * parameters){
// Infinite loop
for(;;){
// Try to take the semaphore
if (xSemaphoreTake(myBinarySemaphore, portMAX_DELAY)){
// If successful, print a message, blink the blue LED, and give the semaphore back
Serial.println("This is task 1");
digitalWrite(ledPin_Blue, HIGH);
vTaskDelay(250/portTICK_PERIOD_MS);
digitalWrite(ledPin_Blue, LOW);
vTaskDelay(250/portTICK_PERIOD_MS);
xSemaphoreGive(myBinarySemaphore);
}
}
}
// Task 2 function
void serialTask2(void * parameters){
// Infinite loop
for(;;){
// Try to take the semaphore
if (xSemaphoreTake(myBinarySemaphore, portMAX_DELAY)){
// If successful, print a message, blink the red LED, and give the semaphore back
Serial.println("This is task 2");
digitalWrite(ledPin_Red, HIGH);
vTaskDelay(250/portTICK_PERIOD_MS);
digitalWrite(ledPin_Red, LOW);
vTaskDelay(250/portTICK_PERIOD_MS);
xSemaphoreGive(myBinarySemaphore);
}
}
}
// Main loop function
void loop() {}