/*
  Arduino | coding-help
  Stoplight help
  icyiscool — October 14, 2025 at 11:10 PM
  So i was makeing a stoplight and I need it so when I push
  my analog buttio it swices bwteen modes green, red, normal
  (red then yellow then green)
*/
const int BTN_PIN = 10;
const int LED_PINS[] = {9, 8, 7};
const char* MODE_NAMES[] = {
  "Normal", "Red Blinker", "Yellow Blinker"
};
const unsigned long MODE_INTERVALS[] = {3000, 1000, 3000};
const unsigned long BLINK_INTERVAL = 1000;
bool flash = false;       // hold flasher state
int mode = 0;             // normal, red blink, yel blink
int ledIdx = 0;           // LED index
int oldBtnState = HIGH;   // hold button state
unsigned long prevCycleTime = 0;
unsigned long prevFlashTime = 0;
bool checkButton()  {
  bool wasPressed = false;
  int btnState = digitalRead(BTN_PIN);  // read the pin
  if (btnState != oldBtnState)  {       // if it changed
    oldBtnState = btnState;             // remember the state
    if (btnState == LOW)  {             // was just pressed
      wasPressed = true;
      //Serial.println("Button Pressed");
    } else  {                           // was just released
      //Serial.println("Button Released");
    }
    delay(20);  // short delay to debounce button
  }
  return wasPressed;
}
void flasher(int index) {
  if (millis() - prevFlashTime >= BLINK_INTERVAL) {
    prevFlashTime = millis();
    flash = !flash;
  }
  digitalWrite(LED_PINS[index], flash);
}
void ledsOff()  {
  for (int i = 0; i < 3; i++) {
    digitalWrite(LED_PINS[i], LOW);
  }
}
void showRYG()  {
  digitalWrite(LED_PINS[ledIdx], HIGH);
  if (millis() - prevCycleTime >= MODE_INTERVALS[ledIdx])  {
    prevCycleTime = millis();
    ledsOff();
    ledIdx++;
    if (ledIdx >= 3) ledIdx = 0;
  }
}
void setup() {
  Serial.begin(9600);
  pinMode(BTN_PIN, INPUT_PULLUP);
  for (int pin = 0; pin < 3; pin++) {
    pinMode(LED_PINS[pin], OUTPUT);
  }
  Serial.println("Ready\n");
  Serial.print("Mode: ");
  Serial.println(MODE_NAMES[mode]);
}
void loop() {
  if (checkButton())  {
    mode++;
    if (mode >= 3) mode = 0;
    ledsOff();
    ledIdx = 0;
    prevCycleTime = millis();
    Serial.print("Mode: ");
    Serial.println(MODE_NAMES[mode]);
  }
  if (mode == 0)  {
    showRYG();
  } else if (mode == 1) {
    flasher(0);
  } else if (mode == 2) {
    flasher(1);
  }
}