Interrupts and service routines

Can detachInterrupt be placed in an ISR? specifically for the interrupt that caused the iSR to execute?

Yes.

It would have the effect of preventing that interrupt from being triggered again. That is not at all unusual.

...R

Thanks. My problem must be elsewhere.

On a related topic ... does attachInterrupt clear the interrupt pending queue? That is, if there is an interrupt pending on (say) external interrupt 2 when the attachInterrupt is executed, does the ISR get triggered immediately? if so, how does one clear the queue?

There is no interrupt pending queue, so there is no reason to clear it. ;)

Interrupts (normally) don't pend, they get executed asynchronously interrupting the normal flow of control.

Only a tiny fraction of the processing time interrupts are disabled, that's when interrupts can kind of "pend".

They get executed as soon as interrupts get enabled (after one instruction enabled) in the order of their priority.

No and NO. No it does not clear the Q. And no there will not be a pending interrupt in any case.

Do not use detach at all. Attach the interrupt in setup and then leave it alone. Use a flag in the ISR to control the action of the ISR.

Detach, as specified, is NOT safe for use in an ISR. It may turn ON interrupts when called. You could check the code to see what it does but there is no guarantee that it will not change.

Mark

Hmmm. we seem to lack consensus. Holmes4: why do you say there will be no interrupt pending? what happens to external interrupts if no ISR has been attached?

I think there could be a pending interrupt if the interrupts happen quickly and if the ISR is itself slow.

It is probably easier to do what you want reliably by modifiying the relevant MCU registers directly rather than using the detachInterrupt() function. You would need to study the code that detachInterrupt() uses.

The registers are all clearly explained in the Atmel datasheets.

However if you use detachInterrupt() as the last call in the ISR it won't matter much what side-effects it has.

Of course, with a bit of test code you could probably have figured all this out before now. The Arduino is a great system for learning by doing.

...R

captnKrunch: Hmmm. we seem to lack consensus. Holmes4: why do you say there will be no interrupt pending? what happens to external interrupts if no ISR has been attached?

IMO the built-in handler will check for a valid (non-NULL) address of an user supplied handler. detachInterrupt() may or may not turn off the interrupt, depending on the library version.

AVRLibcReferenceManual/group_avr_interrupts.html ;)