/* Robust Timer (c)Forward Computing and Control Pty. Ltd. Works even if sometimes the loop() takes longer the 1mS to execute. This example code is in the public domain. */ static unsigned long lastMillis = 0; // holds the last read millis() static int timer_1 = 0; // a repeating timer max time 32768 mS = 32sec use an unsigned long if you need a longer timer // NOTE timer_1 is a signed int #define TIMER_INTERVAL_1 2000 // 2S interval static int timer_2 = 0; // a one off timer max time 32768 mS = 32sec use an unsigned long if you need a longer timer // NOTE timer_2 is a signed int #define TIMER_INTERVAL_2 5000 // 2sec interval // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. timer_1 = TIMER_INTERVAL_1; // timeout in first loop timer_2 = TIMER_INTERVAL_2; // set up one off timer times out in 10 sec Serial.begin(9600); while (Serial.available()) { } Serial.println("Timer Begin"); lastMillis = millis(); // do this last in setup } // the loop routine runs over and over again forever: void loop() { // set millisTick at the top of each loop if and only if millis() has changed unsigned long deltaMillis = 0; // clear last result unsigned long thisMillis = millis(); // do this just once to prevent getting different answers from multiple calls to millis() if (thisMillis != lastMillis) { // we have ticked over // calculate how many millis have gone past deltaMillis = thisMillis-lastMillis; // note this works even if millis() has rolled over back to 0 lastMillis = thisMillis; } // handle one off timer // repeat this code for each timer you need to handle if (timer_2 > 0) { // still counting down timer_2 -= deltaMillis; if (timer_2 <= 0) { // timer timed out // do timeout stuff here // in this set the led HIGH Serial.println("Timer 2 timed out"); } } // handle repeating timer // repeat this code for each timer you need to handle timer_1 -= deltaMillis; if (timer_1 <= 0) { // reset timer since this is a repeating timer timer_1 += TIMER_INTERVAL_1; // note this prevents the delay accumulating if we miss a mS or two // if we want exactly 1000 delay to next time even if this one was late then just use timeOut = 1000; // do time out stuff here Serial.println("Repeating Timer 1 timed out"); } }