// Define the number of tasks
#define NUM_TASKS 3
// Define task state
typedef void (*Task)();
Task tasks[NUM_TASKS]; // Array to hold tasks
int currentTask = 0; // Index of the currently running task
// Task 1: Blink LED on pin 13
void task1() {
static unsigned long lastRun = 0;
unsigned long now = millis();
if (now - lastRun >= 500) { // Task runs every 500ms
lastRun = now;
digitalWrite(13, !digitalRead(13)); // Toggle LED
Serial.println("Task 1: Toggling LED");
}
}
// Task 2: Print a message every 1 second
void task2() {
static unsigned long lastRun = 0;
unsigned long now = millis();
if (now - lastRun >= 1000) { // Task runs every 1000ms
lastRun = now;
Serial.println("Task 2: Printing message");
}
}
// Task 3: Check a button press (on pin 2)
void task3() {
static unsigned long lastRun = 0;
unsigned long now = millis();
if (now - lastRun >= 200) { // Task runs every 200ms
lastRun = now;
if (digitalRead(2) == HIGH) { // Assuming active LOW button
Serial.println("Task 3: Button Pressed");
}
}
}
// Function to switch tasks (round-robin)
void switchTask() {
currentTask++;
if (currentTask >= NUM_TASKS) {
currentTask = 0;
}
}
// Scheduler loop that calls the current task
void scheduler() {
tasks[currentTask]();
switchTask();
}
void setup() {
Serial.begin(9600);
// Initialize hardware
pinMode(13, OUTPUT); // LED pin
pinMode(2, INPUT); // Button pin
// Register tasks
tasks[0] = task1;
tasks[1] = task2;
tasks[2] = task3;
}
void loop() {
scheduler(); // Run the scheduler in the main loop
}