chapter 4: advanced assembly...

76
The HCS12/MC9S12 Microcontroller Chapter 4: Advanced Assembly Programming The HCS12 Microcontroller Han-Way Huang Minnesota State University, Mankato September 2009 H. Huang Transparency No.41 Copyright © 2010 Delmar Cengage Learning

Upload: dinhkhanh

Post on 28-Sep-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Chapter 4: Advanced Assembly Programming

The HCS12 Microcontroller

Han-Way Huang

Minnesota State University, Mankato

September 2009

H. Huang Transparency No.4‐1Copyright © 2010 Delmar Cengage Learning

Page 2: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Chapter SummeryChapter Summery

The same sequence of instructions often need to be executedin several places of the program.in several places of the program.The subroutine mechanism enables the programmer to group thecommon instruction sequence into a subroutine.A subroutine can be called from many places.The processor saves the return address in the stack during a subroutine call.The subroutine restores the return address from the stack before itreturns to the caller.The subroutine can receive parameters from the caller to perform operations and may return result to the caller.Top do n design ith hierarchical refinement i th t ff tiTop-down design with hierarchical refinement is the most effectiveand popular software development methodology.

H. Huang Transparency No.4‐2Copyright © 2010 Delmar Cengage Learning

Page 3: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Introduction- Program = data structures + algorithm- Data structures to be discussed

1. stacks: a last-in-first-out data structure2. arrays: a set of elements of the same type3. strings: a sequence of characters terminated by a special character

Stack

Top elementLow address SP

B tt l tHi h dd Bottom elementHigh address

Figure 4.1 Diagram of the HCS12 stack

H. Huang Transparency No.4‐3Copyright © 2010 Delmar Cengage Learning

Page 4: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

HCS12 Support for the Stack Data StructureHCS12 Support for the Stack Data Structure

- A 16-bit stack pointer (SP)

- Instructions and addressing mode

Table 4.1 HCS12 push and pull instructions and their equivalent load and store instructions

Mnemonic Function Equivalent instruction

pshapshbpshcpshdpshx

h

push A into the stackpush B into the stackpush CCR into the stackpush D into stackpush X into the stack

h Y i t th t k

staa 1, -SPstab 1, -SPnonestd 2, -SPstx 2, -SPsty 2 SPpshy

pulapulbpulcpuldpulx

l

push Y into the stackpull A from the stackpull B from the stackpull CCR from the stackpull D from the stackpull X from the stack

ll Y f th t k

sty 2, -SPldaa 1, SP+ldab 1, SP+noneldd 2, SP+ldx 2, SP+ldy 2 SP+puly pull Y from the stack ldy 2, SP+

H. Huang Transparency No.4‐4Copyright © 2010 Delmar Cengage Learning

Page 5: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Example 4 1 Derive the stack contents after the execution of the following instructionExample 4.1 Derive the stack contents after the execution of the following instructionSequence:

lds #$15C0ldaa #$20pshapshaldab #40pshbldx #0pshxpshx

Solution:

SP (= $14FC)0

0

$28

$20

Figure 4.2 The contents of the HCS 12 stackFigure 4.2 The contents of the HCS 12 stack

H. Huang Transparency No.4‐5Copyright © 2010 Delmar Cengage Learning

Page 6: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

What is a Subroutine?What is a Subroutine?A sequence of instructions that can be called from many places of the programThe program flow during a subroutine call is shown in Figure 4.3.Saving and restoring return address is the key for the subroutine mechanism t kto work.

.

.

.

<call> subroutine _x

caller

.

.

.

.

.subroutine _x

Figure 4.3 Program flow during a subroutine call

.

<return >

H. Huang Transparency No.4‐6Copyright © 2010 Delmar Cengage Learning

Page 7: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Instructions that Support Subroutine Callppbsr <sub>: branch subroutine<sub> is specified in relative addressing mode and is in the rangeof -128 to +127 bytes from the instruction immediately after thebsr <sub> instruction The return address is pushed into the stackbsr <sub> instruction. The return address is pushed into the stack.jsr <sub>: jump subroutine<sub> is specified in direct, extended, indexed, and indexed indirectmode. The subroutine being called can be within the range of 64 kB.The return address is pushed into the stack.call <sub>: call subroutineThe <sub> field specifies the page number and the address of the subroutine within the page to be called The page number is to besubroutine within the page to be called. The page number is to be loaded into the PPAGE register.rts: return from subroutinerestrieve the return address from the stack and return to the caller.

f llrtc: return from callThis instruction retrieve the page number and the return address fromthe stack.

H. Huang Transparency No.4‐7Copyright © 2010 Delmar Cengage Learning

Page 8: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Example 4.2 Write a subroutine that converts a 16-bit binary number into a BCD ASCIIp ystring. The 16-bit number is passed in D and the pointer to the buffer to hold the stringis passed in Y.Solution:Let num, ptr, quo, and rem represent the number to be converted pointer, quotient, and remainder. The procedure is as follows:Step 1Push a 0 into the stack. quo ← num.Step 2rem ← quo % 10; quo ← quo / 10.Step 3Push the sum of $30 and rem into the stack.Step 4If (quo == 0) goto Step 5; else goto step 2.Step 5Pull a byte from stack and save it in the location pointed to by ptr.Step 6ptr ← ptr + 1.Step 7If the byte pulled in Step 5 is NULL, stop; else goto Step 5.

H. Huang Transparency No.4‐8Copyright © 2010 Delmar Cengage Learning

Page 9: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

bin2dec h X i t kbin2dec pshx ; save X in stackmovb #0,1,-SP ; push NULL character into stack

divloop ldx #10 ; divide the number by 10idiv ; “addb #$30 ; con ert the remainder to ASCII codeaddb #$30 ; convert the remainder to ASCII codepshb ; push it into the stackxgdx ; swap quotient to Dcpd #0 ; if quotient is 0, then prepare to pull outbeq revloop ; the decimal digit charactersbeq revloop ; the decimal digit charactersbra divloop ; quotient is not 0, continue to perform divide-by-10

revloop pula ; start to reverse the string from stackstaa 1,y+ ; save ASCII string in the buffercmpa #0 ; reach the NULL pushed previously?cmpa #0 ; reach the NULL pushed previously?beq done ; if yes, then donebra revloop ; continue to pup

done pulx ; restore the index register Xrtsrts

H. Huang Transparency No.4‐9Copyright © 2010 Delmar Cengage Learning

Page 10: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Issues related to Subroutine CallsIssues related to Subroutine Calls

1. Parameter Passing• Use CPU registersg• Use stack• Use global memory

2 Result Returning2. Result Returning• Use CPU registers• Use stack• Use global memory

3. Local Variable Allocation• Allocated in the stack• Use the instruction leas -n,SP to allocate n bytes of space in stack• Use the instruction leas n, SP to deallocate n bytes from stack

H. Huang Transparency No.4‐10Copyright © 2010 Delmar Cengage Learning

Page 11: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Saving CPU Registers in Stackg gThe subroutine may use some CPU registers that were used by its caller.The subroutine must save these registers in order to make sure the caller programcan obtain correct resultThe subroutine must restore the saved registers before returning to the caller.g gThe order of register restoration must be reversed to that to which registers aresaved.

if the saving order isg

pshxpshypshdp

then the restoring order is

puldppulypulx

H. Huang Transparency No.4‐11Copyright © 2010 Delmar Cengage Learning

