const int redLedPin = 13; // Red LED pin
const int yellowLedPin = 11; // Yellow LED pin
const int greenLedPin = 9; // Green LED pin
const int ldrPin = A0; // LDR connected to A0
bool redLedState = false; // State of red LED
bool yellowLedState = false; // State of yellow LED
bool greenLedState = false; // State of green LED
unsigned long previousRedMillis = 0;
unsigned long previousYellowMillis = 0;
unsigned long previousGreenMillis = 0;
const int redOnTime = 200; // Red LED ON time (ms)
const int redOffTime = 800; // Red LED OFF time (ms)
unsigned long redInterval = redOnTime; // Initial interval for red LED
int yellowBlinkInterval = 500; // Initial blink speed for yellow LED
bool greenLedActivated = false; // Prevents continuous triggering of green LED
void setup() {
pinMode(redLedPin, OUTPUT);
pinMode(yellowLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
Serial.begin(9600); // Debugging
}
void loop() {
unsigned long currentMillis = millis();
// Red LED Blinking (200ms ON, 800ms OFF)
if (currentMillis - previousRedMillis >= redInterval) {
previousRedMillis = currentMillis; // Reset timer
redLedState = !redLedState; // Toggle LED state
digitalWrite(redLedPin, redLedState); // Apply state
// Set next interval (switch between ON and OFF time)
redInterval = redLedState ? redOnTime : redOffTime;
}
// Read LDR value
int ldrValue = analogRead(ldrPin); // Read LDR (0-1023)
// Smoothly adjust yellow LED blink interval using LDR value
yellowBlinkInterval += (ldrValue - yellowBlinkInterval) * 0.1; // Smooth transition
// Ensure blinking remains visible (limit range)
//if (yellowBlinkInterval < 200) yellowBlinkInterval = 200; // Fastest blink
//if (yellowBlinkInterval > 1000) yellowBlinkInterval = 1000; // Slowest blink
// Yellow LED Blinking based on LDR value
if (currentMillis - previousYellowMillis >= yellowBlinkInterval) {
previousYellowMillis = currentMillis; // Reset timer
yellowLedState = !yellowLedState; // Toggle LED state
digitalWrite(yellowLedPin, yellowLedState); // Apply state
}
// Check if Red and Yellow LEDs blink exactly at 200ms ON / 800ms OFF
if (!greenLedActivated && yellowBlinkInterval == (redOnTime + redOffTime)) {
greenLedState = true;
greenLedActivated = true; // Prevent retriggering
previousGreenMillis = currentMillis;
digitalWrite(greenLedPin, HIGH); // Turn on Green LED for 3 seconds
}
// Turn off Green LED after 3 seconds
if (greenLedState && currentMillis - previousGreenMillis >= 3000) {
greenLedState = false;
digitalWrite(greenLedPin, LOW);
}
// Reset green LED activation when yellow and red are no longer in sync
if (yellowBlinkInterval != (redOnTime + redOffTime)) {
greenLedActivated = false;
}
// Debug output
Serial.print("LDR Value: ");
Serial.print(ldrValue);
Serial.print(" - Yellow Blink Interval: ");
Serial.print(yellowBlinkInterval);
Serial.print(" - Green LED State: ");
Serial.println(greenLedState);
}