// Include necessary libraries and headers
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <freertos/semphr.h>
#include "freertos/queue.h"
#define RED_LED_PIN 2
#define BLUE_LED_PIN 4
int globalVariable = 0;
QueueHandle_t serialQueue;
SemaphoreHandle_t globalVariableSemaphore;
// First Function
void redLedTask(void *pvParameters) {
pinMode(RED_LED_PIN, OUTPUT);
while (1) {
digitalWrite(RED_LED_PIN, HIGH);
vTaskDelay(pdMS_TO_TICKS(200)); //required: 2.5 Hz
digitalWrite(RED_LED_PIN, LOW);
vTaskDelay(pdMS_TO_TICKS(200));
}
}
// Second Function
void blueLedTask(void *pvParameters) {
pinMode(BLUE_LED_PIN, OUTPUT);
while (1) {
digitalWrite(BLUE_LED_PIN, HIGH);
vTaskDelay(pdMS_TO_TICKS(500)); // required: 1 Hz
digitalWrite(BLUE_LED_PIN, LOW);
vTaskDelay(pdMS_TO_TICKS(500));
}
}
// Third Function
void serialTask(void *pvParameters) {
(void)pvParameters;
serialQueue = xQueueCreate(5, sizeof(int));
while (1) {
// Wait for the semaphore before accessing the global variable
if (xSemaphoreTake(globalVariableSemaphore, portMAX_DELAY)) {
// Send global variable to the queue
xQueueSend(serialQueue, &globalVariable, portMAX_DELAY);
// Increment global variable
globalVariable++;
// Release the semaphore
xSemaphoreGive(globalVariableSemaphore);
}
// Delay for a while
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void setup() {
// Create tasks
xTaskCreate(redLedTask, "RedLedTask", 1000, NULL, 2, NULL);
xTaskCreate(blueLedTask, "BlueLedTask", 1000, NULL, 2, NULL);
xTaskCreate(serialTask, "SerialTask", 1000, NULL, 1, NULL);
// Create semaphore
globalVariableSemaphore = xSemaphoreCreateMutex();
// Start scheduler
vTaskStartScheduler();
}
void loop() {
// Access the global variable within the loop function
if (xSemaphoreTake(globalVariableSemaphore, portMAX_DELAY)) {
// Do something with the global variable (e.g., print it)
Serial.println(globalVariable);
// Release the semaphore
xSemaphoreGive(globalVariableSemaphore);
}
// Add any other non-blocking code here if needed
delay(1000); // Delay for a while
}