Page 12: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Stack FrameStack 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.

- The stack frame is also called activation record.

Local variables

SP

Saved registers

Return address

Incoming parametersIncoming parameters

Figure 4.9 Structure of the 68HC12 stack frame

H. Huang Transparency No.4‐12Copyright © 2010 Delmar Cengage Learning

Page 13: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Example 4 3 Draw the stack frame for the following program segment after theExample 4.3 Draw the stack frame for the following program segment after the leas –10,sp instruction is executed:

ldd #$1234pshdpshdldx #$4000pshxjsr sub_xyz 10 bytes for local

variables

SP

…sub_xyz pshd

pshxpshyleas -10 sp $1234

$4000

[Y]

variables

leas 10,sp…

Solution: The stack frame is shown Figure 4.10.

$1234

$4000

$1234

return address

Figure 4.5 Stack frame of Example 4.3

H. Huang Transparency No.4‐13Copyright © 2010 Delmar Cengage Learning

Page 14: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Subroutines with Local Variables

Example 4.4 Write a subroutine that can convert a BCD ASCII string to a binary number and leave the result in double accumulator D. The ASCII string represents a number in the range of -215 ~ 215 – 1. A pointer to the string is passed to this subroutine in X. Solution:The subroutine will return an error indication using the CY flag of the CCR register.Let in_ptr, sign, error, and number represent the pointer to the BCD string, sign flag, error flag, and the number represented by the BCD string.The algorithm is:Step 1sign ← 0; error ← 0; number ← 0.Step 2If the character pointed to by in_ptr is the NULL character, then go to step 4.else if the character is not a BCD digit, then:

error ← 1;go to step 4;

elsenumber ← number × 10 + m[in_ptr] - $30;in_ptr ← in_ptr + 1;go to step 3;

H. Huang Transparency No.4‐14Copyright © 2010 Delmar Cengage Learning

Page 15: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

St 4Step 4If sign = 1 and error = 0, then

number ¬ two’s complement of number;else

tstop;

This subroutine allows local variables in the stack and its stack is shown in Figure 4.6.

valpdVal

dummy1

24

SPPresent digit value

The binary value of the BCD string

Ret_addrYerr

signval4

5

The binary value of the BCD stringSign of the number

Error flag

Figure 4.6 Stack frame of Example 4.4

H. Huang Transparency No.4‐15Copyright © 2010 Delmar Cengage Learning

Page 16: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

#include "c:\miniide\hcs12.inc"minus equ $2D ; ASCII code of minus signdummy equ 0 ; offset of dummy to hold a 0pdVal equ 1 ; offset of present digit value from SP in stackval equ 2 ; offset of the 2-byte binary value of the BCD string q y y g

; from SP in stack sign equ 4 ; offset of the sign from SP in stackerr equ 5 ; offset of error flag from SP in stacklocVar equ 6q

org $1000StrBuf dc.b "-9889",0 ; input ASCII to be convertedresult ds.w 1

org $1500start lds #$1500

ldx #StrBufjsr bcd2binstd resultswi

; -----------------------------------------------------------------------------------------------------------; This subroutine converts a BCD string into its equivalent binary value and also uses the; CY flag to indicate error condition. The CY flag is set to 1 to indicate error.

H. Huang Transparency No.4‐16Copyright © 2010 Delmar Cengage Learning

; ------------------------------------------------------------------------------------------------------------

Page 17: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

bcd2bin pshyleas -locVar,SP ; allocate 4 bytes for local variablesmovw #0,val,SP ; initialize accumulated value to 0movb #0,dummy,SPmovb #0,sign,SP ; initialize sign to positivemovb #0,err,SP ; clear error flag initiallyldaa 0,x ; check the first charactercmpa #minus ; is the first character a minus sign?bne GEZero ; branch if not minusmovb #1,sign,SP ; set the sign to 1inx ; move the pointer

GEZero ldab 1,x+ ; is the current character a NULL character?lbeq done ; yes, we reach the end of the string

b $ i h h bcmpb #$30 ; is the character not between 0 to 9?blo inErr ; "cmpb #$39 ; "bhi inErr ; "

bb #$30 h C di i lsubb #$30 ; convert to the BCD digit valuestab pdVal,SP ; save the current digit valueldd val,SP ; get the accumulated valueldy #10

l f 16 bi b 16 bi l i li i

H. Huang Transparency No.4‐17Copyright © 2010 Delmar Cengage Learning

emul ; perform 16-bit by 16-bit multiplication

Page 18: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

addd dummy,SP ; add the current digit valuestd val SP ; save the sumstd val,SP ; save the sumbra GEZero

inErr movb #1,err,SP ; set the error flag to indicate errorbra chkout

done ldaa sign SP ; check to see if the original number is negativedone ldaa sign,SP ; check to see if the original number is negativebeq chkoutldd #$FFFF ; convert to two's complement format subd val,SP ; if the number is negativeaddd #1 ; "addd #1 ; " std val,SP ; "

chkout ldaa err,SP ; check the error flagbeq clrErr ; go to clear CY flag before returnsec ; clear the C flagsec ; clear the C flagbra dealloc

clrErr clc ; set the C flagdealloc ldd val,SP

leas locVar SP ; deallocate local variablesleas locVar,SP ; deallocate local variablespuly ; restore Yrts

; org $FFFE ; uncomment these two lines for CodeWarrior; dc w start ; “

H. Huang Transparency No.4‐18Copyright © 2010 Delmar Cengage Learning

; dc.w start ; end

Page 19: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Bubble SortSorting is useful for improving the searching speed when an array or a file needs to be searched many times.Bubble sort is a simple but inefficient sorting method.

Example 4.13 Write a subroutine to implement the bubble sort algorithm and a sequence of instructions for testing the subroutine. Solution: The algorithm of bubble sort is shown in Figure 4.7.The bubble sort subroutine uses the following local variables:

Buf: a buffer for swapping elementsInOrder: a flag indicating whether the array is in orderInner: no of comparisons remained to be performed in the current iterationIteration: number of iterations remained to be performed

H. Huang Transparency No.4‐19Copyright © 2010 Delmar Cengage Learning

Page 20: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

S tart

ite ration ⎯ N - 1

in _orde r ⎯ 1inne r ⎯ ite ration

i ⎯ 0

yes

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

sw ap array [i] & array [i+ 1 ]in _orde r ⎯ 0

n o

inner ⎯ inne r - 1i ⎯ i + 1

inner = 0 ?

y es

n o

in _o rder = 1 ?y es

n on o

ite ration = 0 ?n o

ye s

I te ration ⎯ ite ratio n - 1

H. Huang Transparency No.4‐20Copyright © 2010 Delmar Cengage Learning

S top

F ig ure 4 .7 L og ic flo w of bubble sort

Page 21: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

S f SStack Frame for bubble Sort

bufinOrderinner

iteration SP

SP+1

SP+2SP+3

t ddBAYX

bufSP+3

Figure 4.8 Stack frame for bubble sort

arrayXN

return addressSP+12SP+13

H. Huang Transparency No.4‐21Copyright © 2010 Delmar Cengage Learning

Page 22: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

arr equ 13 ; distance of the variable arrayX from stack toparcnt equ 12 ; distance of the variable arcnt from stack topbuf equ 3 ; distance of local variable buf from stack topinOrder equ 2 ; distance of local variable inOrder from stack topinner equ 1 ; distance of local variable inner from stack topi i di f l l i bl i i f kiteration equ 0 ; distance of local variable iteration from stack toptrue equ 1false equ 0n equ 30 ; array countl l 4 b f b d b l l i bllocal equ 4 ; number of bytes used by local variables

