/*
Traffic light with crosswalk demo
AnonEngineering December 2025
*/
const unsigned long STATE_DELAYS[] = {
1000, 4000, 2000, 1000, 4000, 2000
};
const int NUM_BTNS = 2;
const int BTN_PINS[] = {19, 16};
const int LED_PINS[] = {23, 22, 21, 18, 5, 17};
const bool LED_STATES[][6] = {
{0, 0, 1, 0, 0, 1}, // all stop
{1, 0, 0, 0, 0, 1}, // NS go
{0, 1, 0, 0, 0, 1}, // NS caution
{0, 0, 1, 0, 0, 1}, // all stop
{0, 0, 1, 1, 0, 0}, // EW go
{0, 0, 1, 0, 1, 0}, // EW caution
};
unsigned long prevTime = 0;
int state = 0;
int btnState[NUM_BTNS];
int oldBtnState[NUM_BTNS];
// function returns which button was pressed, or 0 if none
int checkButtons() {
int btnPressed = 0;
for (int i = 0; i < NUM_BTNS; i++) {
btnState[i] = digitalRead(BTN_PINS[i]); // check each button
if (btnState[i] != oldBtnState[i]) { // if it changed
oldBtnState[i] = btnState[i]; // remember state for next time
if (btnState[i] == 0) { // was just pressed
btnPressed = i + 1;
}
delay(20); // debounce
}
}
return btnPressed;
}
void setup() {
Serial.begin(115200);
for (int i = 0; i < 6; i++) {
pinMode(LED_PINS[i], OUTPUT);
}
pinMode(BTN_PINS[0], INPUT_PULLUP);
pinMode(BTN_PINS[1], INPUT_PULLUP);
Serial.println("\nTraffic Light Demo");
}
void loop() {
// check the buttons
int btnNumber = checkButtons();
if (btnNumber) {
if (btnNumber == 1 && state == 4) {
Serial.println("North/South crosswalk button pressed");
prevTime = millis();
state = 5;
}
if (btnNumber == 2 && state == 1) {
Serial.println("East/West crosswalk button pressed");
prevTime = millis();
state = 2;
}
}
// set all the LEDs
for (int led = 0; led < 6; led++) {
digitalWrite(LED_PINS[led], LED_STATES[state][led]);
}
// change the state after the correct delay
if (millis() - prevTime >= STATE_DELAYS[state]) {
prevTime = millis();
state++;
if (state == 6) state = 0;
}
delay(10); // this speeds up the Wokwi simulation
}North/South
East/West