#include <Arduino.h>
// Define pins
#define LED1_PIN 21
#define LED2_PIN 23
#define BUTTON_PIN 19
// Define task handles
TaskHandle_t Task1Handle = NULL;
TaskHandle_t Task2Handle = NULL;
// Variable to control blinking
int countButton = 0;
unsigned int delayLED1 = 1000;
unsigned int delayLED2 = 500;
void IRAM_ATTR buttonISR() {
static unsigned long lastInterruptTime = 0;
unsigned long interruptTime = millis();
if (interruptTime - lastInterruptTime > 200) { // Debounce time
// Toggle the blinking state
countButton++;
if(countButton >= 3)countButton = 0;
Serial.print("Count Buttton: ");
Serial.println(countButton );
//1. Blink LED1, with an interval of 1s ON and 1s OFF
//2. Blink LED2, with an interval of 0.5s ON and 0.5s OFF
//3. When the button is pressed, turn off the LED2.
//4. When the button is pressed again, blink LED2 again with the same interval
if (countButton == 0) {
vTaskSuspend(Task1Handle);
vTaskSuspend(Task2Handle);
delayLED1 = 1000;
delayLED2 = 500;
vTaskResume(Task1Handle);
vTaskResume(Task2Handle);
Serial.println("Blink LED1, with an interval of 1s ON and 1s OFF");
Serial.println("Blink LED2, with an interval of 0.5s ON and 0.5s OFF");
}
else if(countButton == 1)
{
vTaskSuspend(Task2Handle);
digitalWrite(LED2_PIN, LOW);
Serial.println("When the button is pressed, turn off the LED2");
}
else if(countButton == 2)
{
delayLED2 = delayLED1;
vTaskResume(Task2Handle);
Serial.println("When the button is pressed again, blink LED2 again with the same interval");
}
}
lastInterruptTime = interruptTime;
}
// Task for blinking LED1 with 500ms delay
void Task1(void *pvParameters) {
while (1) {
digitalWrite(LED1_PIN, HIGH);
vTaskDelay(delayLED1 / portTICK_PERIOD_MS); // 500ms delay
digitalWrite(LED1_PIN, LOW);
vTaskDelay(delayLED1 / portTICK_PERIOD_MS); // 500ms delay
}
}
// Task for blinking LED2 with 1000ms delay
void Task2(void *pvParameters) {
while (1) {
digitalWrite(LED2_PIN, HIGH);
vTaskDelay(delayLED2 / portTICK_PERIOD_MS); // 1000ms delay
digitalWrite(LED2_PIN, LOW);
vTaskDelay(delayLED2 / portTICK_PERIOD_MS); // 1000ms delay
}
}
void setup() {
Serial.begin(9600);
Serial.println("Starting the program...");
// Initialize LED pins
pinMode(LED1_PIN, OUTPUT);
pinMode(LED2_PIN, OUTPUT);
// Initialize Button pin
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Attach interrupt to the button pin
attachInterrupt(BUTTON_PIN, buttonISR, FALLING);
// Create tasks
xTaskCreate(Task1, "LED1 Task", 1000, NULL, 1, &Task1Handle);
xTaskCreate(Task2, "LED2 Task", 1000, NULL, 1, &Task2Handle);
Serial.println("Blink LED1, with an interval of 1s ON and 1s OFF");
Serial.println("Blink LED2, with an interval of 0.5s ON and 0.5s OFF");
}
void loop() {
// Nothing to do in loop, RTOS handles tasks
delay(10);
}