//Define pins for LEDs
const int redLED = 8;
const int yellowLED = 9;
const int greenLED = 10;
// Define pin for the stop button
const int stopButton = 2; // Connect the button to any digital pin
//Define delays (in milliseconds)
const int redDelay = 5000; //Red light duration (5 seconds)
const int yellowDelay = 2000; //Yellow light duration (2 seconds)
const int greenDelay = 5000; //Green light duration ( 5 seconds)
const int stopDelay = 10000; //Stop button press duration (10 seconds)
// Define states for the traffic light
enum TrafficLightState {
RED,
YELLOW,
GREEN,
STOPPED
};
TrafficLightState currentState = RED; // Initial state
unsigned long previousMillis = 0; // Variable to store the time since the last state change
unsigned long stopMillis = 0; // Variable to store the time since the stop button press
void setup() {
// Set LED pins as output
pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
// Set button pin as input with pull-up resistor
pinMode(stopButton, INPUT_PULLUP);
}
void loop() {
unsigned long currentMillis = millis(); // Get the current time
// Check if the stop button is pressed
if (digitalRead(stopButton)== LOW) {
stopMillis = currentMillis; // Record the time when the button was pressed
currentState = STOPPED; // Set the state to stopped
}
// Handle traffic light states
switch (currentState) {
case RED:
if (currentMillis - previousMillis >+ redDelay) {
currentState = GREEN; // Transition to green
previousMillis = currentMillis; // Update the previous state change time
}
break;
case YELLOW:
if (currentMillis - previousMillis >= yellowDelay) {
currentState = RED; // Transition to red
previousMillis = currentMillis; // update the previous state change time
}
break;
case STOPPED:
if (currentMillis - stopMillis >= stopDelay) {
currentState = RED; // Resume traffic light cycle after stopDelay
previousMillis = currentMillis; // Update the previous state change time
}
break;
}
// Update the LEDs based on the current state
switch (currentState) {
case RED:
digitalWrite(redLED, HIGH);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, LOW);
break;
case YELLOW:
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, HIGH);
digitalWrite(greenLED, LOW);
break;
case GREEN:
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, HIGH);
break;
case STOPPED:
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, LOW);
break;
}
}