org $1000 ; test dataarrayX dc.b 3,29,10,98,54,9,100,104,200,92,87,48,27,22,71

dc.b 1,62,67,83,89,101,190,187,167,134,121,20,31,34,54$1500org $1500

start lds #$1500 ; initialize stack pointerldx #arrayXpshxld #ldaa #npshajsr bubbleleas 3,sp ; deallocate space used by outgoing parametersb $ hi i i d C d W i

H. Huang Transparency No.4‐22Copyright © 2010 Delmar Cengage Learning

; bra $ ; uncomment this instruction under CodeWarriorswi ; break to D-Bug12 monitor

Page 23: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

bubble pshdhpshy

pshxleas -local,sp ; allocate space for local variablesldaa arcnt,sp ; compute the number of iterations to be performedd "deca ; "staa iteration,sp; "

ploop ldaa #true ; set array inOrder flag to true before any iterationstaa inOrder,sp ; "ld i d i t X th i tldx arr,sp ; use index register X as the array pointerldaa iteration,sp; initialize inner loop count for each iterationstaa inner,sp ; "

cloop ldaa 0,x ; compare two adjacent elements1 "cmpa 1,x ; "

bls looptst; the following five instructions swap the two adjacent elements

staa buf,sp ; swap two adjacent elementsld 1 "ldaa 1,x ; "staa 0,x ; "ldaa buf,sp ; "staa 1,x ; "ldaa #false ; reset the inOrder flag

H. Huang Transparency No.4‐23Copyright © 2010 Delmar Cengage Learning

ldaa #false ; reset the inOrder flagstaa inOrder,sp ; "

Page 24: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

looptst inxd idec inner,sp bne clooptst inOrder,sp ; test array inOrder flag after each iterationbne doned it tidec iteration,spbne ploop

; the following instruction deallocates local variablesdone leas local,sp ; de-allocate local variables

lpulxpulypuldrts

$FFFE t thi li f C d W i; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

H. Huang Transparency No.4‐24Copyright © 2010 Delmar Cengage Learning

Page 25: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Binary Search Subroutiney S SDivide the array into three parts: upper half, middle element, andlower half.Let min, man, mean be the minimum, maximum, and middle indicesof the subarray to be searchedof the subarray to be searched.The algorithm of binary search is as follows:

Step 1min < 0; max = n 1;min <- 0; max = n – 1;Step 2If (max < min), stop.Step 3Mean < (min + max)/2Mean <- (min + max)/2Step 4If (key == arr[mean]), then key is found and exit.Step 5If (key < arr[mean]) then set max to mean 1 and go to Step 2If (key < arr[mean]), then set max to mean – 1 and go to Step 2.Step 6if (key < arr[mean]), then set min to mean + 1 and go to Step 2.

H. Huang Transparency No.4‐25Copyright © 2010 Delmar Cengage Learning

Page 26: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

mean SP

key

ret_addressB

X

max

min SP+1

SP+2

SP+8

arrBase

arrCnt

key SP+8SP+9

SP+10

Figure 4.9 Stack frame for binary search

n equ 30 ; array countsrch equ 69 ; key to be searchedmean equ 0 ; stack offset for local variable meanmin equ 1 ; stack offset for local variable minmin equ 1 ; stack offset for local variable minmax equ 2 ; stack offset for local variable maxkey equ 8 ; stack offset for local variable keyarrCnt equ 9 ; stack offset for local variable arrCntarrBas equ 10 ; stack offset for local variable arrBasarrBas equ 10 ; stack offset for local variable arrBaslocvar equ 3 ; number of bytes for local variables

org $1000result ds.b 1 ; search result

H. Huang Transparency No.4‐26Copyright © 2010 Delmar Cengage Learning

Page 27: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

org $1500lds #$1500movw #arr,2,-SP ; pass array base addressmovb #n,1,-SP ; pass array countmovb #srch,1,-SP ; pass key for searchjsr binsearchleas 4,SP ; de-allocate space used in passing parametersstaa result

; bra $ ; uncomment this instruction for CodeWarriorswi

binSearch pshx ; save X in the stackpshb ; save B in the stackleas -locVar,SP ; allocate space for locVar variablesmovb #0,min,SP ; initialize min to 0ldaa arrCnt,SP ; initialize max to arCnt - 1deca ; "staa max,SP ; "ldx arrBas,SP ; use X as the pointer to the array

loop ldab min,SP ; is search over yet?cmpb max,SP ; "

H. Huang Transparency No.4‐27Copyright © 2010 Delmar Cengage Learning

lbhi notfound ; if min > max, then not found (unsigned comparison)

Page 28: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

addb max,SP ; compute meanlsrb ; "stab mean,SP ; save meanldaa b,x ; get a copy of the element arr[mean]cmpa key,SP ; compare key with array[mean]beq found ; found it?bhi searchLO ; continue to search in lower halfldaa mean,SP ; prepare to search in upper halfinca ; "staa min,SP ; "bra loop

searchLO ldaa mean,SP ; set up indices range for searching in the deca ; lower halfstaa max,SP ; "bra loop

found ldaa #1bra exit

notfound ldaa #0exit leas locVar,SP

pulbpulx

H. Huang Transparency No.4‐28Copyright © 2010 Delmar Cengage Learning

rts

Page 29: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

arr db 1,3,6,9,11,20,30,45,48,60db 61,63,64,65,67,69,72,74,76,79db 80,83,85,88,90,110,113,114,120,123

; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

Subroutine that perform 32-bit division

R register Q register

set lsbshift left

32-bit 32-bitC

msb lsb

ALU

shift leftwrite R

Controller

P register

32 bit

H. Huang Transparency No.4‐29Copyright © 2010 Delmar Cengage Learning

32-bit

Figure 4.10 Conceptual hardware for implementing the repeated subtraction method

Page 30: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Algorithm for Multi-byte DivisionStep 1icnt n; R 0; Q dividend; P divisor.Step 2Shift the register pair (R, Q) one bit to the left.Step 3Subtract P from R, put the result back to R if the result is nonnegative.Step 4If the result of Step 2 is negative, then set the lsb of Q to 0. Otherwise, set the lsb to 1.Step 5icnt icnt – 1.Step 6If (icnt == 0) then stop; else go to Step 2

Example 4.7 Write a subroutine to implement the division algorithm using the repeatedsubtraction method for a 32-bit unsigned dividend and divisor. The caller of the subroutine allocate space in the stack for this subroutine to return the quotient and remainder and then push the dividend and divisor into the stack before calling thissubroutine.

H. Huang Transparency No.4‐30Copyright © 2010 Delmar Cengage Learning

Page 31: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

i

bufSP

SP+4

[x]

[y]

Q

R

iSP+4

SP+5

SP+9

dividend

divisor

return address

[D]

[ ]

SP+21

SP+25

remainder

quotientSP+29

SP+33

Figure 4.11 Stack frame for Example 4.7

