Chapter 3: Data Structures and Subroutine Calls

62
H. Huang Transparency No.3-1 The 68HC11 Microcontroller Chapter 3: Data Structures and Subroutine Calls The 68HC11 Microcontroller Han-Way Huang Minnesota State University, Mankato

description

Chapter 3: Data Structures and Subroutine Calls. The 68HC11 Microcontroller. Han-Way Huang. Minnesota State University, Mankato. Examples of Data Structures. 1. Strings . A sequence of characters. 2. Arrays . An ordered set of elements of the same type. - PowerPoint PPT Presentation

Transcript of Chapter 3: Data Structures and Subroutine Calls

Page 1: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-1

The 68HC11 Microcontroller

Chapter 3: Data Structures and Subroutine Calls

The 68HC11 Microcontroller

Han-Way Huang

Minnesota State University, Mankato

Page 2: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-2

The 68HC11 Microcontroller

Examples of Data Structures

1. Strings. A sequence of characters.2. Arrays. An ordered set of elements of the same type.3. Stacks. A data structure with a top and bottom. Elements can be added or removed

only at the top of the stack.4. Queues. A data structure to which elements can be added at only one end (called head)

and removed only from the other end (called tail).5. Dequeues. A data structure in which elements can be added and removed at both ends.6. Trees. A data structure in which one element is called the root and the remaining

elements are partitioned into m disjoint subtrees, each of which is itself a tree.7. Graphs. A data structure that consists of a set of nodes and a set of arcs (or edges).

Each arc in a graph is specified by a pair of nodes.8. Linked lists. A data structure that consists of linked nodes. Each node consists of two

fields, an information field and a next address field. The information field holdsthe actual element on the list, and the next address field contains the addressof the next node in the list.

Operations performed on data structures

- adding and deleting elements- traversing and searching a data structure- etc.

Page 3: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-3

The 68HC11 Microcontroller

The 68HC11 Stack

SPlow address

high address

top element

bottom

.

.

.

- A 16-bit stack pointer (SP) points to the location above the top byte of the stack.- The 68HC11 CPU registers can be pushed into the stack.- The top element (s) of the stack can be pulled into a CPU register.- The stack grows from high addresses toward lower addresses.

Push and Pull Instructions

- PSHA: Push A onto the stack- PSHB: Push B onto the stack- PSHX: Push X onto the stack (low order byte is pushed first)- PSHY: Push Y onto the stack (low order byte is pushed first)- PULA: Pull A from the stack- PULB: Pull B from the stack- PULX: Pull X from the stack (high order byte is pulled first)- PULY: Pull Y from the stack (high order byte is pulled first)

Page 4: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-4

The 68HC11 Microcontroller

Example 3.1 Suppose that [A] = $33, [B] = $20, [SP] = $00FF. What will be the contents of the top byte of the stack before and after the execution of PSHA? Whatwill be the contents of the top two bytes of the stack if PSHB is executed?Solution: The contents of the stack before and after the execution of PSHA and PSHB are:

XX

original stack

[SP] = $00FF

$33XX [SP] =

$00FE

XX

$20

$33

[SP] =$00FD

after PSHA after PSHB

Page 5: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-5

The 68HC11 Microcontroller

Instructions Related to the Stack Pointer (SP)

[<label>] DES [<comment>] decrements the contents of the stack pointer by 1[<label>] INS [<comment>] increments the contents of the stack pointer by 1[<label>] LDS <opr> [<comment>]

loads the contents of a memory location or an immediate value into SP[<label>] STS <opr> [<comment>]

stores the contents of the stack pointer in a memory location[<label>] TSX [<comment>] places the contents of SP plus one into X[<label>] TSY [<comment>] places the contents of SP plus one into Y[<label>] TXS [<comment>] places the contents of X minus one into SP[<label>] TYS [<comment>] places the contents of Y minus one into SP

Example 3.2 Write down an instruction sequence to load the top element of the stack intoA and the 9th element from the top of the stack into B.Solution:

TSX ; points the index register X to the top element of the stackLDAA 0,X ; places the top element of the stack in ALDAB 9,X ; places the 9th element from the top of the stack in B

Page 6: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-6

The 68HC11 Microcontroller

array[i] = key?

Indexable Data Structures

- Vectors and matrices are indexable data structures- A vector is one dimensional and a matrix is two dimensional- The first element of a vector is associated with index 0- Vectors and matrices can be defined by one or multiple FCB or FDB directives

Example 3.3 Write a program to search an array with N 16-bit elements that are storedstarting at $10 using the key stored at $00-$01 and save the address of the first matched element at $02-$03. Save the value $FFFF (-1) if no element matches the key.Solution:

start

i 0result $FFFF

i = N - 1?

Stop

i i + 1

yes

no

yes

result address of array[i]

Page 7: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-7

