const byte myButtonPin = 4;
byte buttonPinState;
const byte myMotorPin = 12;
// constants for the state-machine
const byte sm_idling = 0;
const byte sm_OpeningGate = 1;
const byte sm_GateOpened = 2;
// constants self-explaining constants motor on/off
const byte ON = HIGH;
const byte OFF = LOW;
// INPUT_PULLUP inverts the logic states
// button unpressed = released = HIGH
// button pressed = LOW
const byte pressed = LOW;
const byte released = HIGH;
unsigned long myMotorTimer;
unsigned long myPrintTimer;
unsigned long myGateTimer;
byte myState;
void setup() {
Serial.begin(115200);
digitalWrite(myMotorPin, OFF);
Serial.println("Setup-Start");
Serial.println("press button to open gate ");
pinMode(myMotorPin, OUTPUT);
// INPUT_PULLUP inverts the logic states
// button unpressed = released = HIGH
// button pressed = LOW
pinMode(myButtonPin, INPUT_PULLUP);
myState = sm_idling; // start state-machine in state idling
}
void myStateMachine() {
buttonPinState = digitalRead(myButtonPin);
switch (myState) {
case sm_idling:
// check if button is pressed
if (buttonPinState == pressed) {
// if button is REALLY
Serial.println("button pressed opening gate...");
digitalWrite(myMotorPin, ON); // switch motor on
myMotorTimer = millis(); // store snapshot of time when motor i switched ON
myState = sm_OpeningGate; // change to state
}
break; // IMMIDIATELY jump down to END-OF-SWITCH
case sm_OpeningGate:
if ( TimePeriodIsOver(myMotorTimer, 10000) ) {
digitalWrite(myMotorPin, OFF); // switch motor off
myState = sm_GateOpened; // change to state
}
printTimingMessage(myMotorTimer); // execite lines of code defined under void printTimingMessage
break; // IMMIDIATELY jump down to END-OF-SWITCH
case sm_GateOpened:
if ( TimePeriodIsOver(myPrintTimer, 2000) ) {
Serial.println("10 seconds are over what shall happen now?");
Serial.println("I repeat this message infinitely");
}
} // END-OF-SWITCH
}
void loop() {
myStateMachine(); // cal this function over and over infinitely
}
// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - startOfPeriod >= TimePeriod ) {
// more time than TimePeriod has elapsed since last time if-condition was true
startOfPeriod = currentMillis; // a new period starts right here so set new starttime
return true;
}
else return false; // actual TimePeriod is NOT yet over
}
void printTimingMessage(unsigned long p_Timer) {
static unsigned long myPrintTimer;
unsigned long timeSinceStart;
timeSinceStart = (millis() - p_Timer) / 1000;
if (TimePeriodIsOver(myPrintTimer, 1000) ) {
Serial.print("Time since motor started ");
Serial.print(timeSinceStart);
Serial.println(" seconds");
}
}