// Delay execution until condition has been true for X secs // delay printing a “Finished” message until there has been no input from the Serial Monitor for 10secs. #include // see the tutorial https://www.forward.com.au/pfod/ArduinoProgramming/TimingDelaysInArduino.html /* (c)2018 Forward Computing and Control Pty. Ltd. NSW Australia, www.forward.com.au This code is not warranted to be fit for any purpose. You may only use it at your own risk. This generated code may be freely used for both private and commercial use provided this copyright is maintained. */ millisDelay executionDelay; // the delay object unsigned long executionDelay_mS = 5000; bool executedMethod = false; bool condition() { // returns when the condition is true return (Serial.read() == -1); // Serial.read() returns -1 when there is nothing to read // other types of conditions could be Range < 5cm etc } void setup() { Serial.begin(115200); // wait a few sec to let user open the monitor for (int i = 5; i > 0; i--) { delay(1000); Serial.print(i); Serial.print(' '); } Serial.println("Enter input at least every 5 secs"); } void loop() { if (executionDelay.justFinished()) { // nothing read for 10 sec //executionDelay only returns true once after start() // do something here executedMethod = true; // only do this once even if condition remains true for a long time Serial.println(" No input for 5 sec."); } if (condition()) { if (!executionDelay.isRunning() && (!executedMethod)) { // start it now executionDelay.start(executionDelay_mS); } // else already timing out don't disturb it OR has already timed out and executed } else { // condtion() is false out side range etc // stop timer executionDelay.stop(); // clear executedMethod so will execute again one condition is true for 5sec executedMethod = false; } }