/*
Forum: https://forum.arduino.cc/t/variable-types-used-in-state-machine/1405843
Wokwi: https://wokwi.com/projects/441646568487244801
*/
constexpr uint8_t analogPins[] = {A3, A4, A5}; // analog pin names for the LEDs
constexpr uint8_t ledNumber = sizeof(analogPins) / sizeof(analogPins[0]);
unsigned long base_time_increment = 150; // increment of time between LEDs
unsigned long base_time_offset = 200; // time added to all of the time_limits
int directionState;
int lastDirection;
int step = 0;
unsigned long previousMillis;
void setup() {
Serial.begin(115200);
pinMode(A0, INPUT_PULLUP);
directionState = digitalRead(A0);
lastDirection = directionState;
allLedsOn();
}
void loop() {
directionState = digitalRead(A0); // get current status of button
if (directionState != lastDirection) {
lastDirection = directionState;
delay(50); // Simple debouncing!
allLedsOn();
}
handleTiming();
}
void handleTiming() {
constexpr int addedSteps {10};
if (millis() - previousMillis > base_time_offset + base_time_increment * (step + 1)) {
if (step >= ledNumber + addedSteps) {
allLedsOn();
} else {
if (step < ledNumber && step >= 0) {
byte no = (lastDirection) ? step : ledNumber - step - 1;
digitalWrite(analogPins[no], LOW);
}
step++;
}
}
}
void allLedsOn() {
for (int i = 0; i < ledNumber; i++) {
pinMode(analogPins[i], OUTPUT);
digitalWrite(analogPins[i], HIGH); // initialize the state of the LEDs
}
previousMillis = millis();
step = 0;
}