#include <Arduino.h>
#include <FreeRTOS.h>
// Định nghĩa chân button và LED
const int buttonPin = 1;
const int ledPin = 13;
// Khai báo semaphore
SemaphoreHandle_t xSemaphore;
// Hàm xử lý ngắt
void IRAM_ATTR handleButtonInterrupt() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xSemaphoreGiveFromISR(xSemaphore, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR();
}
// Task điều khiển LED
void LED_Task(void *pvParameters) {
while (1) {
// Chờ để nhận semaphore
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
// Bật LED
digitalWrite(ledPin, HIGH);
Serial.println("LED is ON");
// Chờ 1 giây
vTaskDelay(1000 / portTICK_PERIOD_MS);
// Tắt LED
digitalWrite(ledPin, LOW);
Serial.println("LED is OFF");
}
}
}
void setup() {
// Khởi động Serial
Serial.begin(9600);
// Thiết lập chân LED là OUTPUT
pinMode(ledPin, OUTPUT);
// Thiết lập chân button là INPUT
pinMode(buttonPin, INPUT_PULLUP);
// Tạo semaphore
xSemaphore = xSemaphoreCreateBinary();
// Thiết lập ngắt cho chân button
attachInterrupt(digitalPinToInterrupt(buttonPin), handleButtonInterrupt, FALLING);
// Tạo task điều khiển LED
xTaskCreate(LED_Task, "LED_Task", 128, NULL, 1, NULL);
}
void loop() {
// Không làm gì trong loop, FreeRTOS sẽ quản lý các task
}