// Define the pins for the lights
const int NSGreen = 2;
const int NSYellow = 3;
const int NSRed = 4;
const int EWGreen = 5;
const int EWYellow = 6;
const int EWRed = 7;
// State representation (2 bits):
// 00 - NS_GREEN
// 01 - NS_YELLOW
// 10 - EW_GREEN
// 11 - EW_YELLOW
uint8_t currentState = 0b00; // Start with NS_GREEN (00)
unsigned long previousMillis = 0; // Timer variable
const unsigned long greenDuration = 7000; // 7 seconds
const unsigned long yellowDuration = 3000; // 3 seconds
void setup() {
// Set pins as outputs
pinMode(NSGreen, OUTPUT);
pinMode(NSYellow, OUTPUT);
pinMode(NSRed, OUTPUT);
pinMode(EWGreen, OUTPUT);
pinMode(EWYellow, OUTPUT);
pinMode(EWRed, OUTPUT);
// Initialize with North-South Green
digitalWrite(NSGreen, HIGH);
digitalWrite(EWRed, HIGH);
}
void loop() {
unsigned long currentMillis = millis();
switch (currentState) {
case 0b00: // NS_GREEN
if (currentMillis - previousMillis >= greenDuration) {
// Transition to NS_YELLOW
digitalWrite(NSGreen, LOW);
digitalWrite(NSYellow, HIGH);
currentState = 0b01; // NS_YELLOW
previousMillis = currentMillis;
}
break;
case 0b01: // NS_YELLOW
if (currentMillis - previousMillis >= yellowDuration) {
// Transition to EW_GREEN
digitalWrite(NSYellow, LOW);
digitalWrite(NSRed, HIGH);
digitalWrite(EWRed, LOW);
digitalWrite(EWGreen, HIGH);
currentState = 0b10; // EW_GREEN
previousMillis = currentMillis;
}
break;
case 0b10: // EW_GREEN
if (currentMillis - previousMillis >= greenDuration) {
// Transition to EW_YELLOW
digitalWrite(EWGreen, LOW);
digitalWrite(EWYellow, HIGH);
currentState = 0b11; // EW_YELLOW
previousMillis = currentMillis;
}
break;
case 0b11: // EW_YELLOW
if (currentMillis - previousMillis >= yellowDuration) {
// Transition to NS_GREEN
digitalWrite(EWYellow, LOW);
digitalWrite(EWRed, HIGH);
digitalWrite(NSRed, LOW);
digitalWrite(NSGreen, HIGH);
currentState = 0b00; // NS_GREEN
previousMillis = currentMillis;
}
break;
}
}