unsigned long myTimer = 0;
const unsigned long RunPeriod = 2800;
unsigned long myCounter = 0;
boolean startHasBeenPressed = false;
const byte startButtonPin = 4;
const byte STOPButtonPin = 5;
#define pressed LOW
#define released HIGH
void setup() {
Serial.begin(115200);
// function-call to that part of the code that does
// what the function names are saying
printStartMessage();
pinMode(startButtonPin, INPUT_PULLUP);
pinMode(STOPButtonPin, INPUT_PULLUP);
}
void loop() {
// function-calls to that part of the code that does
// what the function's name are says
checkForStartButtonPress();
checkForSTOPButtonPress();
doTimeBasedUpCounting();
}
// 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 printStartMessage() {
Serial.println("Setup-Start");
Serial.println("press green button to start non-blocking");
Serial.println("time-based upcounting loop");
Serial.println("press red button to STOP the 'looping'");
}
void checkForStartButtonPress() {
// 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 ....");
}
}
}
void checkForSTOPButtonPress() {
// check if upcounting is running
if (startHasBeenPressed == true) {
// check if STOP-button us pressed
if ( digitalRead(STOPButtonPin) == pressed) {
startHasBeenPressed = false;
Serial.print("STOP-Button terminated upcounting at counter=");
Serial.println(myCounter);
myCounter = 0;
Serial.print("time between pressing Start / STOP-Button ");
Serial.print(millis() - myTimer);
Serial.println(" milliseconds");
}
}
}
void doTimeBasedUpCounting() {
// 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
}
}
}