b f eq 0 ; distance of b f from the top of the stackbuf equ 0 ; distance of buf from the top of the stacki equ 4 ; distance of i from the top of the stackR equ 5 ; distance of R from the top of the stackQ equ 9 ; distance of Q from the top of the stackdivisor equ 21 ; distance of divisor from the top of the stackdivisor equ 21 ; distance of divisor from the top of the stackdividend equ 25 ; distance of dividend from the top of the stackquo equ 29 ; distance of quo from the top of the stackrem equ 33 ; distance of rem from the top of the stacklocVar equ 13 ; number of bytes for local variables

H. Huang Transparency No.4‐31Copyright © 2010 Delmar Cengage Learning

locVar equ 13 ; number of bytes for local variables

Page 32: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

dvdendHI equ $42 ; dividend to be testeddvdendLO equ $4c15 ; "dvsorHI equ $0 ; divisor to be testeddvsorLO equ $64 ; "

org $1000quotient ds.b 4 ; memory locations to hold the quoremain ds.b 4 ; memory locations to hold the remainder

org $1500 ; starting address of the programstart lds #$1500 ; initialize stack pointer

leas -8,SP ; make a hole of 8 bytes to hold the resultldd #dvdendLOpshdldd #dvdendHIpshdldd #dvsorLOpshdldd #dvsorHIpshdjsr div32 ; call the divide subroutineleas 8,SP ; de-allocate space used by dividend & divisormovw 2,sp+,quotient ; pull upper half of quotient

H. Huang Transparency No.4‐32Copyright © 2010 Delmar Cengage Learning

movw 2,sp+,quotient+2 ; pull lower half of quotient

Page 33: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

movw 2,sp+, quotient ; pull upper half of the quotient from the stackmovw 2 sp+ quotient+2 ; pull lower half of the quotient from the stackmovw 2,sp+, quotient+2 ; pull lower half of the quotient from the stackbra $

div32 pshdpshxpshypshyleas -locVar,sp ; allocate space for local variablesldd #0std R,sp ; initialize R to 0std R+2 sp ; “std R+2,sp ;ldd dividend,sp ; place dividend in register Qstd Q,spldd dividend+2,spstd Q+2 spstd Q+2,spmovb #32,i,sp ; initialize loop count

dloop lsl Q+3,sp ; shift (R,Q) to the left by 1 bitrol Q+2,sp ; “rol Q+1 sp ; “rol Q+1,sp ;rol Q,sp ; “rol R+3,sp ; “rol R+2,sp ; “rol R+1 sp ; “

H. Huang Transparency No.4‐33Copyright © 2010 Delmar Cengage Learning

rol R+1,sp ;rol R,sp ; “

Page 34: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

ldd R+2,spsubd divisor+2,spstd buf+2,spldaa R+1,spsbca divisor+1,spstaa buf+1,spldaa R,spsbca divisor,spbcs smaller

; the following six instructions store the difference back to R registerstaa R,spldaa buf+1,spstaa R+1,spldd buf+2,spstd R+2,spbset Q+3,sp,$01 ; set the least significant bit of Q register to 1bra looptest

smaller bclr Q+3,sp,$01 ; set the least significant bit of Q register to 0looptest dec i,sp

lbne loop; the following four instructions copy the remainder into the hole in the stack

H. Huang Transparency No.4‐34Copyright © 2010 Delmar Cengage Learning

ldd R,spstd rem,sp

Page 35: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

ldd R+2,spstd rem+2,sp

; the following four instructions copy the quotient into the hole in the stackldd Q,spstd quo,spldd Q+2,spstd quo+2,spleas locVar,sp ; deallocate local variablespulypulxpuldrts

; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

H. Huang Transparency No.4‐35Copyright © 2010 Delmar Cengage Learning

Page 36: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Finding the Square Rootg qThe successive approximation method can be used to find the square root of an integer.

Step 1sar 0; mask $8000; lpcnt 16; temp 0.sa 0; as $8000; pc 6; e p 0.Step 2temp sar OR maskStep 3If ((temp * temp) ≤ num) (( p p) )

sar ← temp;Step 4mask mask >> 1 (shift right one bit)Step 5plpcnt lpcnt – 1Step 6If (lpcnt == 0) then stop; else go to Step 2.

Example 4.8 Write a subroutine that implements the successive approximation methodto find the square root of a 32-bit integer.

H. Huang Transparency No.4‐36Copyright © 2010 Delmar Cengage Learning

Page 37: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

sar

SP

SP+2mask

y

lpcnt

sar

tem p SP+4

SP+6

x

SP+13

q_lo

return address

q_hi

SP+15

Figure 4.13 Stack frame of Exam ple 4.8

#include "c:\miniide\hcs12.inc"mask equ 0 ; stack offset of the variable mask from SP

2 k ff f h i bl f Ssar equ 2 ; stack offset of the variable sar from SPtemp equ 4 ; stack offset of the variable temp from SPlpcnt equ 6 ; stack offset of one-byte loop count from SPq_hi equ 13 ; stack offset of the upper and lower halves of the

l 15 b Q fi d h f SPq_lo equ 15 ; number Q we want to find the square root from SPlocVar equ 7testHi equ $00 ; upper half of the test number (q)testLo equ $7BC4 ; lower half of the test number (q)

$1000

H. Huang Transparency No.4‐37Copyright © 2010 Delmar Cengage Learning

org $1000sqroot ds.w 1 ; square root

Page 38: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

org $1500start lds #$1500

movw #testLo,2,-SP ; push testHi into stackmovw #testHi,2,-SP ; push testLo into stackjsr findsqrstd sqroot ; save the returned square rootleas 4,SP ; de-allocate the space used in passing parameters

; bra $ ; uncomment this line for CodeWarriorswi

; ------------------------------------------------------------------------------------------------------findsqr pshx

pshyleas -locVar,SP ; allocate space for local variablesmovw #0,sar,SP ; initialize SAR to 0movw #$8000,mask,SP ; initialize mask to $8000movb #16,lpcnt,SP ; initialize loop count to 16

iloop ldd mask,SP ; get the maskoraa sar,SP ; set a bit in SAR to 1orab sar+1,SP ; "std temp,SP ; save a copy of your guesstfr D,Y ; compute sar * sar

H. Huang Transparency No.4‐38Copyright © 2010 Delmar Cengage Learning

emul ; "

Page 39: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

cpy q_hi,SP ; is our guess correct?bhi nextb ; "cpd q_lo,SP ; "bhi nextb ; "ldd temp,SP ; yes, our guess is correct std sar,SP ; so, transfer temp to SAR

nextb lsr mask,SP ; shift mask to the right one placeror mask+1,SP ; "dec lpcnt,SPbne iloopldd sar,SP ; put sar in D as the approximated square rootleas locVar,SP ; de-allocate local variablespulypulxrts

; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

The square root computed using this method tends to be smaller than the actual squareroot and hence may not be the closet approximation and the user should compare (sar + 1)

H. Huang Transparency No.4‐39Copyright © 2010 Delmar Cengage Learning

and sar to find the closest approximation.

Page 40: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Subroutine for Prime TestinggThe most efficient method for testing whether an integer is a prime is to divide the given number by all the prime numbers from 2 to the square root of the given number.Since the prime numbers from 2 to the square root of the given number are not available, we can test divide the given number by all the numbers from 2 to its square, g y qroot.

Example 4.9 Write a subroutine that can test whether an unsigned integer is a prime number.Solution:test_hi equ $0638 ; number to be tested for primetest_lo equ $F227 ; "

org $1000gisprime ds.b 1

org $1500start lds #$1500 ; set up stack pointer

