// Pin definitions
const int red1Pin = 2;
const int yellow1Pin = 3;
const int green1Pin = 4;
const int red2Pin = 5;
const int yellow2Pin = 6;
const int green2Pin = 7;
const int switchPin = 8;
// Traffic light timing settings
const unsigned long greenTime = 10000; // 10 seconds
const unsigned long yellowTime = 3000; // 3 seconds
// Variables
bool useSwitch = false;
bool switchState = false;
unsigned long currentTime = 0;
unsigned long previousTime = 0;
int currentState = 0; // 0: Green1, 1: Yellow1, 2: Red1, 3: Green2, 4: Yellow2, 5: Red2
void setup() {
// Initialize pin modes
pinMode(red1Pin, OUTPUT);
pinMode(yellow1Pin, OUTPUT);
pinMode(green1Pin, OUTPUT);
pinMode(red2Pin, OUTPUT);
pinMode(yellow2Pin, OUTPUT);
pinMode(green2Pin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
// Check if the switch is connected
if (digitalRead(switchPin) == LOW) {
useSwitch = true;
currentState = 3; // Start with Green2
}
}
void loop() {
// Update switch state
if (useSwitch) {
switchState = digitalRead(switchPin);
}
// Traffic light state machine
switch (currentState) {
case 0: // Green1
digitalWrite(green1Pin, HIGH);
digitalWrite(red2Pin, HIGH);
currentState = 1;
previousTime = millis();
break;
case 1: // Yellow1
currentTime = millis();
if (currentTime - previousTime >= yellowTime) {
digitalWrite(yellow1Pin, LOW);
digitalWrite(red1Pin, HIGH);
currentState = 2;
previousTime = currentTime;
} else {
digitalWrite(yellow1Pin, HIGH);
}
break;
case 2: // Red1
currentTime = millis();
if (currentTime - previousTime >= greenTime) {
digitalWrite(green2Pin, HIGH);
digitalWrite(red1Pin, LOW);
currentState = 3;
previousTime = currentTime;
}
break;
case 3: // Green2
digitalWrite(green2Pin, HIGH);
digitalWrite(red1Pin, HIGH);
currentState = 4;
previousTime = millis();
break;
case 4: // Yellow2
currentTime = millis();
if (currentTime - previousTime >= yellowTime) {
digitalWrite(yellow2Pin, LOW);
digitalWrite(red2Pin, HIGH);
currentState = 5;
previousTime = currentTime;
} else {
digitalWrite(yellow2Pin, HIGH);
}
break;
case 5: // Red2
currentTime = millis();
if (currentTime - previousTime >= greenTime) {
digitalWrite(green1Pin, HIGH);
digitalWrite(red2Pin, LOW);
currentState = 0;
previousTime = currentTime;
}
break;
}
// Check switch state to switch traffic lights
if (useSwitch && switchState) {
digitalWrite(green1Pin, HIGH);
digitalWrite(green2Pin, LOW);
digitalWrite(red1Pin, LOW);
digitalWrite(red2Pin, HIGH);
currentState = 0;
}
}