The 68HC11 Microcontroller

N equ 10 ; array countnotfound equ -1

org $00key FDB xxxx ; the key to be used for searchingresult RMB 2 ; memory locations to store the address

org $D000array FDB $20,$40,$202,$1,$200,$10,$22,$21,$300,$101

org $C000ldd #notfound ; store a -1 to result and result+1std result ; “ldd key ; get the keyldx #array ; get the starting address of the arrayldy #0 ; initialize the loop count

loop cpd 0,X ; compare with the keybeq found ; found it?inx ; increment the pointer by 2inx ; “iny ; increment the loop countcpy #N-1 ; check the loop countbne loopjmp stop

found stx result ; stop the searchstop end

Page 8: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-8

The 68HC11 Microcontroller

Matrices

- can be stored in row major order or column major order- a matrix element can be accessed by specifying its row and column numbers

The following matrix

mat =

1 2 3 4 5 6 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 25

in row major order

mat1 FCB 01, 02, 03, 04, 05FCB 06, 07, 08, 09, 10FCB 11, 12, 13, 14, 15 orFCB 16, 17, 18, 19, 20FCB 21, 22, 23, 24, 25

in column major order

mat2 FCB 01, 06, 11, 16, 21FCB 02, 07, 12, 17, 22FCB 03, 08, 13, 18, 23FCB 04, 09, 14, 19, 24FCB 05, 10, 15, 20, 25

can be stored

Page 9: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-9

The 68HC11 Microcontroller

Address Calculation for a N × M Matrix Elements

- row major order

address of mat1(i, j) = (i × M) + j + address of mat1(0,0)

* Suppose memory locations i and j hold the row and column indices * The following instruction sequence computes the address of mat1(i, j)

ldaa i ; place row index in Aldab #M ; place matrix dimension M in Bmul ; compute i × Maddb j ; compute i × M + jadca #0 ; “addd #mat1 ; compute i × M+ j + mat1(0,0)xgdx ; place the address in X

Page 10: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-10

The 68HC11 Microcontroller

- column major order

address of mat2(i, j) = (j × N) + i + address of mat2(0, 0)

* Suppose memory locations i and j hold the row and column indices * The following instruction sequence computes the address of mat2(i, j)

ldaa j ; place row index in Aldab #N ; place matrix dimension N in Bmul ; compute j × Naddb i ; compute j × N + iadca #0 ; “addd #mat2 ; compute j × N + i + mat2(0,0)xgdx ; place the address in X

Page 11: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-11

The 68HC11 Microcontroller

Example 3.4 Write a program to compute the sum of two 8 × 8 matrices. The startingaddresses of these two matrices are MA and MB and that the result matrix is MC. Thesematrices are stored in memory in row major order. Each element is one byte.Solution:

N equ $8 ; dimension of the matrixorg $00

MA fcb .... ; matrix MA is here....

MB fcb .... ; matrix MB is here....

MC rmb 64 ; matrix MC is herei rmb 1 ; row indexj rmb 1 ; column indexbuf rmb 1 ; buffer to hold elementdisp rmb 2 ; memory to hold the value of i × N + j

org $C000ldaa #N ; start from the last rowstaa i ; initialize the index i

out_lp dec ildab #N ; start from the last column toward the 0th columnstab j

Page 12: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-12

The 68HC11 Microcontroller

* The following 10 instructions fetch MA(i, j) and place it at bufin_lp dec j

ldaa i ; place row index in Aldab #N ; place N in Bmul ; compute N × iaddb j ; compute N × i + jadca #0 ; “std disp ; save the value of N × i + j addd #MA ; compute MA(0,0) + N × i + j xgdxldaa 0,Xstaa buf

* The following 4 instructions fetch MB(i, j) into Aldd dispaddd #MBxgdxldaa 0,X

adda buf ; compute MA(i, j) + MB(i, j)staa buf ; save the sum in buf

Page 13: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-13

The 68HC11 Microcontroller

* The following 3 instructions compute the address of MC(i, j) and leave it in Xldd dispaddd #MCxgdx ldaa buf ; get the sumstaa 0,X ; save the sum in MC(i,j)dec j ; decrement the column numberbeq in_lp ; not reach the end of a column yet?dec i ; decrement the row numberbeq out_lp ; is this the end of all computationend

Matrix Transpose

The transpose MT of a matrix M is defined as a matrix obtained by writing the rows of M as the columns of MT. MT can be obtained by swapping the (i, j)th element with the (j, i)th element for each i and j from 0 to N-1.

Example 3.4 Write a program to transpose an N × N matrix.

Page 14: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-14

The 68HC11 Microcontroller

A breakdown of matrix

a0,0 a0,1 a0,n-1

a1,0 a1,1

an-1,0 an-1,n-1an-1,n-2

an-2,n-1

upper right

lower left

