#include <Arduino_FreeRTOS.h> // FreeRTOS library for Arduino
#include <semphr.h> // For semaphore functions
// Variables
SemaphoreHandle_t semaphore; // Declare the semaphore
volatile int i = 0; // Shared variable updated in ISR
volatile int j = 0; // Counter for cycles
volatile int x[8] = {0}; // Array initialized to 0
// ISR
void ISR_Handler() {
i++;
xSemaphoreGiveFromISR(semaphore, NULL); // Give semaphore from ISR
}
// Task1
void Task1(void *pvParameters) {
int w = 0;
for (;;) {
if (xSemaphoreTake(semaphore, portMAX_DELAY) == pdTRUE) { // Wait for semaphore
if (i > 7) {
i = 0;
j++;
}
x[i] = j; // Update array
// Print the values of x for debugging
Serial.print("x array: ");
for (int k = 0; k < 8; k++) {
Serial.print(x[k]);
w++;
Serial.print(w);
}
Serial.println();
}
}
}
void setup() {
// Initialize serial for debugging
Serial.begin(9600);
// Create semaphore and initialize it to BUSY
semaphore = xSemaphoreCreateBinary();
if (semaphore == NULL) {
Serial.println("Failed to create semaphore!");
while (1);
}
// Start semaphore as BUSY
xSemaphoreTake(semaphore, 0);
// Attach the ISR
attachInterrupt(digitalPinToInterrupt(2), ISR_Handler, RISING);
// Create Task1
xTaskCreate(Task1, "Task1", 128, NULL, 1, NULL);
// Start the FreeRTOS scheduler
vTaskStartScheduler();
}
void loop() {
// This will remain empty as tasks are handled by FreeRTOS
}