#include <Arduino_FreeRTOS.h>
#include <semphr.h>
// Định nghĩa các chân kết nối
#define BUTTON_PIN 2
#define LED_PIN 13
// Biến toàn cục để lưu trữ semaphore
SemaphoreHandle_t xBinarySemaphore;
// Interrupt Service Routine (ISR) cho button
void handleButtonInterrupt() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
// Give semaphore từ ISR
xSemaphoreGiveFromISR(xBinarySemaphore, &xHigherPriorityTaskWoken);
// Yield task nếu cần thiết
if (xHigherPriorityTaskWoken == pdTRUE) {
taskYIELD(); // Thay thế portYIELD_FROM_ISR
}
}
// Task để bật LED khi nhận được semaphore
void Task_LED_Control(void *pvParameters) {
(void) pvParameters;
for (;;) {
// Chờ để nhận semaphore
if (xSemaphoreTake(xBinarySemaphore, portMAX_DELAY) == pdTRUE) {
// Bật LED
digitalWrite(LED_PIN, HIGH);
Serial.println("LED is ON");
// Chờ 1 giây
vTaskDelay(1000 / portTICK_PERIOD_MS);
// Tắt LED
digitalWrite(LED_PIN, LOW);
Serial.println("LED is OFF");
}
}
}
void setup() {
// Khởi tạo giao tiếp Serial
Serial.begin(115200);
// Thiết lập chân LED và button
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Tạo binary semaphore
xBinarySemaphore = xSemaphoreCreateBinary();
if (xBinarySemaphore != NULL) {
// Tạo task để điều khiển LED
xTaskCreate(Task_LED_Control, "LED Control Task", 128, NULL, 1, NULL);
// Gán ngắt cho button
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), handleButtonInterrupt, FALLING);
} else {
Serial.println("Failed to create semaphore");
}
}
void loop() {
// Không có gì để làm ở đây vì FreeRTOS sẽ quản lý các task
}