Topics / Embedded C / Q4
What is an ISR and what are the rules for writing one?
Short answer: An Interrupt Service Routine (ISR, interrupt handler) is the function the CPU runs when a hardware interrupt or exception occurs. The rules: keep it short and fast, never block, clear the interrupt source, share data safely with the rest of the program, and do heavy processing elsewhere (main loop, RTOS task, bottom half).
The rules and the reasons
- Keep it short. While it runs, lower- or equal-priority interrupts wait, which adds latency to them. Read the data, clear the flag, put the data in a buffer, signal a task, return.
- Never block or wait. No
delay(), no busy-waiting for a peripheral that takes milliseconds, no waiting for a mutex (an ISR cannot sleep; in an RTOS it would deadlock or crash). - No
printf,mallocor other non-reentrant library calls. They may hold internal locks or static buffers that the interrupted code was using. - Clear the interrupt flag (in the peripheral and, where needed, in the interrupt controller). Otherwise the interrupt fires again immediately when the ISR returns. On Cortex-M with write buffers, make sure the clearing write has completed before returning (
__DSB()or a read-back), or the ISR can re-enter spuriously. - Share data safely:
volatilefor flags and indexes, lock-free single-producer/single-consumer ring buffers, or the RTOS's ISR-safe APIs (xQueueSendFromISR,xTaskNotifyFromISR). - Be careful with floating point: on Cortex-M4F/M7, FPU use in an ISR increases stacking (lazy stacking reduces the cost); some projects forbid FP in ISRs.
- No arguments and no return value (see the next question).
A typical UART receive ISR
#define RX_SIZE 128u /* power of two */
static volatile uint8_t rx_buf[RX_SIZE];
static volatile uint16_t rx_head; /* written only by the ISR */
static volatile uint16_t rx_tail; /* written only by the main loop */
void USART2_IRQHandler(void)
{
if (USART2->SR & USART_SR_RXNE) {
uint8_t b = (uint8_t)USART2->DR; /* reading DR clears RXNE */
uint16_t next = (rx_head + 1u) & (RX_SIZE - 1u);
if (next != rx_tail) { /* drop the byte if the buffer is full */
rx_buf[rx_head] = b;
rx_head = next;
}
}
}
Interview extras: mention priorities (urgent ISRs get higher priority), checking SR for error flags (overrun, framing), and the RTOS rule that ISRs above configMAX_SYSCALL_INTERRUPT_PRIORITY must not call any RTOS API.