const int redLed = 2; // Red LED pin
const int yellowLed = 3; // Yellow LED pin
const int greenLed = 4; // Green LED pin
const int buttonPin = 5; // Push button pin
int currentState = 0; // 0: Red, 1: Green, 2: Yellow
unsigned long previousMillis = 0;
const long interval = 5000; // 5 seconds for each light
bool overrideActive = false;
unsigned long overrideMillis = 0;
const long overrideInterval = 2000; // 2 seconds for override
void setup() {
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Using internal pull-up resistor
digitalWrite(redLed, HIGH); // Start with red light
}
void loop() {
unsigned long currentMillis = millis();
// Check button press for override
if (digitalRead(buttonPin) == LOW) {
if (!overrideActive) {
overrideActive = true;
overrideMillis = currentMillis;
currentState = (currentState + 1) % 3; // Cycle through 0, 1, 2
updateLights(currentState);
}
}
// If override is active, keep light on for a short period
if (overrideActive && (currentMillis - overrideMillis >= overrideInterval)) {
overrideActive = false;
previousMillis = currentMillis; // Reset the main timer
}
// Normal operation
if (!overrideActive && (currentMillis - previousMillis >= interval)) {
previousMillis = currentMillis;
currentState = (currentState + 1) % 3; // Cycle through 0, 1, 2
updateLights(currentState);
}
}
void updateLights(int state) {
switch (state) {
case 0: // Red
digitalWrite(redLed, HIGH);
digitalWrite(yellowLed, LOW);
digitalWrite(greenLed, LOW);
break;
case 1: // Green
digitalWrite(redLed, LOW);
digitalWrite(yellowLed, LOW);
digitalWrite(greenLed, HIGH);
break;
case 2: // Yellow
digitalWrite(redLed, LOW);
digitalWrite(yellowLed, HIGH);
digitalWrite(greenLed, LOW);
break;
}
}