movw #test lo,2,-SP ; push the lower half of the test number_ , , ; pmovw #test_hi,2,-SP ; push the upper half of the test numberjsr PrimeTeststaa isprime

; bra $ ; uncomment this line for CodeWarrior

H. Huang Transparency No.4‐40Copyright © 2010 Delmar Cengage Learning

; ;swi

Page 41: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

ii equ 0 ; stack offset from SP of loop indextli it 2 t k ff t f SP f t t li ittlimit equ 2 ; stack offset from SP of test limitpNumHi equ 10 ; stack offset from SP of upper half of test numberpNumLo equ 12 ; stack offset from SP of lower half of test numberpLocal equ 4 ; number of bytes used by local variables

i T t hprimeTest pshxpshyleas -pLocal,SP ; allocate space for local variablesldaa pNumLo+1,SP ; check if the number is even (if bit 0 is 0)

d #$01 "anda #$01 ; "beq nonPRI ; "ldd pNumHi,SPcpd #0b t tPR h lf th t l t tbne testPR ; upper half nonzero, then enter normal testldd pNumLo,SP ; if upper half is 0, then test lower halfcpd #0 ; is lower half equal to 0?beq nonPri ; 0 is not a primecpd #1 ; is lo er half eq al to 1cpd #1 ; is lower half equal to 1beq nonPri ; 1 is not a prime

testPR ldd pNumLo,SP ; find the square root of Numldx pNumHi,SP ; “pshd ; “

H. Huang Transparency No.4‐41Copyright © 2010 Delmar Cengage Learning

pshd ; “pshx ; “

Page 42: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

jsr findsqr ; “l 4 SP d ll t f i tleas 4,SP ; de-allocate space for passing parametersstd tlimit,SP ; save returned value as the prime test limitmovw #2,ii,SP ; initialize test divide number to 3

divLoop ldd ii,SPd tli it SP h t t di id d ll b t tli it?cpd tlimit,SP ; has test divided all numbers up to tlimit?

bhi isPRI ; the number is primeldd pNumLo,SP; divide Num by iildx pNumHi,SP ; “ld ii SP “ldy ii,SP ; “leas -8,SP ; “pshd ; “ (push pNumLo)pshx ; “ (push pNumHi)

h “ ( h ii)pshy ; “ (push ii)movw #0,2,-SP ; “ (push 0 to the stack)jsr div32 ; “ (call the divide subroutine)leas 14,SP ; de-allocate the space used by outgoing parametersp ld ; get the lo er t o b tes of the remainderpuld ; get the lower two bytes of the remaindercpd #0 ; is remainder equal to 0?beq nonPRI ; If remainder equals 0, then Num is not a primeldd ii,SP ; test divide the next higher integeraddd #1 ; “

H. Huang Transparency No.4‐42Copyright © 2010 Delmar Cengage Learning

addd #1 ; “std ii,SP ; “

Page 43: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

bra divLoopisPRI ldaa #1

bra exitPTnonPRI ldaa #0exitPT leas pLocal,SP

pulypulxrts#include "c:\miniide\findsqr.asm"#include "c:\miniide\div32.asm"

; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

H. Huang Transparency No.4‐43Copyright © 2010 Delmar Cengage Learning

Page 44: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Using the D-Bug12 Functions to Perform I/O OperationsUsing the D Bug12 Functions to Perform I/O Operations

Table 4.2 D-Bug12 monitor (version 4.x.x) routines

Subroutine Functionpointer ddaddress

far main ( )getchar ( )putchar ( )printf ( )far GetCmdLine ( )

Start of D -Bug12Get a character from SCI 0 or SCI1Send a character out to SCI 0 or SCI1Formatted string output -translates binary values to stringGet a line of input from the user

$EE80$EE84$EE86$EE88$EE8Afar GetCmdLine ( )

far sscanhex ( )isxdigit ( )toupper ( )isalpha ( )strlen ( )

Get a line of input from the userConvert ASCII hex string to a binary integerCheck if a character (in B) is a hex digitConvert lowercase characters to uppercase Check if a character is alphabeticReturns the length of a NULL -terminated string

$EE8A$EE8E$EE92$EE94$EE96$EE98( )

strcpy ( )far out 2hex ( )far out 4hex ( )SetUserVector ( )far WriteEEByte ( )f E EE ( )

g gCopy a NULL-terminated stringOutput 8-bit number as two ASCII hex charactersOutput a 16-bit number as four ASCII hex charactersSet up a vector to a user 's interrupt service routineWrite a byte to the on -chip EEPROM memoryB lk th hi EEPROM

$$EE9A$EE9C$EEA0$EEA4$EEA6$EEAAfar EraseEE ( )

far ReadMem ( )far WriteMem ( )

Bulk erase the on -chip EEPROM memoryRead data from the HCS 12 memory mapWrite data to the HCS 12 memory map

$EEAA$EEAE$EEB2

H. Huang Transparency No.4‐44Copyright © 2010 Delmar Cengage Learning

Page 45: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

- All functions listed in Table 4 2 are written in C languageAll functions listed in Table 4.2 are written in C language.

- The first parameter to the function is passed in accumulator D. The remaining parameters are pushed onto the stack in the reverse order they are listed in the function declaration.

- Parameters of type char will occupy the lower order byte of a word pushed onto the stack.

- Parameters pushed onto the stack before the function is called remain on the stack h h f i i h ibili f h ll dwhen the function returns. It is the responsibility of the caller to remove passed

parameters from the stack.

- All 8- and 16-bit values are returned in accumulator D. A returned value of type char is returned in accumulator B.returned in accumulator B.

int getchar (void)Pointer address: $EE84Pointer address: $EE84Returned value: 8-bit character in accumulator B

H. Huang Transparency No.4‐45Copyright © 2010 Delmar Cengage Learning

Page 46: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Adding the following instruction sequence will read a character from SCI0 port:

getchar equ $EE84…jsr [getchar,PCR]

int putchar(int)Pointer address: $EE86Incoming parameter: character to be output in accumulator B

d l h h h (i )Returned vale: the character that was sent (in B)

- This function outputs a character to serial communication port SCI0.- The character to be output should be placed in accumulator B.

h f ll i i i ill h h A i l SC 0 h- The following instruction sequence will output the character A to serial port SCI0 whenthe program is running on the Dragon12 demo board.

putchar equ $EE86…ldab #$41 ; place the ASCII code of A in accumulator Bjsr [putchar,PCR]…

H. Huang Transparency No.4‐46Copyright © 2010 Delmar Cengage Learning

Page 47: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

int printf(char *format,…)p ( , )Pointer address: $EE88Incoming parameters: zero or more integer data to be output on the stack, D contains the

address of the format string. The format string must be terminated with a zero.

Returned value: number of characters printed in D.

- This function is used to convert, format, and print its argument as standard output under the control of the format string pointed to by format.g p y f

- All except floating-point data types are supported.- The format string contains two basic types of objects:

1. ASCII characters which will be copied directly to the display device.p y p y2. Conversion specifications. Each conversion specification begins with a percent sign

(%).3. Optional formatting characters may appear between the percent sign and ends with a

single conversion character in the following order:g g

[-][<FieldWidth>][.][<Precision>][h | l]

H. Huang Transparency No.4‐47Copyright © 2010 Delmar Cengage Learning

Page 48: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Table 4 3 Optional formatting characters

The Meaning of Optional Characters

Table 4.3 Optional formatting characters

Character Description

‐(minus sign)FieldWidth

