#include <Arduino.h>
// Variabel global
volatile int ledDelay = 500; // waktu delay LED (ms)
volatile bool ledOn = true; // status LED on/off
volatile bool buttonPressed = false; // status tombol
SemaphoreHandle_t serialMutex; // Mutex untuk Serial
TaskHandle_t taskHandleBlink; // Handle untuk TaskBlink (opsional)
void TaskBlink(void *pvParameters) {
pinMode(2, OUTPUT);
while (1) {
if (ledOn) {
digitalWrite(2, HIGH);
vTaskDelay(ledDelay / portTICK_PERIOD_MS);
digitalWrite(2, LOW);
vTaskDelay(ledDelay / portTICK_PERIOD_MS);
} else {
digitalWrite(2, LOW);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
}
void TaskButton(void *pvParameters) {
pinMode(4, INPUT_PULLUP);
while (1) {
if (digitalRead(4) == LOW) {
buttonPressed = true;
ledDelay = 100;
} else {
buttonPressed = false;
ledDelay = 500;
}
vTaskDelay(50 / portTICK_PERIOD_MS);
}
}
void TaskSerial(void *pvParameters) {
while (1) {
if (serialMutex != NULL) {
if (xSemaphoreTake(serialMutex, (TickType_t)10) == pdTRUE) {
Serial.println("Running serial task...");
xSemaphoreGive(serialMutex);
}
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void TaskMonitor(void *pvParameters) {
while (1) {
if (serialMutex != NULL) {
if (xSemaphoreTake(serialMutex, (TickType_t)10) == pdTRUE) {
Serial.print("Status Tombol: ");
Serial.println(buttonPressed ? "DITEKAN" : "TIDAK");
Serial.print("Status LED: ");
if (!ledOn) {
Serial.println("MATI");
} else if (ledDelay == 100) {
Serial.println("KEDIP CEPAT");
} else {
Serial.println("KEDIP LAMBAT");
}
Serial.print("Uptime: ");
Serial.print(millis() / 1000);
Serial.println(" detik");
Serial.println("------------------------");
xSemaphoreGive(serialMutex);
}
}
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}
void TaskCommand(void *pvParameters) {
String command = "";
while (1) {
if (Serial.available()) {
command = Serial.readStringUntil('\n');
command.trim();
if (command.equalsIgnoreCase("FAST")) {
ledOn = true;
ledDelay = 100;
} else if (command.equalsIgnoreCase("SLOW")) {
ledOn = true;
ledDelay = 500;
} else if (command.equalsIgnoreCase("OFF")) {
ledOn = false;
}
if (serialMutex != NULL) {
if (xSemaphoreTake(serialMutex, (TickType_t)10) == pdTRUE) {
Serial.print("Perintah diterima: ");
Serial.println(command);
xSemaphoreGive(serialMutex);
}
}
}
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
void setup() {
Serial.begin(115200);
while (!Serial);
serialMutex = xSemaphoreCreateMutex();
xTaskCreate(TaskBlink, "Blink Task", 1000, NULL, 1, &taskHandleBlink);
xTaskCreate(TaskButton, "Button Task", 1000, NULL, 1, NULL);
xTaskCreate(TaskSerial, "Serial Task", 1000, NULL, 1, NULL);
xTaskCreate(TaskMonitor, "Monitor Task", 2000, NULL, 1, NULL);
xTaskCreate(TaskCommand, "Command Task", 2000, NULL, 1, NULL);
}
void loop() {
// Tidak ada apa-apa di loop
}