During coding I started to notice that in my functions where I would use millis() for timing I always typed the exact same words.
void foobar()
{
static uint32_t previousTime ;
uint32_t currentTime = millis() ;
if( currentTime - previousTime >= someInterval )
{
previousTime = currentTime ;
PORTB ^= (1<<5); // toggle led pin 13
}
}
It was the same in every function. I like to use a static variables to keep track of the previous time so I don't have to declare a global variable for every timed event + this allowed me to use the phrase 'previousTime' everywhere.
Because I grew tired of re-typing/copying the same things over and over again. I started to look for alternatives. There are great alternatives such as the fire timer library
And this interesting contraption of LarryD
Especially the latter, well it is quite a code contraption. The problem I had with both these examples is that they work with global objects/variables for timing things.
So every time when you need to do some timing somewhere inside a function, you have to both declare and initialize a new global timer object thingy. And all your timer objects need to have different names.
To solve all of these problems (problem #1 is me being lazy) I devised these little macros to achieve the exact same thing with minimum effort.
#define REPEAT_US(x) { \
static uint32_t previousTime ; \
uint32_t currentTime = micros() ; \
if( currentTime - previousTime >= x ) \
{ \
previousTime = currentTime ;
#define REPEAT_MS(x) { \
static uint32_t previousTime ; \
uint32_t currentTime = millis() ; \
if( currentTime - previousTime >= x ) \
{ \
previousTime = currentTime ;
#define END_REPEAT } \
}
These macros just do the exact same thing as the program 'blinkingWithoutDelay' does.
If you want to use these you can just type something like:
void foobar()
{
REPEAT_MS( someInterval ) ;
PORTB ^= (1<<5); // toggle led pin 13
END_REPEAT
REPEAT_MS( someOtherInterval ) ;
doSomethingElse() ;
END_REPEAT
REPEAT_US( microsInterval ) ;
IworkWithMicros() ;
END_REPEAT
}
You can use these macros wherever, whenever and how often you want. Inside funtions, inside void loop(). You can do it more than once inside a function without problems. Besides the macros and an #include <Arduino.h> for your custom source files, you don't need anything else. No libraries no complicated contraptions.
You don't have to declare and initialize new timer objects and variables. I admit that the construction looks odd to the eye as you don't see the parenthesis but it works so well and so far it made my life a lot easier. So easy that I had to share this.
I hope these macros can help others with their projects as well.
Kind regards,
Bas