This reminded me of a piece of code I wrote a few months ago. I wanted to write a function: boolean every(long micros) , that would return true if micros microseconds had elapsed since last time it returned true, and false at all other times. So you could write for example: if(every(1000000))toggleLed(13); To discriminate between different calls to every in the same program I needed to know the return address to the caller, and I used __builtin_return_address(0) for that. There is __builtin_frame_address too which might be helpful.
Here are the docs for those functions: Return Address (Using the GNU Compiler Collection (GCC))
(What I ended up doing with every was to use preprocessor metaprogramming to make every into a macro. Then I could use COUNTER to discriminate between calls. Usage is now even simpler: every(1000000)toggleLed(13); This is probably the worst hack I have ever written, but for simple LED flashing it seems to work)
//usage: every(time) doSomething();
// time = period in microseconds
// Be careful, this macro has a trailing if and can bite you. You have been warned!
// This code guaranteed safe for use in life support systems, nuclear power stations
// and large hadron colliders
#define CONCAT( a, b ) a##b
#define every2(id,time) static unsigned long CONCAT(_ec , id) = 0; \
unsigned long CONCAT(_et , id) = micros(); \
boolean CONCAT(_eb , id) = (CONCAT(_et , id) -CONCAT(_ec , id)) >= time; \
if(CONCAT(_eb , id)) CONCAT(_ec , id) += time; \
if(CONCAT(_eb , id))
#define every(time) every2( __COUNTER__ ,time)
boolean p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13;
void setup() {
for(int i=2;i<=13;i++)pinMode(i,OUTPUT);
}
void loop() {
every(30000000/51) digitalWrite( 2, p2= !p2);
every(30000000/52) digitalWrite( 3, p3= !p3);
every(30000000/53) digitalWrite( 4, p4= !p4);
every(30000000/54) digitalWrite( 5, p5= !p5);
every(30000000/55) digitalWrite( 6, p6= !p6);
every(30000000/56) digitalWrite( 7, p7= !p7);
every(30000000/57) digitalWrite( 8, p8= !p8);
every(30000000/58) digitalWrite( 9, p9= !p9);
every(30000000/59) digitalWrite(10,p10=!p10);
every(30000000/60) digitalWrite(11,p11=!p11);
every(30000000/61) digitalWrite(12,p12=!p12);
every(30000000/62) digitalWrite(13,p13=!p13);
}