Page 165 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 165
142 Chapter 6 Assembly Language Subroutines
VI: DS 1 ; Allocate a byte of memory just for VI
V2 : DS 1 ; Allocate a byte of memory just for V2
Wl: D S 1 ; Allocate a byte of memory just for W1
W2: D S 1 ; Allocate a byte of memory just for W2
TERM: DS . W 1 ; Allocate two bytes of memory just for TERM
enter: MOVE #1, VI ; Allocate and initialize V( 1)
MOVE #2, V2 ; Allocate and initialize V(2)
MOVE #3, W1 ; Allocate and initialize W( 1)
MOVE #4, W2 ; Allocate and initialize W(2)
LDAA VI ; V(l) into A
LDAB Wl ;W(l)intoB
MUL ; The value of first term is now in D
STD TERM ; Store first term in TERM
LDAA V2 ; V(2) into A
LDAB W2 ; W(2) into B
MUL ; Calculate second term
ADDD TERM ; Add in TERM; dot product is now in D
Figure 6.5. Inner Product Utilizing Different Global Variables (a Bad Example)
Rather than storing a subroutine's local variables in global variables, put them in
either registers or the hardware stack. Figure 6.6 illustrates how registers can be used to
store local variables; this is basically what we did throughout the previous chapters.
Because the 6812 has few registers, the stack holds most local variables, which will be
called stacked local variables. We review relevant stack index addressing and stack-
oriented instructions presented in Chapters 2 and 3.
Recall from Chapter 3 that index addressing using the stack pointer can access data
in the stack and can push or pull data from the stack. We will use a general and simple
rule for balancing the stack so that the segment will be balanced. Push all the stacked
local variables of the segment on the stack at the entry point, and pull all of the local
variables off the stack at the exit point. Do not push or pull words from the stack
anywhere else in the program segment except for two- or three-line segments used to
implement missing instructions. While an experienced programmer can easily handle
exceptions to this rule, this rule is quite sound and general, so we recommend it to you.
In following sections, our program segments will be balanced unless otherwise noted and
we will usually follow this rule, only occasionally keeping local variables in registers.
LDAA #1 ; V(l) into A
LDX #3 ; V(2) into low byte of X
LDAB #2 ;W(l)intoB
LDY #4 ; W(2) into low byte of Y
MUL ; First term is now in D
EXG D, Y ; Store first term in Y, get W(2) in B
EXG A,X ;V(2)intoA
MUL ; Calculate second term
LEAY D, Y ; Add terms, to get result in Y
Figure 6.6. Inner Product Utilizing Registers