Page 171 - Programming Microcontrollers in C
P. 171
156 Chapter 4 Small 8-Bit Systems
be used to access memory and will not be available for other
microcontroller features. (Pin usage, bus expansion, and pin multi
plexing will be discussed in later sections.) The important
consideration at this point is that the limited program memory area
usually associated with a microcontroller should not cause serious
concern. If the program grows to exceed the available size of onboard
memory for a microcontroller family, it is always possible to get a
larger microcontroller that can handle any additional memory re
quirements. The programming goal, though, is usually to confine the
program in the smallest possible program memory space so that the
least expensive microcontroller will do the job.
Using Microcontroller Memory
In our discussion on variables in Chapter 1, it was shown that C
treats all automatic variables as local to the block in which they are
declared. The scope of these variables is the block where they are
declared. Since these variables exist only in the block where they are
declared, the memory locations dedicated to the storage of these vari
ables can be freed when the variables go out of scope. These rules
create an ideal situation for storage on the program stack. Memory
space is easily created on the stack at the beginning of a block, and it
is equally easily destroyed at the close of the block. This operation is
exactly what is needed, but it cannot be used in a typical small
microcontroller. Most microcontrollers have very limited RAM, and
the stack arrangement in them is completely different from that you
will find on a large computer. On the M68HC05 family of parts, for
example, the chip has a hardware stack and no stack pointer into
memory that the compiler writer can access. Therefore, it is imprac
tical to even attempt to use the system stack to store local variables.
The hardware stack on these chips is used only for storage of the
processor status when an interrupt occurs or to store the return ad
dress from a jump to a subroutine. The stack pointer is set to its
initial value on microcontroller reset, and the occurrence of an inter
rupt or a jump to subroutine instruction are the only ways that the
stack pointer can be changed.
In the larger machines, the stack pointer is set to a value that
points to a memory location. This pointer will be automatically
incremented and decremented by the equivalent of stack push or pull