Arduino Code – Timed Events

In most of my Arduino projects I find myself in a situation where two things apply:

  1. My void loop() function needs to run very quickly.
  2. I need to output data to the serial window.

Unfortunately outputting to the serial window can add significant performance problems, so to keep the speed up I choose to only output every n milliseconds.

This requires a timer…

Typically you record a start time (calling millis()), and then thereafter calculate an elapsed time. When a defined time threshold is reached, you perform your operation and then re-record the current ‘start’ time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
int startTime = 0;

void loop() {
  if (startTime == 0)
    startTime = millis();

  if (millis() - startTime > 1000) {
    // Do something.
    startTime = millis(); // Reset the timer.
  }
}

This code is often required several times in the same loop – Each one for a different timed action. To make my life simple, I made a class to help:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Call signal() regularly, and it will return true if the timer has elapsed (and will reset).
class TimedEvent
{
public:
  TimedEvent(unsigned long periodMs) : m_time(millis() * 1000) {
    setMicros(periodMs * 1000);
  }

  void setMicros(unsigned long periodMicros) {
    m_periodMicros = periodMicros;
    m_time = micros();
  }

  bool signal() {
    unsigned long now = micros();
    if (now - m_time >= m_periodMicros) {
      m_time = now;
      return true;
    }

    return false;
  }

private:
  unsigned long m_time;
  unsigned long m_periodMicros;
};

(See my earlier article on how to put this code into its own header file, to make it even easier to use in your projects.)

Now the same example can be written in significantly less code:

1
2
3
4
5
6
7
TimedEvent event(1000);

void loop() {
  if (event.signal()) {
    // Do something.
  }
}

Note: Internally the TimedEvent class uses microseconds, not milliseconds. If you require more fine-tuned timing (Perhaps you’re sending pulses to a stepper motor), just call setMicros() to set your time.

One Reply to “Arduino Code – Timed Events”

Leave a Reply

Your email address will not be published. Required fields are marked *