#include <Arduino.h>
#include <Arduino_FreeRTOS.h>
// Task handles
TaskHandle_t Task1Handle = NULL;
TaskHandle_t Task2Handle = NULL;
volatile bool buttonPressed = false;
volatile bool buttonStateChanged = false;
// Function prototypes
void Task1(void *pvParameters);
void Task2(void *pvParameters);
void buttonISR();
void setup() {
Serial.begin(9600);
// Set up the button pin
pinMode(2, INPUT_PULLUP);
// Set up external interrupt on pin 2
attachInterrupt(digitalPinToInterrupt(2), buttonISR, CHANGE);
// Create the tasks
xTaskCreate(Task1, "Task1", 128, NULL, 1, &Task1Handle);
xTaskCreate(Task2, "Task2", 128, NULL, 1, &Task2Handle);
// Start the scheduler
vTaskStartScheduler();
}
void loop() {
// Nothing to do here, tasks and interrupts handle the functionality
}
void Task1(void *pvParameters) {
(void) pvParameters;
for (;;) {
// Wait for 1 second
vTaskDelay(pdMS_TO_TICKS(1000));
// Print "Hello World"
Serial.println("Hello World");
}
}
void Task2(void *pvParameters) {
(void) pvParameters;
for (;;) {
if (buttonStateChanged) {
buttonStateChanged = false;
if (buttonPressed) {
// Increase the priority of Task2 and decrease the priority of Task1
vTaskPrioritySet(Task2Handle, 2);
vTaskPrioritySet(Task1Handle, 1);
} else {
// Restore the original priorities
vTaskPrioritySet(Task2Handle, 1);
vTaskPrioritySet(Task1Handle, 1);
}
}
if (buttonPressed) {
// Print "Hello Interrupt From Button"
Serial.println("Hello Interrupt From Button");
// Add a small delay to control the print rate while the button is held down
vTaskDelay(pdMS_TO_TICKS(100));
} else {
// Add a small delay to prevent this task from hogging the CPU
vTaskDelay(pdMS_TO_TICKS(10));
}
}
}
void buttonISR() {
bool currentState = digitalRead(2);
buttonPressed = (currentState == LOW);
buttonStateChanged = true;
}