Left justifies the converted argument.Integer number that specifies the minimum field width for the converted

. (period)Precision

arguemnt. The argument will be displayed in a field at least this wide . The displayed argument will be padded on the left or right if necessary.Separates the field width from the precision.Integer number that specifies the maximum number of characters to di l f i h i i b f di i f i

hl(letter ell)

display from a string or the minimum number of digits for an intger. To have an integer displayed as a short .To have an integer displayed as a long .

H. Huang Transparency No.4‐48Copyright © 2010 Delmar Cengage Learning

Page 49: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Formatting Characters Supported by the printf() function:

Table 4.4 Prin tf() conversion characters

d, i

character A rgument type; d isplayed as

int; signed decimal number

g pp y p f() f

oxXucs

int; unsigned octal number (w ithout a leading zero)int; unsigned hex number using abcdef for 10...15int; unsigned hex number using A BCD EF for 10...15int; unsigned decimal numberint; single characterchar *; display from the string until a '\0 ' (N U LL)s

p%

char *; d isplay from the string until a '\0 ' (N U LL)void *; pointer ( implementation-dependent representation)no argument is converted; print a %

E l f t tti (Fli ht i l ti )Example for outputting a message (Flight simulation):CR equ $0DLF equ $0Aprintf equ $EE88

…ldd #promptjsr [printf,PCR]

H. Huang Transparency No.4‐49Copyright © 2010 Delmar Cengage Learning

…prompt db “Flight simulation”,CR,LF,0

Page 50: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Example for outputting three numbers m, n, and gcd along with a message:

CR equ $0DLF equ $0Aprintf equ $F686

…ldd gcdpshdldd npshdldd mpshdldd #promptjsr [printf,PCR]leas 6,sp…

prompt db “The greatest common divisor of %d and %d is %d”,CR,LF,0

H. Huang Transparency No.4‐50Copyright © 2010 Delmar Cengage Learning

Page 51: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

int far GetCmdLine(char *CmdLineStr int CmdLineLen)int far GetCmdLine(char CmdLineStr, int CmdLineLen)Pointer address: $EE8AIncoming parameters: a pointer to the buffer where the input string is to be stored and

the maximum number of characters that will be accepted by this functionfunction.

- This function is used to obtain a line of input from the user.- The reception of an ASCII carriage return ($0D) terminates the reception of characters

from the userfrom the user.- The caller of this function normally would output a message so that the user knows to

enter a message. The example in the next page illustrates this interaction.

H. Huang Transparency No.4‐51Copyright © 2010 Delmar Cengage Learning

Page 52: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

printf equ $EE88printf equ $EE88GetCmdLine equ $EE8Acmdlinelen equ 100CR equ $0DLF equ $0ALF equ $0A

…prompt db “Please enter a string: “,CR,LF,0

…inbuf ds b 100inbuf ds.b 100

…ldd #prompt ; output a prompt to remind the user to jsr [printf,PCR] ; enter a stringldd #cmdlinelen ; push the CmdLineLenldd #cmdlinelen ; push the CmdLineLen pshd ; “ldd #inbufcall [GetCmdLine,PCR] ; read a string from the keyboardpuld ; clean up the stackpuld ; clean up the stack

H. Huang Transparency No.4‐52Copyright © 2010 Delmar Cengage Learning

Page 53: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Example 4 15 Write a program that invokes appropriate functions to find the prime numberExample 4.15 Write a program that invokes appropriate functions to find the prime number between 1000 and 2000. Output eight prime numbers in one line. To do this, you will need to

1.-- write a subroutine to test if an integer is a prime.2 invoke the printf() function to output the prime number2.-- invoke the printf() function to output the prime number.3.-- write a loop to test all the integers between 1000 and 2000.

Solution: The logic structure of the program is

Step 1Output the message “The prime numbers between 1000 and 2000 are as follows:”.Step 2For every number between 100 and 1000 doFor every number between 100 and 1000 do

1. - call the test_prime() function to see if it is a prime.2. - output the number (call printf()) if it is a prime.3 - if there are already eight prime numbers in the current line then also output a carriage3. - if there are already eight prime numbers in the current line, then also output a carriage

return.

H. Huang Transparency No.4‐53Copyright © 2010 Delmar Cengage Learning

Page 54: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

The algorithm of the test_prime()St 1Step 1Let num, i, and isprime represent the number to be tested, the loop index, and the flag to indicate if num is prime. Step 2i i 0isprime ← 0;Step 3For i = 2 to num/2 do

if num % i = 0 thentreturn;

isprime ← 1;return;

Th St k f f th f ti t t i ()The Stack frame of the function test_prime ():SP

prime_flag

ilimit

iSP + 2

SP + 4

num

return address

[X]

SP + 9

H. Huang Transparency No.4‐54Copyright © 2010 Delmar Cengage Learning

Figure 4.18 Stack frame for the prime test subroutine

Page 55: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

CR equ $0DLF equ $0Aupper equ 2000 ; upper limit for testing primelower equ 1000 ; lower limit for testing primeprintf equ $EE88 ; location where the address of printf() is stored

org $1000out_buf ds.b 10PRIcnt ds.b 1 ; prime number countk ds.b 2tmp ds.b 2

org $1500start ldx #upper

stx tmppshxldx #lowerstx k ; initialize k to 1000 for prime testingpshxldd #form0jsr [printf,PCR]leas 4,spclr PRIcnt

H. Huang Transparency No.4‐55Copyright © 2010 Delmar Cengage Learning

again ldd kcpd #upper

Page 56: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

bhi Pstop ; stop when k is greater than upperpshdldd #0pshdjsr primetest ; test if k is primeleas 4,sp ; de-allocate space used by outgoing parameterststabeq next_k ; test next integer if k is not primeinc PRIcnt ; increment the prime countldd kpshdldd #form1jsr [printf,PCR] ; output kleas 2,spldaa PRIcntcmpa #8 ; are there eight prime numbers in the current line?blo next_k

; output a CR, LF if there are already eight prime numbers in the current lineldd #form2jsr [printf,PCR]clr PRIcnt

H. Huang Transparency No.4‐56Copyright © 2010 Delmar Cengage Learning

next_k ldx k

Page 57: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

inxstx klbra again

; Pstop bra $ ; uncomment this line for CodeWarriorPstop swi ; comment this line for CodeWarrior

#include "c:\miniide\primetest.asm"#include "c:\miniide\div32.asm"#include "c:\miniide\findsqr.asm"

form0 db CR,LF,"The prime numbers between %d and %d are as follows: "db CR,LF,CR,LF,0

form1 db " %d ",0form2 db " ",CR,LF,0; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

H. Huang Transparency No.4‐57Copyright © 2010 Delmar Cengage Learning

Page 58: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Program Execution Result

>g 1500The prime numbers between 1000 and 2000 are as follows: 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093 10971051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 1291 1297 1301 1303 1307 1319 1321 1327 1361 1367 1373 1381 1399 1409 14231327 1361 1367 1373 1381 1399 1409 1423 1427 1429 1433 1439 1447 1451 1453 1459 1471 1481 1483 1487 1489 1493 1499 1511 1523 1531 1543 1549 1553 1559 1567 1571 1579 1583 1597 1601 1607 1609 1613 1619 1621 1627 1637 1657 1663 1667 1669 1693 1697 1699 1709 1721 1723 1733 1741 1747 1753 1759 1777 1783 1787 1789 1801 1811 1823 1831 1847 1861 1867 1871 1873 1877 1879 1889 1901 1907 1913 1931 1933 19491879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987 1993 1997 1999 User Bkpt Encountered

