// Module #5 project
const int LED_PINS[] = {19, 21, 22, 17, 5, 18}; //NSR, NSY, NSG, EWR, EWY, EWG
const int XW_BTN_PIN = 23;
const int STATES[][6] = {
{0, 0, 1, 1, 0, 0}, // NS go, EW stop
{0, 1, 0, 1, 0, 0}, // NS caution
{1, 0, 0, 1, 0, 0}, // NS stop, EW stop
{1, 0, 0, 0, 0, 1}, // EW go, NS stop
{1, 0, 0, 0, 1, 0}, // EW caution
{1, 0, 0, 1, 0, 0} // NS stop, EW stop
};
const unsigned long DELAYS[] = {5, 1, 2, 5, 1, 2}; // in seconds
const unsigned long DEBOUNCE_TIME = 20;
const unsigned long HALF_SEC = 500;
int state = 0;
unsigned long prevBlinkTime = 0;
unsigned long prevStateTime = 0;
bool checkButton() {
static unsigned long lastTime = 0;
static bool lastState = true;
bool isPressed = false;
bool currentState = digitalRead(XW_BTN_PIN);
unsigned long now = millis();
if (currentState != lastState && now - lastTime >= DEBOUNCE_TIME) {
if (!currentState) {
Serial.println("Crosswalk pressed!");
isPressed = true;
} else {
Serial.println("Crosswalk released!");
}
lastTime = now;
lastState = currentState;
}
return isPressed;
}
bool doWalk() {
static int count = 0;
static int ledState = 0;
bool isDone = false;
if (millis() - prevBlinkTime >= HALF_SEC) {
prevBlinkTime = millis();
ledState = !ledState;
count++;
if (count % 2) {
Serial.print(" Count = ");
Serial.print(10 - (count / 2));
Serial.println(" == Walk == ");
}
}
if (count > 20) { // 20 * half-second = 10 seconds
isDone = true;
count = 0;
state = 5;
ledState = 0;
}
digitalWrite(LED_PINS[0], ledState); // NS Red
digitalWrite(LED_PINS[3], ledState); // EW Red
return isDone;
}
void setup() {
Serial.begin(115200);
pinMode(XW_BTN_PIN, INPUT_PULLUP); // 0=pressed, 1 = unpressed button
for (int i = 0; i < 6; i++) {
pinMode(LED_PINS[i], OUTPUT);
}
// set LEDs to state 0
for (int i = 0; i < 6; i++) {
digitalWrite(LED_PINS[i], STATES[state][i]);
}
}
void loop() {
static bool isWalk = false;
if (checkButton()) { // if crosswalk button pressed
for (int i = 0; i < 6; i++) {
digitalWrite(LED_PINS[i], LOW);
}
isWalk = true;
}
if (isWalk) {
isWalk = !doWalk();
} else { // normal traffic light
if (millis() - prevStateTime >= DELAYS[state] * 1000UL) {
prevStateTime = millis();
state++;
if (state == 6) state = 0;
Serial.print("State: ");
Serial.print(state);
Serial.println(" == Don't Walk == ");
for (int i = 0; i < 6; i++) {
digitalWrite(LED_PINS[i], STATES[state][i]);
}
}
}
}
N-S
E-W