The ArduinoTimer
class in our Arduino library is a simple wrapper around the Arduino’s millis()
to make it easier to run code periodically. Check out delays are boring in our article 5 tips for Arduino programs to see why blocking code causes problems.
Using the millis()
timer directly, you need to write something like:
1 2 3 4 5 6 7 8 |
static uint32_t LastTime = 0; uint32_t Now = millis(); if ((Now - LastTime) > 2000) { LastTime = Now; Serial.println("This will happen every two seconds"); } |
Using the ArduinoTimer
class you can write:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include "ArduinoTimer.h" ArduinoTimer Timer1; ArduinoTimer Timer2; void setup() { Serial.begin(9600); } void loop() { if (Timer1.TimePassed_Milliseconds(300)) { Serial.println("300 ms has passed"); } if (Timer2.TimePassed_Seconds(10)) { Serial.println("10 seconds has passed. My time flies!"); } } |
The methods supported by the ArduinoTimer are:
Reset();
Resets the timer to the current value of themillis
timerEllapsedMilliseconds();
Returns the number of milliseconds that have passed since the timer was last resetEllapsedSeconds();
Returns the number of seconds that have passed since the timer was last reset- TimePassed_Milliseconds(Period, AutoReset — optional); Returns true if Period milliseconds have elapsed since the timer was last reset. If AutoReset is true, or not present, the timer will be reset if the period has passed
TimePassed_Seconds(Period, AutoReset — optional);
Returns true if Period seconds have elapsed since the timer was last reset. If AutoReset is true, or not present, the timer will be reset if the period has passedTimePassed_Minutes(Period, AutoReset — optional);
Returns true if Period minutes have elapsed since the timer was last reset. If AutoReset is true, or not present, the timer will be reset if the period has passedTimePassed_Hours(Period, AutoReset — optional);
Returns true if Period hours have elapsed since the timer was last reset. If AutoReset is true, or not present, the timer will be reset if the period has passedStartTime();
The value of themillis
counter when the timer was last reset