The addition of time to NextAction is problematic too. Here's a refactor that should be better:
// States are named for ease of use
#define START 0
#define SCANNING 1
#define RESULTS 2
#define RESET 3
// Timing variables
const int StartTime = 2500;
const int ScanTime = 1500;
const int RESULTSTime = 1500;
const int ResetTime = 2000;
int state=START; // initial state
unsigned long StateStartTime=0L;
unsigned long StateDuration=0L;
void setup()
{
Serial.begin(9600); // initialize serial communication for debugging
state=START;
StateStartTime=millis();
StateDuration=StartTime;
}
void loop()
{
if(millis()-StateStartTime > StateDuration)
ChangeState();
}
void ChangeState() // Function declared outside of the main loop, for managing the state
{
StateStartTime=millis();
switch (state)
{
case START:
Serial.println("case START");
StateDuration=StartTime;
state=SCANNING;
break;
case SCANNING:
Serial.println("case SCANNING");
StateDuration=ScanTime;
state=RESULTS;
break;
case RESULTS:
Serial.println("case RESULTS");
StateDuration=RESULTSTime;
state=RESET;
break;
case RESET:
Serial.println("case RESET");
StateDuration=ResetTime;
state=START;
break;
}
}