ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 65

Assembly: Writing an Interrupt Routine

Save everything you touch.

An interrupt can strike between any two instructions, so a handler must leave registers and flags exactly as it found them. Push whatever it changes at the start and pop it at the end.

It finishes with a special return instruction that restores the interrupted state. Keep the routine as short as possible and acknowledge the interrupt source if the hardware requires it.

Forgetting to restore the flags is a classic cause of strange, random bugs.

EXAMPLE
; generic teaching syntax
isr:    PUSH  R0
        PUSHF              ; save flags too
        LOAD  R0, flag
        ADD   R0, 1
        STORE flag, R0
        POPF
        POP   R0
        RETI               ; return from interrupt