// Code by Novelio Putra Indarto
// email: [email protected]
#include <Arduino.h>
#include <TM1637Display.h>
// Define Pin to the Traffic LED and the Pedestrian Button
#define sigR 5
#define sigY 4
#define sigG 3
#define pedestrian 2
// Define the states
enum State {
RED,
YELLOW,
GREEN,
PENDING
} state;
// Define the counter
uint8_t count;
uint32_t oneSecLoop;
TM1637Display display(9, 8);
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(sigR, OUTPUT);
pinMode(sigY, OUTPUT);
pinMode(sigG, OUTPUT);
pinMode(pedestrian, INPUT_PULLUP);
state = RED;
digitalWrite(sigR, HIGH);
Serial.println("Initial State is RED, starting FSM");
display.setBrightness(0x0f);
}
void loop() {
oneSecLoop = millis();
FSMTrafficLight();
display.showNumberDec(count, true);
while (millis() - oneSecLoop < 1000);
}
void FSMTrafficLight() {
switch (state) {
case RED:
if (count >= 60) {
Serial.println("Change State to GREEN after 60s");
state = GREEN;
digitalWrite(sigR, LOW);
digitalWrite(sigG, HIGH);
count = 0;
} else {
count++;
}
break;
case GREEN:
if (count >= 60) {
Serial.println("Change State to YELLOW after 60s");
state = YELLOW;
digitalWrite(sigG, LOW);
digitalWrite(sigY, HIGH);
count = 0;
} else {
if (!digitalRead(pedestrian)) {
Serial.println("Change State to PENDING because there is a pedestrian");
state = PENDING;
}
count++;
}
break;
case YELLOW:
if (count >= 5) {
Serial.println("Change State to RED after 5s");
state = RED;
digitalWrite(sigY, LOW);
digitalWrite(sigR, HIGH);
count = 0;
} else {
count++;
}
break;
case PENDING:
if (count >= 60) {
Serial.println("Change State to YELLOW after 60s");
state = YELLOW;
digitalWrite(sigG, LOW);
digitalWrite(sigY, HIGH);
count = 0;
} else {
count++;
}
break;
default: break;
}
}