PP PC SP X Y D = A:B CCR = SXHI NZVC30 1560 1500 07D1 15DE 07:D1 1001 0000xx:1560 34 PSHX

H. Huang Transparency No.4‐58Copyright © 2010 Delmar Cengage Learning

>

Page 59: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Subroutines for Creating Time Delaysg yExample 4.11 Write a subroutine that can create a time delay of 100 ms.Solution:Delay100mspshx

ldx #60000 ; 2 E cyclesiloop psha ; 2 E cycles

pula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cycles

l 3 lpula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclesp ; ynop ; 1 E cyclenop ; 1 E cycledbne x,ilooppulxrts

H. Huang Transparency No.4‐59Copyright © 2010 Delmar Cengage Learning

rts

Page 60: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

The previous subroutine can be modified to create a time delay that is a multiple of100 ms as follows (the multiple is passed in Y):

delayby100ms pshxeloop3 ldx #60000 ; 2 E cyclesil 3 h 2 E liloop3 psha ; 2 E cycles

pula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclesp ypula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclesnop ; 1 E cyclenop ; 1 E cycledbne x,iloop3 ; 3 E cyclesdbne y,eloop3 ; 3 E cyclespulx

H. Huang Transparency No.4‐60Copyright © 2010 Delmar Cengage Learning

pulxrts

Page 61: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Introduction to Parallel I/O Port and Simple I/O DevicespA HCS12 device may have from 48 to 144 pins arranged in 3 to 12 I/O Ports.An I/O port consists of a set of I/O pins and the registers required to control its operation.An I/O pin can be configured for input or output.An I/O pin usually serves multiple functions. When it is not used as a peripheral function,/O p usua y se ves u p e u c o s. W e s o used as a pe p e a u c o ,it can be used as a general-purpose I/O pin.

Addressing the I/O Port Data RegisterWhen inputting or outputting data from or to an I/O port, the user read from or write top g p g p ,the port data register.Each I/O port register is assigned to an address in the HCS12 memory space. For example,Port A data register is assigned to address 0, the next instruction output $35 to Port A:

movb #$35,0 ; address 0 is Port A data register

A name is also assigned to each register so that we can access a register by referring toits name:

PTA equ 0movb #$35,PTA ; output $35 to Port A

The name and address association is established by including the HCS12.inc file to your

H. Huang Transparency No.4‐61Copyright © 2010 Delmar Cengage Learning

y g yprogram using the “#include c:\...\hcs12.inc” statement.

Page 62: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Configuring I/O Pin Directiong gEach I/O port has a data direction register DDRx (x is the port name) that configuresthe direction of each pin.By setting a bit of the DDRx register to 1, the corresponding I/O pin is configured foroutput.ou pu .By setting a bit of the DDRx register to 0, the corresponding I/O pin is configured forinput.

movb #$FF,DDRB ; configure Port A for output$ , ; g pmovb #0,DDRB ; configure Port B for inputmovb #$AA,DDRB ; configured Port A odd pins for output,

even pins for input

Input and Output Operationsmovb #$FF,DDRB ; configure Port B for outputstaa PTB ; output the contents of A to port Bmovb #$67,PTB ; output the value $67 to Port B$ , ; p $

movb #0,DDRC ; configure Port C for inputmovb PTC,ibuf ; read the contents of Port C and save it at the memory

; location represented by ibuf

H. Huang Transparency No.4‐62Copyright © 2010 Delmar Cengage Learning

; p y

Page 63: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

The HCS12 I/O ports and Pin Names

Table 4.5 Num ber of pins available in each paralle port

Port Nam e No. of Pins Pin Nam e

AB

88

PA7~PA0PB7~PB0B

EHJKMP

8884788

PB7 PB0PE7~PE0PH7~PH0PJ7~PJ0PK4~PK0

PM7~PM0PP7~PP0P

ST

PAD1, PAD0LUV

888

16888

PP7 PP0PS3~PS0PT7~PT0

PAD15~PAD0PL7~PL0PU7~PU0PV7~PV0V

W88

PV7 PV0PW7~PW0

H. Huang Transparency No.4‐63Copyright © 2010 Delmar Cengage Learning

Page 64: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Interfacing with LEDsgAn LED has an anode and cathode terminal.The anode terminal must at a voltage at least 1.6 V above that of the cathodeterminal (forward biased) in order for the LED to be lighted. The forward current required to light an LED is from a few to more than 10 mA.e o wa d cu e equ ed o g a s o a ew o o e a 0 .The I/O pin can drive an LED using one of the circuits shown in Figure 4.15. The resistors R1, R2, are R3 are called current-limiting resistors.

V VCC

Port pin

R1

R2

VCC

Port pin

74HC04

Figure 4.15 An LED connected to a CMOS inverter through a current -limiting resistor .

(a) Positive direct drive (c) Buffered drive

R3pin

Port pin(b) Inverse direct drive

H. Huang Transparency No.4‐64Copyright © 2010 Delmar Cengage Learning

Page 65: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

LED Circuit in the Draong12-Plus Demo Board

H C S12

PB7

PB6

1.5 KΩ

PB3

PB5

PB4

PB 2

PB 1

PB 0

Figure 4 .16 C ircuit connection for Exam ple 4 .12

PJ1

Example 4.12 Write a program to drive the LEDs shown in Figure 4.16 so that one LED islighted at a time from top to bottom and then from bottom to top with each LED lighted for about 200 ms.

H. Huang Transparency No.4‐65Copyright © 2010 Delmar Cengage Learning

Page 66: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

#include "C:\miniide\hcs12.inc"org $1000

lpcnt ds.b 1org $1500

start movb #$FF,DDRB ; configure port B for outputbset DDRJ,$02 ; configure PJ1 pin for outputbclr PTJ,$02 ; enable LEDs to light

forever movb #16,lpcnt ; initialize LED pattern countldx #led_tab ; Use X as the pointer to LED pattern table

led_lp movb 1,x+,PORTB ; turn on one LEDldy #5 ; wait for half a secondjsr delayby100ms ; "dec lpcnt ; reach the end of the table yet?bne led_lpbra forever ; start from beginning

led_tab dc.b $80,$40,$20,$10,$08,$04,$02,$01dc.b $01,$02,$04,$08,$10,$20,$40,$80#include "C:\miniide\delay.asm"

; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

H. Huang Transparency No.4‐66Copyright © 2010 Delmar Cengage Learning

Page 67: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Interfacing with Seven-Segment Displaysg g p ySeven-segment displays are mainly used to display decimal digits and a small set of letters.The HCS12 I/O port can drive a seven-segment display directly.Buffer chips are used mainly to save excessive current draw from the HCS12. u e c ps a e used a y o save e cess ve cu e d aw o e CS .A example circuit for interfacing with seven-segment display is shown in Figure 4.17.Some people may use PB0 to PB6 to drive segment a to g instead.The microcontroller must send an appropriate value to the output in order to displaya certain value.

PB6 aa

HCS12 470 Ω each

74H

C24

4PB5PB4PB3PB2PB1

bc

defg

b

cd

e

fg

PB0 gcom m on cathode

Figure 4.17 Driving a single seven -segm ent display

H. Huang Transparency No.4‐67Copyright © 2010 Delmar Cengage Learning