- swap each element in the upper rightwith an element in the lower left

- row index i runs from 0 to n-2 for theupper right elements

- for row i column index j runs from i+1 to n-1

- diagonal elements need not be swapped

Page 15: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-15

The 68HC11 Microcontroller

Start

i = 0

j = i + 1

X = address of MAT(i, j)

Y = address of MAT(j,i)

A = MAT(i, j)B = MAT(j, i)

Store A in the memory location pointed to by YStore B in the memory location pointed to by X

j < N - 1?

j = j + 1

i < N - 2?

Stop

i = i + 1

yes

yes

no

no

Figure 3.6 Flowchart for matrix transposition

Page 16: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-16

The 68HC11 Microcontroller

Matrix Transpose Program

N equ 8 ; matrix dimensionilimit equ N-2 ; upper limit of index ijlimit equ N-1 ; upper limit of index j

org $00i rmb 1 ; row indexj rmb 1 ; column index

ORG $D000 ; starting address of the matrixmat FCB ..... ; matrix to be transposed

FCB .... ; “. ; “. ; “ORG $C000clr i ; initialize i to 0

row_loop ldaa iincastaa j ; initialize j to i + 1

* The following 7 instructions compute the address of mat(i,j)col_loop ldaa i

ldab #Nmuladdb jadca #0

Page 17: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-17

The 68HC11 Microcontroller

addd #matxgdx

* The following 7 instructions compute the address of mat(j,i) and leave address in Yldaa jldab #Nmuladdb iadca #0addd #matxgdy

* The following 4 instructions swap mat(i,j) with mat(j,i)ldaa 0,Xldab 0,Ystaa 0,Ystab 0,Xldab jinc j ; update index jcmpb #jlimit ; j = N - 1?bne col_loopldaa iinc i ; update index icmpa #ilimit ; i = N - 2?bne row_loopEND

Page 18: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-18

The 68HC11 Microcontroller

Strings

Example 3.6 Write a program to append a string to the end of another string.Solution: There are two steps in this program:Step 1Find the end of the first string.Step 2Copy string 1.

ORG $C000LDX #string2

again LDAA 0,XBEQ copyINXBRA again

copy LDY #string1copy_loop LDAA 0,Y

STAA 0,XBEQ doneINXINYBRA copy_loop

done NOPSWI

Page 19: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-19

The 68HC11 Microcontroller

…ORG $D000

string1 FCC “….”FCB 0

string2 FCC “….”FCB 0END

Example 3.7 Write a program to count the number of characters and words contained in a string.Solution: The first non-white-space character to the right of one or more spaces is the beginning of a new word. Parameters used in the program:

- char_cnt: character count- wd_cnt: word count- str_ptr: string pointer- curr_char: current character

Page 20: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-20

The 68HC11 Microcontroller

Figure 3.7 Flowchart forcharacter and word countprogram

char_cnt 0word_cnt 0str_ptr addr. of string_X

Start

curr_char [str_ptr]

str_ptr str_ptr + 1

curr_char = NULL?

curr_char = space, tab, LF, or CR?

Stopyes

no

word_cnt word_cnt + 1

curr_char [str_ptr]

str_ptr str_ptr + 1

curr_char = NULL?yes

no

Stop

curr_char = space, tab, LF, or CR?

noyes

no

yes

Figure 3.7 Flowchart for character count and word count program

skip whitespaces

reach a new word

skip theremainingcharacters ofthe word

char_cnt char_cnt + 1

char_cnt char_cnt + 1

Page 21: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-21

The 68HC11 Microcontroller

tab equ $09 ; ASCII code for horizontal tab charactersp equ $20 ; ASCII code for SPACECR equ $0D ; ASCII code for carriage returnLF equ $0A ; ASCII code for line feed

org $00char_cnt rmb 1wd_cnt rmb 1

ORG $D000string_X fcc “xxxxxxxxxxxxxxxx” ; the string to be processed

fcb 0 ; the NULL character to terminate the previous stringorg $C000ldx #string_Xclr char_cnt ; initialize the character count to 0clr wd_cnt ; initialize the word count to 0

string_lp ldab 0,X ; fetch the current characterbeq exit ; is this a NULL character?inx ; move to the next characterinc char_cnt

* The following 8 instructions skip the spaces between wordscmpb #spbeq string_lp ; skip the space charactercmpb #tabbeq string_lp ; skip the tab character

Page 22: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-22

The 68HC11 Microcontroller

cmpb #CRbeq string_lp ; skip the carriage return charactercmpb #LFbeq string_lp ; skip the line feed character

* A non-space character is the beginning of a new wordinc wd_cnt

wd_loop ldab 0,Xbeq exit ; null character is not included in character countinc char_cntinx ; move the character pointer

