#include <Arduino.h>
#include <Arduino_FreeRTOS.h>
#include <semphr.h>
#define BUTTON_PIN 2 // Sử dụng chân 2 thay vì chân 1 do chân 1 và 0 được sử dụng cho Serial
#define LED_PIN 13
SemaphoreHandle_t binarySemaphore;
void LED_Task(void *pvParameters);
void buttonISR();
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // Sử dụng PULLUP để tránh sử dụng thêm điện trở ngoài
// Create the binary semaphore
binarySemaphore = xSemaphoreCreateBinary();
if (binarySemaphore == NULL) {
Serial.println("Failed to create semaphore.");
while (1); // Halt the program if semaphore creation fails
}
// Attach interrupt to the button pin
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), buttonISR, FALLING);
// Create task
xTaskCreate(LED_Task, "LED Task", 128, NULL, 1, NULL);
// Start scheduler
vTaskStartScheduler();
}
void loop() {
// Empty. Tasks are handled by FreeRTOS.
}
void LED_Task(void *pvParameters) {
while (1) {
// Wait for the semaphore
if (xSemaphoreTake(binarySemaphore, portMAX_DELAY) == pdTRUE) {
// Turn on the LED
digitalWrite(LED_PIN, HIGH);
Serial.println("LED is ON");
// Wait for 1 second
vTaskDelay(pdMS_TO_TICKS(1000));
// Turn off the LED
digitalWrite(LED_PIN, LOW);
Serial.println("LED is OFF");
}
}
}
// Interrupt Service Routine (ISR)
void buttonISR() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
// Give the semaphore
xSemaphoreGiveFromISR(binarySemaphore, &xHigherPriorityTaskWoken);
// Yield to higher priority task
if (xHigherPriorityTaskWoken == pdTRUE) {
portYIELD();
}
}