// Pin assignments
const int greenLED = 8;
const int yellowLED = 9;
const int redLED = 10;
// Timing constants
const unsigned long greenDuration = 5000; // Duration for Green light (in milliseconds)
const unsigned long yellowDuration = 2000; // Duration for Yellow light (in milliseconds)
const unsigned long redDuration = 5000; // Duration for Red light (in milliseconds)
const unsigned long offDuration = 500; // Duration for turning off LEDs between changes (in milliseconds)
// State definition for LEDs
enum LightState { GREEN, YELLOW, RED };
// Current state of the traffic light
LightState currentLightState = GREEN;
unsigned long previousMillis = 0; // To store time for non-blocking delay
void setup() {
// Set LED pins as outputs
pinMode(greenLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(redLED, OUTPUT);
// Ensure all LEDs are off initially
turnOffAllLEDs();
}
void loop() {
unsigned long currentMillis = millis(); // Get the current time in milliseconds
switch (currentLightState) {
case GREEN:
digitalWrite(greenLED, HIGH); // Turn on Green LED
if (currentMillis - previousMillis >= greenDuration) {
// Turn off Green LED immediately after the duration
digitalWrite(greenLED, LOW);
previousMillis = currentMillis; // Reset the timer
currentLightState = YELLOW; // Move to Yellow light state
delay(offDuration); // Short delay for smooth transition
}
break;
case YELLOW:
digitalWrite(yellowLED, HIGH); // Turn on Yellow LED
if (currentMillis - previousMillis >= yellowDuration) {
// Turn off Yellow LED immediately after the duration
digitalWrite(yellowLED, LOW);
previousMillis = currentMillis; // Reset the timer
currentLightState = RED; // Move to Red light state
delay(offDuration); // Short delay for smooth transition
}
break;
case RED:
digitalWrite(redLED, HIGH); // Turn on Red LED
if (currentMillis - previousMillis >= redDuration) {
// Turn off Red LED immediately after the duration
digitalWrite(redLED, LOW);
previousMillis = currentMillis; // Reset the timer
currentLightState = GREEN; // Move to Green light state
delay(offDuration); // Short delay for smooth transition
}
break;
}
}
// Function to turn off all LEDs (if needed for reset)
void turnOffAllLEDs() {
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, LOW);
}