8 subroutines (lcall, acall, ret) – Texas Instruments MSC1210 User Manual
Page 201
Subroutines (LCALL, ACALL, RET)
16-7
8052 Assembly Language
16.8 Subroutines (LCALL, ACALL, RET)
As in other languages, 8052 assembly language permits the use of subrou-
tines. A subroutine is a section of code that is called by a program, does a task,
and then returns to the instruction immediately following that of the instruction
that made the call.
LCALL and ACALL are both used to call a subroutine. LCALL requires three
bytes of program memory and can call any subroutine anywhere in memory.
ACALL requires two bytes of program memory and can only call a subroutine
within the same 2k block of program memory.
Both call instructions will save the current address on the stack and jump to
the specified address or label. The subroutine at that address will perform
whatever task it needs to and then return to the original instruction by execut-
ing the RET instruction.
For example, consider the following code:
LCALL SUBROUTINE1
;Call the SUBROUTINE1 subroutine
LCALL SUBROUTINE2
;Call the SUBROUTINE2 subroutine
.
.
.
SUBROUTINE1: {subroutine code}
;Insert subroutine code here
RET
;Return from subroutine
SUBROUTINE2: {subroutine code}
;Insert subroutine code here
RET
;Return from subroutine
The code starts by calling SUBROUTINE1. Execution transfers to
SUBROUTINE1 and executes whatever code is found there. When the MCU
hits the RET instruction, it automatically returns to the next instruction, which
is LCALL SUBROUTINE2. SUBROUTINE2 is then called, executes its code,
and returns to the main program when it reaches the RET instruction.
Note:
It is very important that all subroutines end with the RET instruction, and that
all subroutines exit themselves by executing the RET instruction. Unpredict-
able results will occur if a subroutine is called with LCALL or ACALL and a
corresponding RET is not executed.
Note:
Subroutines may call other subroutines. For example, in the code above
SUBROUTINE1 could include an instruction that calls SUBROUTINE2.
SUBROUTINE2 would then execute and return to SUBROUTINE1, which
would then return to the instruction that called it. However, keep in mind that
every LCALL or ACALL executed expands the stack by two bytes. If the stack
starts at internal RAM address 30
H
and 10 successive calls to subroutines
are made from within subroutines, the stack will expand by 20 bytes to 44
H
.