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

Assembly: Subroutines and the Stack

Calling and returning.

A subroutine is a block of code reached with a call instruction. The CPU pushes the return address on the stack, runs the block, and a return instruction pops it back to continue.

The stack also saves registers that a routine reuses. Every push must be matched by a pop in reverse order, or the return goes to the wrong place and the program crashes.

Document which registers each routine changes.

EXAMPLE
; generic teaching syntax
main:   CALL  delay
        HALT

delay:  PUSH  R1          ; save the register
        LOAD  R1, 200
d1:     SUB   R1, 1
        JNZ   d1
        POP   R1          ; restore it
        RET