#include <Arduino_FreeRTOS.h>
#include <semphr.h>
// Khai báo semaphore
SemaphoreHandle_t xSemaphore = NULL;
const int buttonPin = 2; // Nút nhấn nối với chân 2 (INT0)
const int ledPin = 13; // LED nối với chân 13
void handleButtonInterrupt() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
// Give the semaphore from ISR
xSemaphoreGiveFromISR(xSemaphore, &xHigherPriorityTaskWoken);
// Explicitly yield from ISR if required
if (xHigherPriorityTaskWoken) {
taskYIELD();
}
}
void taskLED(void *pvParameters) {
while (1) {
// Take the semaphore
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
// Bật LED trong 1 giây
digitalWrite(ledPin, HIGH);
vTaskDelay(pdMS_TO_TICKS(1000)); // Delay 1 giây
digitalWrite(ledPin, LOW);
}
}
}
void setup() {
Serial.begin(9600);
// Thiết lập chân button và LED
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
// Tạo binary semaphore
xSemaphore = xSemaphoreCreateBinary();
if (xSemaphore != NULL) {
// Tạo task LED
xTaskCreate(taskLED, "Task LED", 256, NULL, 1, NULL);
// Thiết lập ngắt cho nút nhấn
attachInterrupt(digitalPinToInterrupt(buttonPin), handleButtonInterrupt, FALLING);
// Bắt đầu scheduler
vTaskStartScheduler();
}
}
void loop() {
// Không cần làm gì trong loop vì FreeRTOS sẽ quản lý các task
}