unsigned long myTimer = 0;
const unsigned long RunPeriod = 2800;
unsigned long myCounter = 0;
boolean startHasBeenPressed = false;
const byte startButtonPin = 4;
#define pressed LOW
#define released HIGH
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
Serial.println("press button to start non-blocking");
Serial.println("time-based upcounting loop");
pinMode(startButtonPin, INPUT_PULLUP);
}
void loop() {
// check if counting up through pressing the button
// has not yet started
if (startHasBeenPressed == false) {
// check for button-press
if ( digitalRead(startButtonPin) == pressed) {
startHasBeenPressed = true;
myTimer = millis(); // store snapshot of time
Serial.println("Startbutton pressed start counting ....");
}
}
// check if startbutton has been pressed
if (startHasBeenPressed == true) {
myCounter++;
// check if number of milliseconds
// stored in variable RunPeriod have passed by
if ( TimePeriodIsOver(myTimer, RunPeriod) ) {
// when number of milliseconds stored in variable RunPeriod
// have REALLY passed by
startHasBeenPressed = false; // stop counting
Serial.print("counting up for ");
Serial.print(RunPeriod);
Serial.print(" milliseconds is over myCounter=");
Serial.println(myCounter);
myCounter = 0; // reset counter to zero
}
}
}
// 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
}