Take this as an example.
I start with lights off, so the first press of any button starts the lamps.
I would suggest to remove the switch to green-button, because it will be misused.
Nice trick to kill elderly people crossing slowly...
// https://github.com/thomasfredericks/Bounce2
#include <Bounce2.h>
const byte pinCarRed = 2;
const byte pinCarYellow = 3;
const byte pinCarGreen = 4;
const byte pinPedRed = 5;
const byte pinPedGreen = 6;
const byte pinButCross = 7;
const byte pinButClear = 8;
const unsigned int yellowTime = 2000;
const unsigned int redTime = 6000;
enum states {
tlOff,
tlNormal,
tlYellow,
tlRed,
};
byte currentState = tlOff;
unsigned long stateEntered;
unsigned long topLoop;
Bounce butCross;
Bounce butClear;
void setup() {
pinMode(pinCarRed, OUTPUT);
pinMode(pinCarYellow, OUTPUT);
pinMode(pinCarGreen, OUTPUT);
pinMode(pinPedRed, OUTPUT);
pinMode(pinPedGreen, OUTPUT);
butCross.attach(pinButCross, INPUT_PULLUP);
butClear.attach(pinButClear, INPUT_PULLUP);
Serial.begin(115200);
Serial.println(F("Pedestrian Crossing"));
switchLamps();
}
void loop() {
topLoop = millis();
butCross.update();
butClear.update();
switch (currentState) {
case tlOff:
if (butCross.fell() || butClear.fell()) {
switchState(tlNormal);
}
break;
case tlNormal:
if (butCross.fell() || butClear.fell()) {
switchState(tlYellow);
}
break;
case tlYellow:
if (topLoop - stateEntered > yellowTime) {
switchState(tlRed);
}
break;
case tlRed:
if ((topLoop - stateEntered > redTime) || butClear.fell()) {
switchState(tlNormal);
}
break;
}
}
void switchState(byte newState) {
Serial.print(F("state "));
Serial.print(newState);
Serial.print(F(" from "));
Serial.print(currentState);
Serial.print(F(" @ "));
Serial.println(topLoop);
currentState = newState;
stateEntered = topLoop;
switchLamps();
}
void switchLamps() {
switch (currentState) {
case tlOff:
digitalWrite(pinCarRed, LOW);
digitalWrite(pinCarYellow, LOW);
digitalWrite(pinCarGreen, LOW);
digitalWrite(pinPedRed, LOW);
digitalWrite(pinPedGreen, LOW);
break;
case tlNormal:
digitalWrite(pinCarRed, LOW);
digitalWrite(pinCarYellow, LOW);
digitalWrite(pinCarGreen, HIGH);
digitalWrite(pinPedRed, HIGH);
digitalWrite(pinPedGreen, LOW);
break;
case tlYellow:
digitalWrite(pinCarRed, LOW);
digitalWrite(pinCarYellow, HIGH);
digitalWrite(pinCarGreen, LOW);
digitalWrite(pinPedRed, HIGH);
digitalWrite(pinPedGreen, LOW);
break;
case tlRed:
digitalWrite(pinCarRed, HIGH);
digitalWrite(pinCarYellow, LOW);
digitalWrite(pinCarGreen, LOW);
digitalWrite(pinPedRed, LOW);
digitalWrite(pinPedGreen, HIGH);
break;
}
}