* The following 8 instructions check the end of a wordcmpb #spbeq string_lpcmpb #tabbeq string_lpcmpb #LFbeq string_lpcmpb #CRbeq string_lp

* A non-space character is part of a wordbra wd_loop

exit swiend

Page 23: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-23

The 68HC11 Microcontroller

Example 3.8 Write a program to search a certain word from a given string.Solution: The flowchart of the word search program is in Figure 3.8.

Start

Skip the white spaces to look forthe next word in the string

Is the current wordin the string equal to the word

to be searched?

Is this the end ofthe string?

Stop

yes

no

no

yes

Figure 3.8 Flowchart of the word search program

Page 24: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-24

The 68HC11 Microcontroller

tab equ $09 ; ASCII code for horizontal tabsp equ $20 ; ASCII code for SPACECR equ $0D ; ASCII code for carriage returnLF equ $0A ; ASCII code for line feedNULL equ $00 ; ASCII code for NULL

org $00search rmb 1 ; flag to indicate if the given word is in the stringstring_X fcc “xxxxxxxxxxxxxxxx” ; a string terminated by NULL

fcb 0word_X fcc “yyyyyyy”; a word terminated by NULL

fcb 0org $C000clr search ; initialize the search flag to 0ldx #string_X ; place the string address in X

loop ldab 0,Xinx

* The following 10 instructions skip the white spaces to search for the next word* in the string

tstbbeq done ; is this the end of the string?cmpb #sp ; is the current character a space?beq loop ; skip the spacecmpb #tab ; is the current character a tab?

Page 25: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-25

The 68HC11 Microcontroller

beq loop ; skip the tab charactercmpb #CR ; is this a carriage return?beq loop ; skip itcmpb #LF ; is this a line feed?beq loop ; skip it

* The occurrence of the first non-white character indicates the beginning of a word,* and the comparison should be started

ldy #word_X ; place the word address in Yldaa 0,Y ; place the current character of word_X in Ainy ; move the word pointer

next_ch cba ; compare the character in A and Bbne end_of_wd ; check the next wordcmpa #NULL ; is this the end of a word?beq matched ; if yes, the word is found in the stringldaa 0,Y ; get the next character in word_Xldab 0,X ; get the next character in string_Xinxinybra next_ch ; check the next pair of characters

* The following 10 instructions check to see if the end of the given word is reachedend_of_wd cmpa #NULL

bne next_wd ; if the not the end of the given word, then not matchedcmpb #CR

Page 26: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-26

The 68HC11 Microcontroller

beq matchedcmpb #LFbeq matchedcmpb #tabbeq matchedcmpb #spbeq matched

* The following twelve instructions skip the unmatched word in the stringnext_wd ldab 0,X ; get the next character in the string

beq done ; stop if this is the end of the stringinxcmpb #CRbeq jmp_loop ; the label loop is too far away to use a conditional branchcmpb #LFbeq jmp_loopcmpb #tabbeq jmp_loopcmpb #spbeq jmp_loopbra next_wd

jmp_loop jmp loopmatched ldab #1 ; set the search flag to 1

stab search ; “done swi ; return to monitor (buffalo)

Page 27: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-27

The 68HC11 Microcontroller

Subroutines

- A sequence of instructions that can be called from various places in the program- Allows the same operation to be performed with different parameters- Simplifies the design of a complex program by using the divide-and-conquer approach

Instructions related subroutine calls

[<label>] BSR <rel> [<comment>] ; branch to subroutine[<label>] JSR <opr> [<comment>] ; jump to subroutine[<label>] RTS [<comment>] ; return from subroutine

where<rel> is the offset to the subroutine<opr> is the address of the subroutine and is specified in the DIR, EXT, or INDexedaddressing mode.

Page 28: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-28

The 68HC11 Microcontroller

Main program

Subroutine 1 Subroutine 2 Subroutine 3

Subroutine 1.1 Subroutine 2.1 Subroutine 3.1

Subroutine 2.1.1 Subroutine 2.1.2

Figure 3.9 A structured program

Program Structure

Main program

Subroutine

<call> sub_x . . .

. . .<return>

sub_x:

Figure 3.10 Subroutine processing

Subroutine Processing

Page 29: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-29

The 68HC11 Microcontroller

Issues in Subroutine Calls

1. Parameter passing - use registers- use the stack- use global memory

2. Returning results- use registers- use the stack (caller created a hole in which the result will be placed)- use global memory

3. Local variables allocation- allocated by the callee- use as many DES instructions when no more than 5 bytes are needed- use the following instruction sequence to allocate more than 5 bytes.

TSXXGDXSUBD #N ; allocate N bytesXGDXTXS ; move the stack pointer up by N bytes

Page 30: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-30

The 68HC11 Microcontroller

Issues in Subroutine Calls (continued)

4. Local variables deallocation

- use as many INS instructions as needed when no more than 5 bytes are to bedeallocated

