Loading
Build a pedestrian crossing and learn the non-blocking timing pattern that every bigger project needs.
Guide
With delay(6000) the Arduino cannot notice a button press for six seconds. Instead we remember when the light last changed, check the clock on every loop, and react the moment enough time has passed.
7 parts · about ₹1,633
What you need
Step 1 of 3
INPUT_PULLUP means no resistor is needed.Milestone
Wired
Step 2 of 3
| 1 | const int RED = 8, AMBER = 9, GREEN = 10, BUTTON = 2; |
| 2 | |
| 3 | enum State { GO, SLOW, STOP }; |
| 4 | const unsigned long DURATION[] = { 6000, 2000, 6000 }; // how long GO, SLOW, STOP last (ms) |
| 5 | |
| 6 | State state = STOP; |
| 7 | unsigned long since = 0; // when the current state started |
| 8 | bool walkRequested = false; |
| 9 | |
| 10 | void show(State s) { |
| 11 | digitalWrite(GREEN, s == GO); |
| 12 | digitalWrite(AMBER, s == SLOW); |
| 13 | digitalWrite(RED, s == STOP); |
| 14 | } |
| 15 | |
| 16 | void setup() { |
| 17 | pinMode(RED, OUTPUT); pinMode(AMBER, OUTPUT); pinMode(GREEN, OUTPUT); |
| 18 | pinMode(BUTTON, INPUT_PULLUP); |
Milestone
Lights cycle on their own
Milestone
The button shortens green
Pressing during green switches to amber within two seconds.
Step 3 of 3
since = millis();millis() - since >= wait. This keeps working when millis() rolls over after 49 days.loop() short and never block it. Every other part of your project gets a turn.Labs
All labs