const int carRed_pin = 13;
const int carYlw_pin = 12;
const int carGrn_pin = 11;
const int pedRed_pin = 5;
const int pedGrn_pin = 4;
const int pedBtn_pin = 3;
enum STATES {
GREEN, // 0
BLINK_ON, // 1
BLINK_OFF, // 2
YELLOW, // 3
RED, // 4
} state, old_state;
// system variables
bool isButtonPressed;
bool isTimePassed;
bool isCycleFinished;
unsigned long currentTime;
unsigned long lastTime;
int blinkCounter;
bool isRed = true;
// button variables
bool btn_val, btn_old_val;
void setup() {
pinMode(carRed_pin, OUTPUT);
pinMode(carYlw_pin, OUTPUT);
pinMode(carGrn_pin, OUTPUT);
pinMode(pedRed_pin, OUTPUT);
pinMode(pedGrn_pin, OUTPUT);
pinMode(pedBtn_pin, INPUT_PULLUP);
}
void loop() {
readButton();
currentTime = millis();
switch (state) {
case GREEN:
if (isButtonPressed && currentTime - lastTime > 3000) {
state = BLINK_OFF;
}
carLeds(0, 0, 1);
pedLeds(1, 0);
break;
case BLINK_OFF:
if (currentTime - lastTime > 500) {
state = BLINK_ON;
}
if (blinkCounter == 3) {
state = YELLOW;
}
carLeds(0, 0, 0);
pedLeds(1, 0);
break;
case BLINK_ON:
if (currentTime - lastTime > 500) {
state = BLINK_OFF;
blinkCounter++;
}
carLeds(0, 0, 1);
pedLeds(1, 0);
break;
case YELLOW:
if (currentTime - lastTime > 2000 && isRed) {
state = RED;
}
if (currentTime - lastTime > 2000 && !isRed) {
state = GREEN;
}
carLeds(0, 1, 0);
pedLeds(1, 0);
break;
case RED:
if (currentTime - lastTime > 5000) {
isRed = false;
state = YELLOW;
}
carLeds(1, 0, 0);
pedLeds(0, 1);
break;
}
if (state != old_state) {
lastTime = currentTime;
}
if (state == GREEN && old_state == YELLOW) {
isRed = true;
blinkCounter = 0;
isButtonPressed = false;
}
old_state = state;
}
void carLeds (bool cR, bool cY, bool cG) {
digitalWrite(carRed_pin, cR);
digitalWrite(carYlw_pin, cY);
digitalWrite(carGrn_pin, cG);
}
void pedLeds (bool pR, bool pG) {
digitalWrite(pedRed_pin, pR);
digitalWrite(pedGrn_pin, pG);
}
void readButton() {
btn_val = !digitalRead(pedBtn_pin);
Serial.println(btn_val);
if (btn_val && !btn_old_val) {
isButtonPressed = true;
}
btn_old_val = btn_val;
}