timer functions

hello all,

using an arduino as an aquaponics greenhouse controller. One of the most important tasks assigned to the arduino is as a reoccuring timer. The recirculation pump pumps to the growbeds from the fish tanks every 20 min for 4 min. I am afraid that the method I am using is not very elegant as I am using my rtc to give me time which i convert to time in min and then have an array of 45 start times 20 min appart. I would guess that there is a better way.... have read of a few different libraries and just figured I would put it out there as a question.


Troy Pearce

Well, you could use arithmetic.

You need two more variables. One for storing the next shutoff minute (shutoffMin), and you need to keep a ‘previous minute’ (lets call is prevMin) variable, so you can detect the state change like this:

if ((min%20 == 0) && (prevMin != min)) {
  //start pumps
  shutoffMin = min + 4;
if ((min == shutoffMin) && (prevMin != min)) {

//store this min as prev for next iteration
prevMin = min;


If you have a RTC, a good way to manage the whole thing is to use the Time library. Even without the RTC you can use it if you just need durations and not the current time.

You also can just use millis(), that’s good enough for duration under 49 days. Just make sure you declare all timesstamps as unsigned long, otherwise you might get problems at roll-over time.

The proper way to do it is something like this:

#include <Time.h>

const int phasecount = 2;
unsigned long durations[phasecount] = { 1200, 240 };

... other stuff here ...

void loop() {
static int phase;
static unsigned long phasestart;

if (now() - phasestart >= durations[phase]) {
    phase = (phase + 1) % phasecount;
    phasestart = now();
    switch (phase) {
        case 0: // turn on
            // Turn things on
        case 1: // turn on
            // Turn things on

If you don’t want to use the Time library, replace the durations in seconds by durations in milliseconds (1200000L and 240000L for 20 min and 4 min) and replace now() by millis(). That’s all that’s necessary. For bonus points you can tell the Time library to synchronise with the RTC quite easily to have the correct time.


Thanks Korman and AlphaBeta.... both of your methods seem a whole lot more elegant than the way I am currently doing it.....

and Alpha...... that method seem very simple indeed..... Seems very familular from long ago programming in Fortran.... but the mind..... I just could not remember it.

Thanks again and will look into both methods not sure which one but both are better than how i am doing it.....

Thanks again Troy