Code
Code
Code
int buttonState = 0;
int lastButtonState = 0;
void setup() {
pinMode(carRed, OUTPUT);
pinMode(carYellow, OUTPUT);
pinMode(carGreen, OUTPUT);
pinMode(pedRed, OUTPUT);
pinMode(pedGreen, OUTPUT);
void loop() {
buttonState = digitalRead(buttonPin);
// Pedestrian has pressed the button, so switch car traffic light to red
carState = 0;
lastButtonState = buttonState;
switch (carState) {
case 0: // red
digitalWrite(carRed, HIGH);
digitalWrite(carYellow, LOW);
digitalWrite(carGreen, LOW);
// Switch to yellow
carState = 1;
lastCarTime = millis(); // reset car timer
break;
case 1: // yellow
digitalWrite(carRed, LOW);
digitalWrite(carYellow, HIGH);
digitalWrite(carGreen, LOW);
// Switch to green
carState = 2;
break;
case 2: // green
digitalWrite(carRed, LOW);
digitalWrite(carYellow, LOW);
digitalWrite(carGreen, HIGH);
// Switch to yellow
carState = 3;
break;
case 3: // yellow
digitalWrite(carRed, LOW);
digitalWrite(carYellow, HIGH);
digitalWrite(carGreen, LOW);
// Switch to red
carState = 0;
break;
if (carState == 0 || carState == 3) {
digitalWrite(pedRed, LOW);
digitalWrite(pedGreen, HIGH);
// Switch to red
pedState = 0;
} else {
digitalWrite(pedRed, HIGH);
digitalWrite(pedGreen, LOW);
}
}