- use the following instruction sequence when more than 5 bytes are deallocated

TSXXGDXADDD #N ; deallocate N bytesXGDXTXS ; move down the stack pointer by N bytes

Stack Frame

The region in the stack that holds incoming parameters, the subroutine return address, local variables, and saved registers is referred to as stack frame.

Page 31: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-31

The 68HC11 Microcontroller

SPLow address

High address

Local variables

Saved registers

Previous frame pointer

Return address

Incoming parameters

Figure 3.12 A stack frame

Frame pointer

Local variables

SP

Saved registers

Return address

Incoming parameters

Y (or X)

Figure 3.13 Example of 68HC11 stack frame

Page 32: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-32

The 68HC11 Microcontroller

Example 3.9 Draw the stack frame for the following program segment when the 9thinstruction of the subroutine subx is executed.

ldaa #Npshaldx #matpshxbsr subx...

Subx:(1) pshb(2) psha(3) pshx(4) pshy(5) tsx(6) xgdx(7) subd #6(8) xgdx(9) txs

...

Solution:

6 bytes for local variables

SP

Y_H

Y_L

X_H

X_L

A

B

ret_addr_H

ret_addr_L

upper byte of return address

lower byte of return address

MAT_H

MAT_L

N

upper byte of Y

lower byte of Y

upper byte of X

lower byte of X

upper byte of MAT

lower byte of MAT

Figure 3.14 Stack frame for Example 3.9

Page 33: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-33

The 68HC11 Microcontroller

Example 3.10 Write a subroutine to compute the average of an array with N 8-bit elementsand an instruction sequence to call the subroutine. The array starts at ARRAY. Use registers to pass parameters and return the average in B.Solution:

The instruction sequence to call thissubroutine is:

LDX #ARRAYLDAA #NBSR average....

The subroutine saves array count A in the stackand also push a 0 into the stack so that 0 and N can be loaded into X when computing theaverage.

Using Registers to Pass Parameters

SP

ret_addr_H

ret_addr_L

N

Figure 3.15 Stack frame of example 3.10

0Y

Page 34: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-34

The 68HC11 Microcontroller

Start

N = 0?

N = 1?

i = 0sum = 0

sum = sum + array[i]

average = sum / N

Stop

i = N - 1?

average = array[0]

i = i + 1

yes

yes

no

no

no

yes

Figure 3.16 Logic flow for computing array average

Page 35: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-35

The 68HC11 Microcontroller

* The following subroutine computes the average of an array and returns it in Baverage psha ; save the array count

clrapsha ; clear the top byte of the stack to 0tsy ; Y points to the top byte of the stackldab 1,Y ; place the array count in Bcmpb #1 ; check the array countblo exit ; is the array empty?bhi do ; does the array have more than one element?ldab 0,X ; get the single element and returnbra exit ; “

do xgdy ; place N in Y and use Y as the loop countclra ; use D as the sum and initialize it to 0clrb ; “

again addb 0,X ; add an element to the sumadca #0 ; add the carry to the upper 8 bitsinx ; move the array pointerdey ; decrement the loopbne again ; is the end of the loop?tsy ; point Y to the top of the stackldx 0,Y ; place N in X

Page 36: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-36

The 68HC11 Microcontroller

idiv ; compute the average of the array xgdx ; exchange X and D so that D contains the quotient

* ; in which A contains 0 and B contains the quotientexit pula ; restore registers

pula ; “rts

Page 37: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-37

The 68HC11 Microcontroller

Example 3.11 Write a subroutine to find the largest element of an array and an instructionsequence to call this subroutine. The following parameters are passed to this subroutine in thestack:- array: the starting address of the given array- arcnt: the array count- amax: address of the memory location to hold the maximum element of the arraySolution:

The instruction sequence that calls this subroutine is:

ldx #arraypshxldaa #arcntpshaldx #armaxpshxbsr max ; call the subroutinetsx ; clean up the stackldab #5 ; “abx ; “txs ; “

Using the Stack to Pass Parameters

Page 38: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-38

The 68HC11 Microcontroller

Start

arcnt < 1?

arcnt = 1?

Return

Return array[0]

yes

yes

no

no

armax arr[0]i 1

armax >= arr[i]?

armax arr[i]

i = arcnt - 1?

Return armax

i i + 1

yes

no

no

yes

Figure 3.17 Logic flow of the array max subroutine

Page 39: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-39

The 68HC11 Microcontroller

A

ret_add_H

B

Y_H

Y_L

X_H

X_L

ret_add_L

armax_H

armax_L

arcnt

array_H

array_L

Y

SP

Y+11

Y+10

Y+8

Each slot of the stack is one byte.The suffix _H specifies the upper byte of a parameter.The suffix _L specifies the lower byte of a parameter.

Figure 3.18 Stack frame for the array max subroutine

