Multiple non-blocking countdown timers? I'm building a control system for three sump pumps using a single Arduino and a set of relays.  I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered.  Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.

Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal.  This throws me for a loop since I need the other pumps and sensors to function during this delay time.  I quickly found that the blocking delay() function is no longer feasible.

How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays?  Would a non-blocking timer solution work?  Would I have to delve into interrupts?
Would a non-blocking timer solution work?


Yes.  Your "timer" doesn't have to be anything more than a start time from millis() and a flag.  Then your loop just compares the start time to the current millis() value, and if it's more than the interval you wanted, do the "thing".  In code:

uint32_t startTime;
bool waiting = false;
const uint32_t PUMP_DURATION = 30000UL;

void setup()
{
  // start the "timer"
  startTime = millis();
  waiting = true;
}

void loop()
{
  if (waiting &amp;&amp; (millis() - startTime &gt;= PUMP_DURATION)) {
    waiting = false;
    // do something now!
    foo();
  }


The flag keeps it from checking when the pump isn't running.

If you have multiple timed things, just make another set of variables (i.e., startTime2 and waiting2).  Give 'em better names, eh?

There are also Arduino libraries that encapsulate this common design pattern.  TimeMark is one.

Here's some sample code on the Arduino forum.