//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 {
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() {
// put your setup code here, to run once:
//Set LED pins as output
pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
//Set stop button pin as input with pull-up resistor
pinMode(stopButton, INPUT_PULLUP);
}
void loop() {
// put your main code here, to run repeatedly:
unsigned long current Millis = 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
}
}
}