In most of my Arduino projects I find myself in a situation where two things apply:
void loop()function needs to run very quickly.
- 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.
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:
(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:
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.