Page 99 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 99
76 Chapter 3 Addressing Modes
point in the program, the stack is balanced at that point if it is balanced in every possible
simple trace to that point. To balance the stack means to deallocate all the bytes that
have been allocated, so that it becomes balanced. We usually allocate space for variables
at the beginning of a subroutine and deallocate the space just before we exit the
subroutine to balance the stack, but we can have program segments that are not
subroutines in which space is allocated at the beginning of the program segment and
deallocated at the end of that program segment.
It is possible for a program to have a segment that has space allocated at its
beginning and deallocated at its end and to have within it another segment that has space
allocated at its beginning and deallocated at its end. This is called a nested allocated
segment. Figure 3.16a illustrates a program that has a nested segment where the outer
segment allocates three bytes, an inner segment allocates two bytes, and an inner
segment of it allocates another four bytes. The outer segment writes the number 5 in its
lowest addressed byte, the next inner segment reads this byte into accumulator A, and the
innermost segment reads this byte into accumulator B. Note that different offsets are used
with the stack pointer to access the same byte of data, due to intervening allocations, but
the outer data is available to each inner program segment, even though they are nested.
3.5 Examples
We now tie together some of the ideas that were introduced above using some examples.
These examples give you some experience with addressing modes and loops.
One of the most common operations is to clear a block of memory. The program
segment in Figure 3.17 clears 39 bytes starting at location $910.
This example can be sped up by using STD, where accumulator D is zero. A
similarly common operation is to move a block of data from one area to another. The
following program segment moves 15 bytes from a block starting at location $930 to a
block starting at location $921. The MOVW instruction can move data twice as fast.
We now extend an example started in Chapter 1. Suppose that we want to add N 1-
byte numbers that are stored consecutively beginning in location $843. The value of N is
stored in location $841, and the result is to be placed in location $842. The program
segment in Figure 3.19 does this for either unsigned or signed (two's-complement)
numbers. If the numbers are unsigned, the result will be correct as long as there is no
unsigned overflow, that is, the sum can be expressed with an 8-bit unsigned number. If
the numbers are signed, the result will likewise be correct as long as there is no signed
Figure 3.17. Program Segment to Clear a Block of Memory