Page 40: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-40

The 68HC11 Microcontroller

array equ 11 ; array base address offset from the top of the stackarcnt equ 10 ; array count offset from the top of the stackarmax equ 8 ; array max address offset from the top of the stack

max pshx ; save al registerspshy ; “pshb ; “psha ; “tsy ; point Y to the top of the stackldx array,Y ; load the base address into Xldab arcnt,Y ; load the array count into Bldaa 0,X ; assign the first element as the temporary array maxcmpb #1 ; check array countblo exit ; return if the array is emptybhi start ; look for the array max if the array count is larger than 1bra done ; the array has only one element

start inx ; set X to point to the second element of the arraydecb ; loop limit is arcnt - 1

again cmpa 0,X ; compare the next element with the array maxbge noswap ; should array max be updated?ldaa 0,X ; update the array max

noswap inx ; move to the next element

Page 41: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-41

The 68HC11 Microcontroller

decb ; decrement the loop countbne again ; is it done?

done ldx armax,Y ; get the address for the array maxstaa 0,X ; save the array max

exit pula ; restore registerspulb ; “puly ; “pulx ; “rts

Page 42: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-42

The 68HC11 Microcontroller

Example 3.12 Write a program to compute the greatest common divisor (gcd) of two 16-bit integers. The caller pushes these two integers onto the stack and this subroutine returns the gcd in double accumulator D.Solution: Let these two integers be n1 and n2. Assume n1 n2. If not, swap them.Algorithm:

Step 1 If n1 > n2 then swap n1 and n2.Step 2i = 2, gcd = 1.Step 3 If (n1 = 1) or (n2 = 1) return.Step 4If both n1 and n2 can be divided by i then gcd i.Step 5If i = n1 then stop. Otherwise, i i + 1. Go to step 4.

Page 43: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-43

The 68HC11 Microcontroller

Stack frame of gcd subroutine

SP

gcd

i

ret_addr

n1

n2

YY+2

Y+8

Y+10

Figure 3.19 Stack frame for gcd program

Y

Instruction sequence to call find_gcd

…LDX <operand n1>PSHXLDX <operand n2>PSHXJSR find_gcdINSINSINSINS…

Page 44: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-44

The 68HC11 Microcontroller

n1_dis EQU 8 ; offset of n1 from the top of the stackn2_dis EQU 10 ; offset of n2 from the top of the stackgcd_dis EQU 0 ; offset of gcd from the top of the stacki_dis EQU 2 ; offset of i from the top of the stack

Find_gcd PSHYTSYDESDESDESDESLDX #1STX gcd_dis,YLDD n2_dis,Y ; if n2 = 1 then gcd = 1CPD #1 ; “BEQ done ; “LDD n1_dis,Y ; if n1 = 1 then gcd = 1CPD #1 ; “BEQ done ; “CPD n2_dis,YBLS start ; if n1 is smaller then start to compute gcdLDX n2_dis,Y ; n1 is larger than n2, so swap them

Page 45: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-45

The 68HC11 Microcontroller

STD n2_dis,YSTX n1_dis,Y

start LDX #2 ; initialize i to 2STX i_dis,Y ; “

again LDD n1_dis,YIDIVCPD #0 ; can i divide n1?BNE next_i ; “LDD n2_dis,YLDX i_dis,Y ; can i divide n2?IDIV ; “CPD #0 ; “BNE next_iLDD i_dis,Y ; use current i asSTD gcd_dis,Y ; the temporary gcd

next_i LDX i_dis,Y ; have we done withCPX n1_dis,Y ; all the test yet?BEQ doneINXSTX i_dis,YJMP again

done INSINSINSINSRTS

Page 46: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-46

The 68HC11 Microcontroller

Example 3.13 Write a subroutine that can divide a 32-bit number into another 32-bit number.Solution: Use repeated subtraction method to implement the division. Assume we have thehardware shown in Figure 3.0.

R Q

P

C

ALUController

lsb

shift leftwrite R

msb

32-bit

32-bit32-bit

set

lsb

Figure 3.20 Hardware for 32-bit by 32-bit division

Page 47: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-47

The 68HC11 Microcontroller

Algorithm of Division Using Repeated Subtraction

Step 1Shift the register pair (R, Q) one bit to the left.Step 2Subtract register P from register R, put the result back to R if the difference is nonnegative.Step 3If the result in step 2 is negative, set the least significant bit of Q to 0. Otherwise, set it to 1.Step 4Repeat Step 1 to 4 for 31 times.

The caller allocates 8 bytes in the stack to hold the remainder and quotient. Both the dividend and the divisor are pushed into the stack. The subroutine allocates 13 bytes for local variables.The calling instruction sequence is

TSXXGDXSUBD #8XGDXTXSLDX divsor ; push divisor PSHX ; “LDX didend ; push dividendPSHX ; “JSR div32

