I have not found an easy to use non-blocking on/off-delay / cycle timer library and for this reason I created the muTimer library.
This library does not use any hardware timers, it uses the Arduino millis() function to store the current time and compares it then with the current time later.
It is also registered in the PlatformIO registry.
I hope it is easy to understand for beginners as well.
The library probably works with any other platform if you replace the millis() function with any other function that returns msec as uint32_t.
The functions
delayOn()
delayOff()
delayOnOff()
provide simple on and off delays for any digital signal.
The function cycleOnOff() provides a simple cyclically on/off output, for example to blink a LED.
cycleTrigger() allows to run periodically any action once after each cycle.
Example code to create a simple on/off-delay for a digital signal.
Can be used as general on/off delay as well as button/switch debounce.
#include <muTimer.h>
// input and output variables, typically assigned to hardware in- and outputs
bool input1;
bool output1;
// create timer object
muTimer myDelay1 = muTimer();
void setup()
{
}
void loop()
{
// on-delay: 2000 ms, off-delay: 1000 ms
output1 = myDelay1.timerOnOff(input1, 2000, 1000);
}
// in : _______------------______---______________------------_------
// out: ___________----------_________________________---------------
Example code for a flashing LED:
#include <muTimer.h>
// processor pin definitions
#define PIN_LED 9
// LED1 status variable
bool LED1;
// muTimer object
muTimer myCycle1 = muTimer();
void setup()
{
// configure output hardware pin
pinMode(PIN_LED, OUTPUT);
}
void loop()
{
// LED flashing with 100ms on and 500ms off
LED1 = myCycle1.cycleOnOff(100, 500);
// write LED1 status to hardware output
digitalWrite(PIN_LED, LED1);
}
// out: _____-_____-_____-_____-_____
I started about one month ago with the programming of an Arduino Mega unit and this is actually my first C++ library (I just programmed in C before), any comments are welcome.
I’ve had a few dealings with this type of thing in the past – I’ve worked with pseudo-schedulers for the Arduino. They always forget that the millis() counter will rollover from 0xffffffff to 0 at some point.
Granted, that point is 49 days, 17 hours, 2 minutes, and 47.29487424 seconds (plus one solitary millisecond to cause the rollover) after the sketch starts running, but it does happen.
I think your code should be ok as the calculations should all be done as unsigned, but if you wanted to, you can test rollover without waiting all that time like this:
If necessary, I’m sure that changing lines similar to if (millis() - _startTime >= delayTimeSwitchOn) to if (abs(millis() - _startTime) >= delayTimeSwitchOn) will suffice. You might need to #include <cstdlib> for PlatformIO and non-Arduino framework. But as I mentioned, probably not required – just a thought.
When I get some playtime, I’ll have a better look.