Texas Instruments MSC1210 User Manual
Page 223
Using the Stack (PUSH/POP)
16-29
8052 Assembly Language
The stack itself resides in internal RAM and is managed by the SP (stack point-
er) SFR. SP will always point to the internal RAM address from which the next
POP instruction should obtain the data.
-
POP will return the value of the internal RAM address pointed to by SP,
then decrement SP by 1.
-
PUSH will increment SP by 1, then store the value at the IRAM address
then pointed to by SP.
SP is initialized to 07
H
when an 8052 is first powered up. That means the stack
begins at 08
H
and grows from there. If PUSHing 16 values onto the stack, for
example, the stack occupies addresses 08
H
through 17
H
.
Using the stack can be both useful and powerful, but it can also be dangerous
when incorrectly used. Remember that the stack is also used by the 8052 to
remember the return addresses of subroutines and interrupts. If the stack is
modified incorrectly, it is very easy to cause the program to crash or to behave
in very unexpected ways.
When using the stack, all but advanced stack users should observe the follow-
ing recommendations:
1) When using the stack from within a subroutine or ISR, be sure there is one
POP instruction for every PUSH instruction. If the number of POPs and
PUSHes are not the same, the program will probably end up crashing.
2) When using PUSH, be sure to always POP that value off the stack—even
if not in a subroutine.
3) Be sure to not jump over the section of code that POPs a value off the
stack. A common error is to PUSH a value onto the stack and then execute
a conditional instruction that jumps over the instruction that POPs that val-
ue off. This results in an unbalanced stack and will probably end up crash-
ing the program. Remember, not only must there be a POP instruction for
every PUSH, but a POP instruction must be executed for every PUSH that
is executed. Make sure the program does not jump over the POP instruc-
tions.
4) Always make sure to use the RET instruction to return from subroutines
and RETI instruction to return from ISRs.
5) As a practice, only modify SP at the very beginning of the program in order
to initialize it. Once the stack is being used or subroutine calls are being
made, do not modify SP.
6) Make sure the stack has enough room. For example, the stack starts by
default at address 08
H
. If there is a variable at internal RAM address 20
H
,
then the stack has only 24 bytes available to it, from 08
H
through 1F
H
. If
the stack is 24 bytes long and another value is pushed onto the stack or
another subroutine is called, the variable at 20
H
will be overwritten.
Keep in mind, too, that the 8052 can only use internal RAM for its stack. Even
if there is 64k of external RAM, the 8052 can only use its 256 bytes of internal
RAM for the stack. That means the stack should be used very sparingly.