traffic_light.ino in Arduino
A junction light: enum phases, timed transitions, no delay anywhere.
// A junction traffic light: state machine, no delay in sight.
const int RED_PIN = 4;
const int AMBER_PIN = 5;
const int GREEN_PIN = 6;
enum Phase { GO, CAUTION, STOP_ALL };
Phase phase = STOP_ALL;
unsigned long phaseStart = 0;
// How long each phase holds, in milliseconds.
unsigned long phaseLength(Phase p) {
switch (p) {
case GO: return 6000;
case CAUTION: return 1500;
case STOP_ALL: return 5000;
}
return 1000;
}
Phase nextPhase(Phase p) {
switch (p) {
case GO: return CAUTION;
case CAUTION: return STOP_ALL;
case STOP_ALL: return GO;
}
return STOP_ALL;
}
void showPhase(Phase p) {
digitalWrite(RED_PIN, p == STOP_ALL ? HIGH : LOW);
digitalWrite(AMBER_PIN, p == CAUTION ? HIGH : LOW);
digitalWrite(GREEN_PIN, p == GO ? HIGH : LOW);
}
void setup() {
pinMode(RED_PIN, OUTPUT);
pinMode(AMBER_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
showPhase(phase);
phaseStart = millis();
}
void loop() {
if (millis() - phaseStart >= phaseLength(phase)) {
phase = nextPhase(phase);
showPhase(phase);
phaseStart = millis();
}
}
How it works
phaseLengthandnextPhasemake the cycle a pair of tables.showPhasemaps the state onto the three pins in one place.- The loop is four lines: check the clock, advance, repaint.
Keywords and builtins used here
HIGHLOWOUTPUTPhasecaseconstdigitalWriteenumifintlongloopmillisnextPhasephaseLengthpinModereturnsetupshowPhaseswitchunsignedvoid
The run, in numbers
- Lines
- 50
- Characters to type
- 1036
- Tokens
- 240
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 222 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.