/*
  Forum: https://forum.arduino.cc/t/i-do-not-read-analog-input-with-millis-function/1310084
  
  State Machine I
     Wokwi: https://wokwi.com/projects/411558098269010945

  State Machine II:
      Wokwi: https://wokwi.com/projects/411555525808778241

  Restart at any time by sending R or r via Serial ...
  Restart after "End of Game" by sending G or g via Serial ...

*/

// +++++++++++++ global constants and enums ++++++++
const unsigned long intervalLen = 100;
const unsigned long periodLen = 10000;
const int maxRepetitions = 3;
enum States {FIRST, SECOND, THIRD};
States state = FIRST;

// +++++++++++++ global variables ++++++++
unsigned long intervalStart = 0;
unsigned long periodStart = 0;
int repeated  = 0;
int count = 0;

void setup() {
  Serial.begin(115200);
  Serial.println("Start");
}

void loop() {
  stateMachine();
  checkEndOfGame();
  resetOnSerialInput();
}

/********************************************************
                  Functions
 ********************************************************/
void stateMachine() {
  switch (state) {
    case FIRST:
      repeated++;
      Serial.print("First state");
      Serial.println(repeated);
      state = SECOND;
      periodStart = 0;
      break;
    case SECOND:
      if (doneFor10Seconds()) {
        state = FIRST;
      }
      break;
    case THIRD:
      // Do nothing here
      break;
  }
}

void checkEndOfGame() {
  if (repeated >= maxRepetitions && state != THIRD) {
    Serial.println("End of Game ...");
    state = THIRD;
  }
}

boolean doneFor10Seconds() {
  // Do something each 100 ms for 10 seconds
  if (periodStart == 0) {
    periodStart = millis();
  }
  if (millis() - intervalStart >= intervalLen) {
    intervalStart = millis();
    count++;
    Serial.print("Second state count = ");
    Serial.println(count);
  }
  return (millis() - periodStart >= periodLen);
}

void resetOnSerialInput() {
  while (Serial.available()) {
    char c = Serial.read();
    bool reset = (c == 'R' || c == 'r');
    bool restart = (c == 'G' || c == 'g') && state == THIRD;
    if (reset || restart) {
      Serial.println(reset ? "Reset" : "Restart");
      repeated = 0;
      count = 0;
      state = FIRST;
    }
  }
}