[Solved - yes] Can I change an ISR while my program is running?

I am using the Timer2 Compare Match A interrupt and all is working perfectly.

The standard name of the ISR is

ISR(TIMER2_COMPA_vect) {

}

I would like to use the same timer for a different purpose at another stage in my sketch. I could use a state variable and use some IF statements to test it at the start of the ISR to decide which piece of ISR code to run.

However it would be nicer (faster) if at different points in the program I could tell the Timer interrupt to call a different ISR - similar to what you can do with AttachInterrupt().

Does anyone know how to do this, or if it is possible? (Google has not helped)

Another possibility might be to have a function call in the ISR - like this

ISR(TIMER2_COMPA_vect) {
    doMyFunction();
}

if it is possible to change the function that doMyFunction() actually calls.

…R

I'm afraid that is not able to change ISR during program run, ISR call is based on int. vector in FLASH memory. Just insert some 'if' into ISR, it can solve it.

You could implement your own "attach" using a function pointer.

ISR(TIMER2_COMPA_vect)  {
    (void)(*action)();
}

// somwhere in code
     action = myFunction1;
.
.
.
    action = myFunction2;

...but in fact it is similar what attach/detachInterrupt do.

Budvar10:

ISR(TIMER2_COMPA_vect)  {

(void)(*action)();
}

// somwhere in code
     action = myFunction1;
.
.
.
    action = myFunction2;



...but in fact it is similar what attach/detachInterrupt do.

Isn’t that what I said?

AWOL:
You could implement your own "attach" using a function pointer.

Thanks - that enabled me to "point" Google in the right direction.

@Budvar10, yes, I think that's how mine will look.

...R

The pointer assignment won't be atomic, so you'll probably want to protect the assignment by disabling interrupts.

You could make it atomic by replacing the function pointer with a number that selects which handler function to call. This would also make it possible to inline the handler functions, saving the overhead of the second function call.

. . . But make sure the number is a single byte. :wink:

...enough complexity already ....

I will disable interrupts where I need to change it while interrupts are active. Thanks for the Heads Up.

...R