Arduino Uno: traffic light with pedestrian button
Red, yellow, green; the button shortens green.
- Arduino Uno
Open in the simulatorNo account needed: press Simulate and it runs.
How it works
Three LEDs on D10 (red), D9 (yellow) and D8 (green) run the traffic light phases. Press SW1 (on D2, with the internal pull-up): green ends early and the light turns red for the pedestrians. The sketch uses millis() instead of delay(), so it always reads the button. The Uno is powered over USB; the serial console shows each phase with its time.
Wiring
Each line is one connection (net) and the pins it joins.
| Net | Pins |
|---|---|
| GND | A1 GNDD1 KD2 KD3 KSW1 2 |
| BTN | A1 D2SW1 1 |
| GRN | A1 D8R3 1 |
| GRN_A | D3 AR3 2 |
| RED | A1 ~D10/SSR1 1 |
| RED_A | D1 AR1 2 |
| YEL | A1 ~D9R2 1 |
| YEL_A | D2 AR2 2 |
Parts
Firmware
sketch.ino · 35 lines
// Traffic light: red D10, yellow D9, green D8. The button on D2 (to GND) asks for red:
// green ends early. No delay() in the loop, so the button is always read (millis state machine).
const int RED = 10, YELLOW = 9, GREEN = 8, BUTTON = 2;
enum Phase { RED_ON, RED_YELLOW, GREEN_ON, YELLOW_ON };
const unsigned long DURATION[] = { 4000, 1000, 5000, 1500 }; // ms per phase
Phase phase = RED_ON;
unsigned long since = 0;
bool request = false;
void show() {
digitalWrite(RED, phase == RED_ON || phase == RED_YELLOW);
digitalWrite(YELLOW, phase == RED_YELLOW || phase == YELLOW_ON);
digitalWrite(GREEN, phase == GREEN_ON);
const char *names[] = { "red", "red+yellow", "green", "yellow" };
Serial.print(millis()); Serial.print(F(" ms: ")); Serial.println(names[phase]);
}
void setup() {
Serial.begin(115200);
pinMode(RED, OUTPUT); pinMode(YELLOW, OUTPUT); pinMode(GREEN, OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
show();
}
void loop() {
if (digitalRead(BUTTON) == LOW && !request) { request = true; Serial.println(F("button: pedestrian waiting")); }
unsigned long d = DURATION[phase];
if (phase == GREEN_ON && request) d = 1000; // shorten green
if (millis() - since >= d) {
phase = (Phase)((phase + 1) % 4);
since = millis();
if (phase == RED_ON) request = false;
show();
}
}Open in the simulator