Page 48: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-48

The 68HC11 Microcontroller

buf EQU 0 ; space used as a bufferR EQU 5 ; offset of register R from the top of the stackQ EQU 9 ; offset of register Q from the top of the stackdivisor EQU 21 ; offset of divisor from the top of the stackdividend EQU 25 ; offset of dividend from the top of the stacki EQU 4 ; offset of variable i from the top of the stacklocal EQU 13 ; number of bytes of local variables

div32 PSHAPSHBPSHXPSHYTSX ; allocate local variablesXGDX ; “SUBD #local ; “XGDX ; “TXS ; “TSY ; Y points the top byte of the stackLDD #0 ; initialize R to 0STD R,Y ; “STD R+2,Y ; “LDD dividend,Y ; transfer dividend to QSTD Q,Y ; “LDD dividend+2,Y ; “

Page 49: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-49

The 68HC11 Microcontroller

dividend

divisor

ret_addr

i

Q

R

SPY

Y+4

Y+9

Y+21

Y+25

Figure 3.21 Stack frame of 32-bit by 32-bit division subroutine

A

B

X

Y

buf

Y+5

quo

rem

Y+29

Y+33

Stack frame for the div32 subroutine

Page 50: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-50

The 68HC11 Microcontroller

STD Q+2,Y ; transfer dividend to QLDAA #32 ; initialize loop count to 32STAA i,Y ; “

loop LSL Q+3,Y ; shift register pair (R, Q) to the left one placeROL Q+2,Y ; “ROL Q+1,Y ; “ROL Q,Y ; “ROL R+3,Y ; “ROL R+2,Y ; “ROL R+1,Y ; “ROL R,Y ; “LDD R+2,Y ; subtract the divisor P from RSUBD divisor+2,Y ; “STD buf+2,Y ; “LDAA R+1,Y ; “SBCA divisor+1,Y ; “STAA buf+1,Y ; “LDAA R,Y ; “SBCA divisor,Y ; “BCS smaller ; is [R] – divisor < 0?STAA R,Y ; store the difference back to R when the difference is positiveLDD buf+2,Y ; “STD R+2,Y ; “

Page 51: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-51

The 68HC11 Microcontroller

LDAA buf+1,YSTAA R+1,YLDAA Q+3,YORAA #01 ; set the lsb of Q to 1STAA Q+3,Y ; “BRA looptest

smaller LDAA Q+3,Y ; set the lsb of Q to 0ANDA #$FE ; “STAA Q+3,Y ; “

looptest DEC i,YBNE loopLDD R,Y ; return the remainder in the hole in the stack STD rem,Y ; “LDD R+2,Y ; “STD rem+2,Y ; “LDD Q,Y ; return the quotient in the hole in the stackSTD quo,Y ; “LDD Q+2,Y ; “STD quo+2,Y ; “TSXXGDXADDD #local ; deallocate local variables

Page 52: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-52

The 68HC11 Microcontroller

XGDXTXSPULYPULXPULBPULARTS

Page 53: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-53

The 68HC11 Microcontroller

Example 3.14 Write a subroutine to sort an array of 8-bit numbers using the bubble sortmethod, and also write an instruction sequence to call the subroutine. The starting address ofthe array and is arr_base, and the array count is N. Use the stack to pass parameters to this routine.Solution: Up to N – 1 (labeled as 0th to (N – 2)th) iterations of comparisons and swaps are performed:

1. N - i – 1 comparisons are performed in iteration i.2. Set an in-order flag to 1 at the beginning of each iteration.3. Start from array element with index 0 to index N – i –2, compare each element with its

adjacent element and swap them if they are not in the right order (ascending or descending).4. Clear the in-order flag whenever a swap is made.5. Check the in-order flag at the end of each iteration. If the flag is 1, then stop. Otherwise,

continue.

Four local variables are used:

1. iteration: keeps track of the numbers of rounds remained to be performed2. inner: keeps track of the number of comparisons remained to be performed in a round3. in_order: indicates if the given array is already in sorted order4. buf: buffer for swapping elements

Page 54: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-54

The 68HC11 MicrocontrollerStart

iteration N - 1

in_order 1

inner iteration

yes

swap array[i] & array[i+1]

array[i] > array[i+1]?

in_order 0

inner inner - 1

inner = 0?

i 0

i i + 1

yes

no

no

in_order = 1?yes

no

iteration iteration - 1

iteration = 0?

Stop

no

yes

Figure 3.22 Logic flow of bubble sort

arr_base

N

ret_addr

B

A

Y

X

buf

in_order

inner

iteration

SP

Figure 3.23 Stack frame for bubble sort

Y

Y+1

Y+2

Y+3

Y+12

Y+13

Page 55: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-55

The 68HC11 Microcontroller

