// Time - Scheduling & Algorithm Optimization Demo
// Pin Definitions
const int RED_LED_PIN = 7;
const int GREEN_LED_PIN = 6;
const int YELLOW_LED_PIN = 5;
const int PUSH_BUTTON_PIN = 8;
// LED states and last blink times
unsigned long redLedLastBlinkTime = 0;
unsigned long greenLedLastBlinkTime = 0;
unsigned long yellowLedLastBlinkTime = 0;
// LED intervals
const long RED_LED_INTERVAL = 500; // milliseconds
const long GREEN_LED_INTERVAL = 200; // milliseconds
const long YELLOW_LED_INTERVAL = 1000; // milliseconds
void setup() {
pinMode(RED_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(YELLOW_LED_PIN, OUTPUT);
pinMode(PUSH_BUTTON_PIN, INPUT_PULLUP); // Use internal pull-up
Serial.begin(115200);
Serial.println("Time - Scheduling & Algorithm Optimization Demo");
}
void loop() {
unsigned long currentTime = millis();
// Non-blocking LED blinking (scheduling)
if (currentTime - redLedLastBlinkTime >= RED_LED_INTERVAL) {
redLedLastBlinkTime = currentTime;
digitalWrite(RED_LED_PIN, !digitalRead(RED_LED_PIN)); // Toggle LED state
Serial.print("Red LED toggled at: ");
Serial.println(currentTime);
}
if (currentTime - greenLedLastBlinkTime >= GREEN_LED_INTERVAL) {
greenLedLastBlinkTime = currentTime;
digitalWrite(GREEN_LED_PIN, !digitalRead(GREEN_LED_PIN)); // Toggle LED state
Serial.print("Green LED toggled at: ");
Serial.println(currentTime);
}
if (currentTime - yellowLedLastBlinkTime >= YELLOW_LED_INTERVAL) {
yellowLedLastBlinkTime = currentTime;
digitalWrite(YELLOW_LED_PIN, !digitalRead(YELLOW_LED_PIN)); // Toggle LED state
Serial.print("Yellow LED toggled at: ");
Serial.println(currentTime);
}
// Algorithm Optimization Example: Simple delay instead of busy-waiting
// This is a conceptual example. In a real scenario, you'd avoid busy-waiting altogether
// for complex tasks and rely on interrupts or FreeRTOS timers.
// The 'delay()' function itself is a form of optimized busy-wait provided by Arduino.
// The "optimization" here is showing how different tasks can co-exist without
// one blocking the other excessively, rather than optimizing the delay function itself.
// Simulate some other non-blocking work that might occur
// For instance, reading a sensor or performing a calculation
// Without this "optimization" section, if we used 'delay()' for each LED,
// the LEDs would not blink independently.
// Example of a potentially "optimized" loop structure for a simple task:
// Instead of a loop like:
// for (long i = 0; i < 1000000; i++) { // Busy wait example }
// We use the millis() based timing, which allows other code to run.
// The 'loop()' itself is the scheduling mechanism.
}