#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/semphr.h>
// Định nghĩa chân LED
#define LED1_PIN 18
#define LED2_PIN 19
#define LED3_PIN 21
// Khai báo Semaphore
SemaphoreHandle_t xSemaphore;
// Tác vụ LED cao nhất
void TaskHighPriority(void *pvParameters) {
while (1) {
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
digitalWrite(LED1_PIN, HIGH);
vTaskDelay(100 / portTICK_PERIOD_MS);
digitalWrite(LED1_PIN, LOW);
vTaskDelay(100 / portTICK_PERIOD_MS);
xSemaphoreGive(xSemaphore);
}
vTaskDelay(1); // Giảm tải CPU
}
}
// Tác vụ LED trung bình
void TaskMediumPriority(void *pvParameters) {
while (1) {
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
digitalWrite(LED2_PIN, HIGH);
vTaskDelay(500 / portTICK_PERIOD_MS);
digitalWrite(LED2_PIN, LOW);
vTaskDelay(500 / portTICK_PERIOD_MS);
xSemaphoreGive(xSemaphore);
}
vTaskDelay(1); // Giảm tải CPU
}
}
// Tác vụ LED thấp nhất
void TaskLowPriority(void *pvParameters) {
while (1) {
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
digitalWrite(LED3_PIN, HIGH);
vTaskDelay(1000 / portTICK_PERIOD_MS);
digitalWrite(LED3_PIN, LOW);
vTaskDelay(1000 / portTICK_PERIOD_MS);
xSemaphoreGive(xSemaphore);
}
vTaskDelay(1); // Giảm tải CPU
}
}
void setup() {
Serial.begin(115200);
// Cài đặt chân LED
pinMode(LED1_PIN, OUTPUT);
pinMode(LED2_PIN, OUTPUT);
pinMode(LED3_PIN, OUTPUT);
// Tạo Semaphore
xSemaphore = xSemaphoreCreateMutex();
if (xSemaphore == NULL) {
Serial.println("Không thể tạo Semaphore");
while (1);
}
// Tạo các tác vụ với ưu tiên khác nhau
xTaskCreate(TaskHighPriority, "TaskHigh", 2048, NULL, 3, NULL); // Ưu tiên cao nhất
xTaskCreate(TaskMediumPriority, "TaskMedium", 2048, NULL, 2, NULL); // Ưu tiên trung bình
xTaskCreate(TaskLowPriority, "TaskLow", 2048, NULL, 1, NULL); // Ưu tiên thấp nhất
}
void loop() {
// Vòng lặp rỗng
}