The "StateChangeDetection" sketch is for a button with only two states. A State Machine generally has more states. I like to use an enumeration to name the states and a switch statement to sort out the states:
enum {WaitingForSwitchOn, MotorMovingOut, DwellPeriod, WaitingForSwitchOff, MotorMovingIn} machineState = WaitingForSwitchOn;
void loop() {
switch (machineState){
case WaitingForSwitchOn:
if (switchPin) {
timerStart = millis();
digitalWrite(CWPin, HIGH);
machineState = MotorMovingOut;
}
break;
case MotorMovingOut:
if (millis() - timerStart > MotorTime) {
digitalWrite(CWPin, LOW);
timerStart = millis;
machineState = DwellPeriod;
}
break;
case DwellPeriod:
if (millis() - timerStart > Dwell) {
machineState = WaitingForSwitchOff;
}
break;
case WaitingForSwitchOff:
if (!switchPin) {
timerStart = millis();
digitalWrite(CCWPin, HIGH);
machineState = MotorMovingIn;
}
break;
case MotorMovingIn:
if (millis() - timerStart > MotorTime) {
digitalWrite(CCWPin, LOW);
machineState = WaitingForSwitchOn;
}
break;
}
}