Topics / Embedded C / Q5
Can you pass parameters to or return a value from an ISR?
Short answer: No. The hardware calls the ISR asynchronously, at an arbitrary point in the program, so there is no caller to supply arguments or to receive a return value. ISRs are declared void handler(void). Data goes in and out through shared variables, buffers, queues or RTOS objects.
Why it is impossible
- The CPU jumps to the address in the vector table when the interrupt occurs; it does not set up argument registers.
- The interrupted code did not call the ISR and does not expect any result.
- On Cortex-M, the exception entry pushes
r0–r3,r12,lr,pc,xPSRautomatically and loadsLRwith anEXC_RETURNvalue; the ISR returning normally restores everything. Any value left inr0is discarded.
How to get data in and out
| Direction | Mechanism |
|---|---|
| ISR → main/tasks | volatile flags, ring buffers, RTOS queues/notifications/semaphores given "FromISR" |
| Main → ISR (configuration) | volatile variables set before enabling the interrupt |
| Context for a shared handler | a static table indexed by peripheral instance, e.g. uart_ctx[instance] |
Exceptions to know
- SVC (supervisor call) handlers do receive "arguments": the caller's
r0–r3are in the stacked exception frame, and the handler can read them (and write a return value into the stackedr0). RTOS kernels and secure-call gateways use this. - HardFault handlers commonly read the stacked frame to find the faulting PC; they get the stack pointer through a small assembly wrapper.
- On some other architectures (e.g. AVR with
ISR()macros, or theinterruptkeyword on older compilers), the compiler generates special prologue/epilogue code; still no parameters.
Linux contrast: a Linux interrupt handler is registered with request_irq() and does receive arguments (int irq, void *dev_id) and returns IRQ_HANDLED/IRQ_NONE, because the kernel's generic interrupt code calls it like a normal function.