#include <TaskScheduler.h>
// Include the TaskScheduler library for Scheduling Tasks
// TaskScheduler instance
Scheduler ts;
// Create an instance of the scheduler to manage tasks
// Variables
int threshold = 512;
// Define a threshold value for comparing the analog input
// Task functions
void blinkLED() {
int value = analogRead(A0);
if (value > threshold) {
// If the analog value exceeds the threshold
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
// Toggle the state of the built-in LED (ON to OFF or vice versa)
}
}
void readAnalog() {
int value = analogRead(A0);
// Read the analog value from pin A0
Serial.print("Analog value: ");
// Print a label for the analog value
Serial.println(value);
// Output the analog value to the serial monitor
}
void pwmLED() {
static int brightness = 0;
// Keep track of the current brightness level
static int increment = 10;
// Define the step size for increasing or decreasing brightness
brightness += increment;
// Update the brightness by adding the increment
if (brightness >= 255 || brightness <= 0) increment = -increment;
// Reverse the direction of brightness adjustment if it reaches maximum (255) or minimum (0)
analogWrite(9, brightness);
// Apply the brightness value to pin 9 using PWM
}
// Define tasks
Task tBlink(500, TASK_FOREVER, &blinkLED, &ts);
// Task to blink the LED every 500 milliseconds (only if the analog value exceeds the threshold)
// Parameters:
// 500: Task interval in milliseconds
// TASK_FOREVER: Run this task forever
// &blinkLED: Function to execute
// &ts: Associated schedular instance
Task tReadAnalog(1000, TASK_FOREVER, &readAnalog, &ts);
// Task to read the analog value every 1000 milliseconds
// Parameters:
// 1000: Task interval in milliseconds
// TASK_FOREVER: Run this task forever
// &readAnalog: Function to execute
// &ts: Associated schedular instance
Task tPWM(100, 10, &pwmLED, &ts);
// Task to adjust LED brightness using PWM every 100 milliseconds
// Will run 10 times per cycle before stopping
// Parameters:
// - 100: Task interval in milliseconds
// - 10: Number of times to run this task before stopping
// - &pwmLED: Function to execute
// - &ts: Associated schedular instance
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
// Set the built-in LED pin as an output
pinMode(9, OUTPUT);
// Set pin 9 as an output for PWM control
Serial.begin(9600);
// Initialize serial communication at 9600 baud rate
// Enable tasks
tBlink.enable();
// Enable the blinking task
tReadAnalog.enable();
// Enable the analog reading task
tPWM.enable();
// Enable the PWM brightness adjustment task
}
void loop() {
ts.execute();
// Execute the tasks managed by the scheduler
}