c - How to implement separate static variables for a given function called with different parameters -


i working on microcontroller project in c requires several timed functions take place. using hardware timer produce interrupt every millisecond, , variables counters produce appropriate time intervals. hardware details not important.

as example, particular function, following code executed on every tick of 1ms counter, resulting in function() being called every 10ms.

if (count < 10) {     count++; } else {     function();     count = 0; } 

i implement wrapper function avoid rewriting counter code every different interval, i.e:

timerwrapper(required interval 1, function 1 pointer) timerwrapper(required interval 2, function 2 pointer) 

and call on every tick of timer. work, each different function called wrapper needs have separate count variable needs persist between calls of timerwrapper(). keep of implementation details separate main program , introduce few variables main program possible.

is possible asking, or there simpler/better way achieve same effect? know how object oriented language skills lacking in plain c.

i think in terms of structure along lines of:

struct interrupt_responder {     int count;     int rep_count;     void (*handler)(void); }; 

you create many such structures have different counters, appropriately initialized:

static struct interrupt_responder c1 = { 0, 10, function }; 

you arrange call function responder:

void time_wrapper(struct interrupt_responder *r) {     if (++r->count >= r->max_count)     {         r->count = 0;         (*r->handler)();     } } 

the function called in response interrupt needs know how dispatch calls time_wrapper appropriate argument each time.

void millisecond_interrupt_handler(void) {     time_wrapper(&c1);     … } 

or can have array of interrupt responders, , millisecond interrupt handler can loop on array, calling time wrapper function.

you have set of file scope variables interrupt responders, they'd not need visible outside file. if need different argument lists handler functions, life trickier — avoid if possibly can. however, seems comment won't problem — embedded functions pointers void (*handler)(void).


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -