Page 300 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 300
9.4 Loop Statements, Arrays, and S tracts 277
The initialization should branch to the loop termination, but because the compiler
determines that the first loop will satisfy the termination test, this step is skipped to
improve efficiency. The inner loop is almost identically constructed. Generally, the for
loop is fundamentally a while loop with a built-in initialization and a built-in stepping
operation that is executed after the statement governed by the for loop is executed and
before the while condition is tested. The general and natural for loop is the most
widely used looping mechanism in C and C++.
The more general for statement is used with instructions that access a two-
dimensional array using accumulator D index addressing. The program in Figure 9.11
adds all the elements of a global unsigned char two-dimensional array into a global
int variable. The two-dimensional array is declared as a[ 10 ] [ 3 ], so it is a ten-row,
three-column array. Elements in rows are stored in consecutively accessed locations, and
whole rows are stored in consecutive groups of these memory words (this is called row-
major order). The middle of the assembly-language code from Figure 9.12 is shown
below:
LDAB 1,SP ; get row index
CLRA
LDY #3 ; number of bytes per row
EMUL ; gets the relative location of row i in array a
TFR D,X
LDAB 0,SP
CLRA
LEAX D,X ; add column number
LDAB 2 0 4 8, X ; get element
It reads out element i, j, into accumulator D. Observe that the calculation of the
location of the i, j th element is obtained by multiplication and addition operations (a
polynomial expression).
The do while statement can produce efficient assembly-language code using C
code that may look somewhat awkward. Figure 9.12 illustrates an efficient way to clear a
vector. Note that the loop counter is decremented, and tested after it has been
decremented, in order to use the instruction DBNE. In order to use this loop counter as an
index into a vector, one is subtracted from the counter to make it the vector index. This
produces the tightest loop to clear a vector in the 6812.
char alpha[10];
void main() { char i = 5; do alpha[i - 1] = 0; while{—i); }
a. A C Program
00000959 8605 LDAA #5
0000095B B705 SEX A,X
0000095D 69E207FF CLR 2047,X
00000961 0430F7 DBNE A,*-6 ;abs = 095B
00000964 3D RTS
b. Assembly Language developed from Part (a)
Figure 9.12. Clearing a Vector with a Do While Loop