#include <Arduino_FreeRTOS.h>
#include <semphr.h>

SemaphoreHandle_t xSemaphore = NULL;
const int ledPin = 13; // Chân LED ngoài
const int buttonPin = 2; // Chân nút nhấn

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);

  // Tạo semaphore
  xSemaphore = xSemaphoreCreateBinary();

  // Gắn ngắt vào nút nhấn
  attachInterrupt(digitalPinToInterrupt(buttonPin), handleButtonPress, FALLING);

  // Tạo nhiệm vụ để xử lý LED
  xTaskCreate(taskBlinkLED, "Blink LED", 128, NULL, 1, NULL);
}

void loop() {
  // Không làm gì trong vòng lặp chính
}

void handleButtonPress() {
  BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  xSemaphoreGiveFromISR(xSemaphore, &xHigherPriorityTaskWoken);
  portYIELD_FROM_ISR();
}

void taskBlinkLED(void *pvParameters) {
  (void) pvParameters;

  for (;;) {
    if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
      digitalWrite(ledPin, HIGH);
      vTaskDelay(500 / portTICK_PERIOD_MS);
      digitalWrite(ledPin, LOW);
    }
  }
}