// Global variable to store button status
volatile int BtnStatus = 0;
SemaphoreHandle_t mutex;
void setup() {
Serial.begin(115200);
// Create a mutex for accessing BtnStatus
mutex = xSemaphoreCreateMutex();
// Set up the button and LED pins
pinMode(18, INPUT_PULLDOWN);
pinMode(12, OUTPUT);
// Create tasks
xTaskCreatePinnedToCore(TaskA, "TaskA", 1024, NULL, 2, NULL, 1); // High priority
xTaskCreatePinnedToCore(TaskB, "TaskB", 1024, NULL, 1, NULL, 1); // Low priority
Serial.println("Tasks created for TaskA and TaskB.");
}
void loop() {
// Empty loop since tasks are running in FreeRTOS
}
// Task A: Read button status and store in BtnStatus
void TaskA(void *pvParameters) {
while (1) {
if (xSemaphoreTake(mutex, (TickType_t) 10) == pdTRUE) { // Timeout every 10 ticks
BtnStatus = digitalRead(18);
xSemaphoreGive(mutex);
}
vTaskDelay(pdMS_TO_TICKS(50)); // 50 ms period
}
}
// Task B: Control LED based on BtnStatus
void TaskB(void *pvParameters) {
while (1) {
if (xSemaphoreTake(mutex, portMAX_DELAY) == pdTRUE) { // No timeout block
if (BtnStatus == HIGH || BtnStatus > 1) {
digitalWrite(12, HIGH);
} else {
digitalWrite(12, LOW);
}
xSemaphoreGive(mutex);
}
vTaskDelay(pdMS_TO_TICKS(120)); // 120 ms period
}
}