/*
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 FirstDuration = 5000;
const unsigned long SecondDuration = 10000;
const unsigned long printEvery = 1000;
enum States {FIRST, SECOND, THIRD};
States state = FIRST;
// +++++++++++++ global variables ++++++++
unsigned long stateStart = 0;
uint32_t count = 0;
void setup() {
Serial.begin(115200);
Serial.println("Start");
}
void loop() {
stateMachine();
resetOnSerialInput();
}
/********************************************************
Functions
********************************************************/
void stateMachine() {
switch (state) {
case FIRST:
if (stateStart == 0) {
stateStart = millis();
count = 0;
}
if (millis() - stateStart <= FirstDuration) {
printEverySecond("FIRST");
} else {
Serial.println("Leaving FIRST for SECOND");
stateStart = 0;
state = SECOND;
}
break;
case SECOND:
if (stateStart == 0) {
stateStart = millis();
count = 0;
}
if (millis() - stateStart <= SecondDuration) {
printEverySecond("SECOND");
} else {
Serial.println("Leaving SECOND for THIRD");
state = THIRD;
}
break;
case THIRD:
// Do nothing here
break;
}
}
void printEverySecond(char text[]) {
static unsigned long lastPrint = 0;
if (millis() - lastPrint >= 1000 ) {
lastPrint = millis();
count++;
Serial.print(text);
Serial.print(" ");
Serial.println(count);
}
}
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");
Serial.println("Leaving THIRD for FIRST");
stateStart = 0;
state = FIRST;
}
}
}