Page 68: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Table 4.7 Decimal to seven-segment decoder

Decimaldigit a b c d e f g

Segments Corresponding Hex Number

012

101

111

110

101

101

100

001

$7E$30$6D

Figure 4.17 circuit Dragon12 demo board

$3F$06$5B2

345678

1101111

1110011

0111111

1101101

1000101

0011101

1111101

$6D$79$33$5B$5F$70$7F

$5B$4F$66$6D$7D$07$7F8

911

11

11

11

10

11

11

$7F$7B

$7F$67

Displaying Multiple Seven-Segment DisplaysA time-multiplexing technique is often used to display multiple digitsA time-multiplexing technique is often used to display multiple digits.The circuit in Figure 4.18 can display up to six digits simultaneous using the time-multiplexing technique.The HCS12 lights one digit for a short period of time and then switches to the next digit.Within one second each digit is lighted in turn many times Due to theWithin one second, each digit is lighted in turn many times. Due to the persistence of vision, all six digits appear to be lighted at the same time.

H. Huang Transparency No.4‐68Copyright © 2010 Delmar Cengage Learning

Page 69: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

800 Ω#5#1#0

.

.

.

a

b

g

. . .

. . .

. . .

74HC244

a

b

g

.

.

.

common common common

ab

g

800 Ω

800 Ω

PB

6

PB1

PB0

74HC244 commoncathode

commoncathode

commoncathode

PP0

74HC367

PP1

Y0A0

Y1A1

HCS12 ...

PP5

PP4

PP3

PP2

A5 Y5

A4

A3

A2 Y2

Y3

Y4

Figure 4.18 Port B and Port P together drive six seven -segment displays (MC9S12DG256)

To display 7 on the display #5

movb #$FF,DDRB ; configure Port B for outputmovb #$3F,DDRP ; configure Port P for outputmovb #$1F,PTP ; enable display #5 to be lightedmovb #$07 PTB ; send out the segment pattern of 7

H. Huang Transparency No.4‐69Copyright © 2010 Delmar Cengage Learning

movb #$07,PTB ; send out the segment pattern of 7

Page 70: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Example 4.14 Write a program to display 123456 on the six seven-segment displays shown in Figure 4.18.Solution: The values 1,2,3,4,5, and 6 are displayed on display #5, #4, …, #0, respectively.A table is set up to control the pattern and digit selection as shown in Table 4.8.

Table 4 8 Table of display patterns for Example 4 14

Seven-SegmentDisplay

DisplayedBCD Digit

Port B Port P

#5#4#3

123

$06$5B$4F

$1F$2F$37

Table 4.8 Table of display patterns for Example 4.14

#3#2#1#0

3456

$4F$66$6D$7D

$37$3B$3D$3E

#i l d " \ i iid \h 12 i "#include "c:\miniide\hcs12.inc"org $1500

start lds #$1500movb #$FF,DDRB

b #$3F DDRPmovb #$3F,DDRPforever ldx #DispTab ; set X to point to the display tableloopi movb 1,x+,PTB ; output segment pattern

movb 1,x+,PTP ; output display select ld #1

H. Huang Transparency No.4‐70Copyright © 2010 Delmar Cengage Learning

ldy #1jsr delayby1ms ; wait for 1 ms

Page 71: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

cpx #DispTab+12 ; reach the end of the table?bne loopibra forever#include "c:\miniide\delay.asm"

DispTab dc.b $06,$1Fdc.b $5B,$2Fdc.b $4F,$37dc.b $66,$3Bdc.b $6D,$3Ddc.b $7D,$3E

; org $FFFE ; uncomment this line for CodeWarrior; dc.w start ; uncomment this line for CodeWarrior

end

Generating a Digital Waveform Using an I/O PinA square wave can be generated by pulling a pin to high for certain amount of time andthen pull it to low for the same amount of time and repeat.p pBy connecting the pin to a speaker and making the frequency in the audible range, asound can be made.

H. Huang Transparency No.4‐71Copyright © 2010 Delmar Cengage Learning

Page 72: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Example 4.15 Write a program to generate a 1-kHz periodic square wave from the PT5 pin.Solution:

#include "c:\miniide\hcs12.inc"org $1500

start lds #$1500bset DDRT,BIT5 ; configure PT5 pin for output

forever bset PTT,BIT5 ; pull PT5 pin to highldy #10 ; wait for 0.5 msjsr delayby50us ; “bclr PTT,BIT5 ; pull PT5 pin to lowldy #10 ; wait for 0.5 msjsr delayby50us ; “bra forever#include "c:\miniide\delay.asm"

; org $FFFE; dc.w start

end

Example 4.16 Write a program to generate a two-tone siren that alternates between 250Hz and 500 Hz with each tone lasting for half of a second.

H. Huang Transparency No.4‐72Copyright © 2010 Delmar Cengage Learning

Page 73: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

#include "c:\miniide\hcs12.inc"org $1500

start lds #$1500bset DDRT,BIT5 ; configure PT5 pin for output

forever ldx #250 ; repeat 500 Hz waveform 250 timestone1 bset PTT,BIT5 ; pull PT5 pin to high

ldy #1jsr delayby1msbclr PTT,BIT5ldy #1jsr delayby1msdbne x,tone1ldx #125 ; repeat 250 Hz waveform for 125 times

tone2 bset PTT,BIT5ldy #2jsr delayby1msbclr PTT,BIT5ldy #2jsr delayby1msdbne x,tone2bra forever

H. Huang Transparency No.4‐73Copyright © 2010 Delmar Cengage Learning

#include "c:\miniide\delay.asm"end

Page 74: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

I t f i ith DIP S it hInterfacing with DIP SwitchesA dual-in-line package can be connected any port with 8 pins.A set of pull-up resistors are needed to pull the voltage to high on one side of the DIP.

VCCCC

10 KΩ

PA0

PA1

HCS12SW DIP-8

PA1PA2PA3

PA4

PA5PA6PA7

Figure 4.19 Connecting a set of eight DIP switches to Port A of the HCS 12

To read data into accumulator A

movb #0,DDRA ; configure port A for inputldaa PTA ; read into accumulator A

H. Huang Transparency No.4‐74Copyright © 2010 Delmar Cengage Learning

Page 75: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

Tips for Program Debugging Involving Subroutine Callsp g gg g g

What to do when the program gets stuck?

Step 1

Find out which subroutine gets stuck by setting a breakpoint immediately after the jsr

or bsr instruction.

Step 2Step 2

Find out why the subroutine gets stuck.

- Forgetting to restore registers pushed onto the stack before return.

- Forgetting to deallocate local variables before return.

- There are some infinite loops in the subroutine.

- Calling other subroutines that do not return.

H. Huang Transparency No.4‐75Copyright © 2010 Delmar Cengage Learning

Page 76: Chapter 4: Advanced Assembly Programmingcourses.engr.uky.edu/ideawiki/lib/exe/fetch.php?media=classes:12s:... · addb #$30 ; con ert the remainder to ASCII code; convert the remainder

The HCS12/MC9S12 Microcontroller

General Debugging Strategygg g gy

1. Make sure all leaf subroutines work correctly by using the methods described in Section2.9.

2. Debug intermediate subroutines. Make sure no intermediate subroutines get stuck.g g3. Debug the top level program.

H. Huang Transparency No.4‐76Copyright © 2010 Delmar Cengage Learning