arr EQU 13 ; offset of array base from the top of the stackarcnt EQU 12 ; offset of array count from the top of the stackbuf EQU 3 ; offset of buf from the top of the stackin_order EQU 2inner EQU 1iteration EQU 0true EQU 1false EQU 0

bubble PSHBPSHAPSHYPSHXDES ; allocate space for local variablesDES ; “DES ; “DES ; “TSY ; set Y to point to the top byte of the stackLDAA arcnt,YDECA ; compute the number of iterations that need to be performedSTAA iteration,Y ; “

Page 56: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-56

The 68HC11 Microcontroller

ploop LDAA #true ; set in-order flag to trueSTAA in_order,Y ; “LDX arr,Y ; place the array base address in XLDAA iteration,YSTAA inner,Y ; initialize inner loop count

cloop LDAA 0,X ; get one elementCMPA 1,X ; compare it with the next elementBLE looptest

* the following 5 instructions swap the two adjacent elementsSTAA buf,YLDAA 1,XSTAA 0,XLDAA buf,YSTAA 1,XLDAA #false ; reset the in_order flagSTAA in_order,Y ; “

looptest INX ; move the array pointerDEC inner,YBNE cloopTST in_order,YBNE doneDEC iteration,YBNE ploop

Page 57: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-57

The 68HC11 Microcontroller

* the following four instructions deallocate space allocated to local variablesdone INS

INSINSINSPULXPULYPULAPULBRTS

Page 58: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-58

The 68HC11 Microcontroller

Buffalo Input and Output Routines

- The Buffalo monitor in EVB and CMD11A8 provides a set of I/O routines.- These I/O routines are located in the Buffalo ROM.- A jump table is implemented so that the user program can call these routines by

jumping to the desired entry.

Buffalo I/O Routines

UPCASE converts the character in accumulator A to uppercaseWCHK tests the character in A and returns with Z bit set if character is white space

(space, comma, tab)DECHK tests the character in A and return with Z bit set if character is delimiter

(carriage return or whitespace)INIT initializes I/O deviceINPUT reads I/O deviceOUTPUT writes I/O deviceOUTLHLF converts left nibble of A to ASCII and outputs to terminal portOUTRHLF converts right nibble of A to ASCII and outputs to terminal portOUTA outputs the ASCII character in AOUT1BYT converts the binary byte at the address in index register X to two ASCII

characters and outputs them; returns address in index register X pointingto next byte

Page 59: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-59

The 68HC11 Microcontroller

OUT1BSP converts the binary byte at the address in index register X to two ASCIIcharacters and outputs them followed by a space; returns address in index register X pointing to next byte

OUT2BSP converts two consecutive bytes starting at address in index register X tofour ASCII characters and outputs the characters followed by a space; returns address in index register X pointing to next byte

OUTCRLF outputs ASCII carriage return followed by a line feedOUTSTRG outputs a string of ASCII bytes pointed to by the address in index register X

until character is an end-of-transmission ($04)OUTSTRG0 same as OUTSTRG, except that leading carriage returns and line feeds are

skippedINCHAR inputs ASCII character to A and echoes back; this routine loops until

character is actually received

Page 60: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-60

The 68HC11 Microcontroller

Table 3.4 The EVB/EVBU I/O routine jump table

Address Instruction

$FFA0 JMP UPCASE$FFA3 JMP WCHEK$FFA6 JMP DCHEK$FFA9 JMP INIT$FFAC JMP INPUT$FFAF JMP OUTPUT$FFB2 JMP OUTLHLF$FFB5 JMP OUTRHLF$FFB8 JMP OUTA$FFBB JMP OUT1BYT$FFBE JMP OUT1BSP$FFC1 JMP OUT2BSP$FFC4 JMP OUTCRLF$FFC7 JMP OUTSTRG$FFCA JMP OUTSTRG0$FFCD JMP INCHAR

Page 61: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-61

The 68HC11 Microcontroller

Calling the EVB I/O Routines

Execute a JSR instruction to call an EVB I/O routine:

To output the character in accumulator A

JSR $FFB8

To output a string pointed by index register X

JSR $FFC7

A better approach is to use assembler directives to make the I/O routine call more readable:

outa equ $FFB8outstrg equ $FFC7

JSR outa...JSR outstrg

Page 62: Chapter 3: Data Structures and Subroutine Calls

H. Huang Transparency No.3-62

The 68HC11 Microcontroller

Example 3.16 Write a subroutine to input a string from the keyboard and save the string ina buffer pointed by X. The input string is terminated by the carriage-return character.Solution:

getchar EQU $FFCD ; use mnemonic to represent hex addressCR EQU $0DEOT EQU $04

get_string JSR getcharCMPA #CRBEQ doneSTAA 0,XINXBRA get_string

done LDAA #EOTSTAA 0,XRTS