That's not expressed as a proper state machine. A state machine would be more like:
- if (input reads HIGH) startTime=millis(); state = 2;
- if (millis() - startTime >= debounceTime) state = 3; if (input reads LOW) state = 1;
- if (input reads LOW) state = 4
- take action. state = 1;
In code, that would be:
const byte ButtonPin = 4;
int State = 1;
unsigned long StartTime;
const unsigned long DebounceTime = 10;
void setup()
{
pinMode(ButtonPin, INPUT);
}
void loop()
{
switch (State)
{
case 1:
if (digitalRead(ButtonPin) == HIGH)
{
StartTime = millis();
State = 2;
}
break;
case 2:
if (millis() - StartTime >= DebounceTime)
State = 3; // Still HIGH at end of wait
if (digitalRead(ButtonPin) == LOW)
State = 1; // Went LOW before end of wait
break;
case 3:
if (digitalRead(ButtonPin) == LOW)
State = 4; // Button released
break;
case 4:
// take action
// Go back to waiting for a button press
State = 1;
break;
}
}