100% found this document useful (1 vote)
138 views

Loops in Assembly Language: and Program Design

The document discusses loops in assembly language and program design. It covers defining problems, developing algorithms using flowcharts or pseudocode, coding programs, debugging, and maintaining programs. It also discusses structured programming concepts like sequences, if-then-else statements, and loops. Examples are provided of implementing loops and if-then-else statements in assembly language using instructions like dbne, cmpa, ble, and bhs. Delay loops are also demonstrated using repeated instruction sequences.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
138 views

Loops in Assembly Language: and Program Design

The document discusses loops in assembly language and program design. It covers defining problems, developing algorithms using flowcharts or pseudocode, coding programs, debugging, and maintaining programs. It also discusses structured programming concepts like sequences, if-then-else statements, and loops. Examples are provided of implementing loops and if-then-else statements in assembly language using instructions like dbne, cmpa, ble, and bhs. Delay loops are also demonstrated using repeated instruction sequences.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

LoopsinAssemblyLanguage

andprogramdesign

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

ProgramDesign
Definetheproblem
Identifywhatshouldbedone

Developthealgorithm(theoverallplanforsolvingthe problem)
Analgorithmisoftenrepresentedusingeither
Flowcharts(graphicaldiagram) Psuedocode (textdescription)

Codetheprogram
Convertthealgorithmintoaprogram

Debugtheprogram Maintaintheprogram

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Flowcharts
Terminal A

Process

Subroutine

Input or output

B off-page connector yes

Decision no

A on-page connector

Figure 2.1 Flowchart symbols used in this book

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Pseudocode
Adescriptionwritteninnormallanguagethatusesthestructural conventionsofaprogramminglanguage Examples: Omitsdetailsthatare notessentialfor humanunderstanding, suchas variable declarationsand systemspecificcode However,itshouldbe detailedenoughthat someonecanconvertit intoaprogram

Ifstudent'sgradeisgreaterthanorequalto60 print"passed" else print"failed Settotaltozero Setgradecountertoone Whilegradecounterislessthanorequaltoten Inputthenextgrade Addthegradeintothetotal Addonetogradecounter Settheclassaveragetothetotaldividedbyten Printtheclassaverage

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Equivalentflowcharts
Ifstudent'sgradeisgreaterthanorequalto60 print"passed" else print"failed

Settotaltozero Setgradecountertoone Whilegradecounterislessthanorequaltoten Inputthenextgrade Addthegradeintothetotal Addonetogradecounter Settheclassaveragetothetotaldividedbyten Printtheclassaverage

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

StructuredProgramming
Wecanwritegoodprogramsusing structuredprogrammingconcepts
goodmeanseasiertodesign, debug,andmaintain

Structuredprogrammingconcepts
Programsarecomposedofafew basicconstructs
sequence ifthenelse loop

Theymaybehierarchical
e.g.,asequencecouldbecomposed ofotherconstructs

Allconstructs(andallprograms) haveasingleentrypointanda singleexitpoint


MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Ifthenelse
C
false true

Pseudocode:

S1

S2

IfCthen S1 else S2 Assemblycode:

Example: IfN=5then foo=foo+2 else bar=bar 3

ldaa suba bne ldaa adda staa bra here ldaa suba staa next

N #5 here foo #2 foo next bar #3 bar

testifN=5

dothethenpart skipoverelsepart

dotheelsepart

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Loops

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Loops
Example:executeablockofcode500times
Flowchart Loadregister with500 (blockofcode)
Pseudocode Loadaregisterwiththevalue500 do (blockofcode) decrementtheregister while(registerzero)

dec.register

registerzero?
Y N

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

AssemblyCodeforLoop
Loop ldd (block : subd bne #500 of code) #1 Loop

Couldyouuseotherregisters fortheloopcounter? Whatsthemaximumcount?

Loopsareusedsooftenthattheyprovideasingleinstruction,dbne, thatbothdecrementsaregisterandthenbranchesifnotzero:
ldd #500 (block of code) : dbne D,Loop

Loop

Therearealsoinstructionsthat incrementinsteadofdecrement, andbranchifequaltozero Fulllist:


dbeq, dbne, ibeq, ibne

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Timetoexecutealoop
TheEclockinourMCUis24MHz Period=1/24MHz=0.0416usec (microseconds) Exampleloop:
loop: ldd nop subd bne #500 #1 loop ; ; ; ; 2 cycles 1 cycle 2 cycles 3/1 cycles

nop meansno operation;thisinstruction justdelaysalittle bne takes3cyclesif branchistaken;1ifnot

Totaltime(notcountinginitialldd):
500*(1+2+3)=3000cycles So3000*0.0416usec =125usec
Actually,forthelast iterationbne onlytakes1 cycleinsteadof3

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

Delayloops
Sometimeswewanttodelayacertainamountoftime wecanusea loop
Wefirstcreateasequenceofinstructionsthatdoesnothing,buttakesa knownamountoftimetoexecute Thenwerepeatthesequenceasmanytimesasnecessarytocreatethe desireddelay

Forexample,oneiterationofthelooponthenextpagetakes24Eclock cyclestoexecute
Byrepeatingthisinstructionsequencecertainnumberoftimes,anytime delaycanbecreated

AssumethattheHCS12hasanEclockfrequencyis24MHzandhencea clockperiodof0.042us(microseconds)
Thereforetheinstructionsequenceonthenextpagewilltake24*(0.042us) =1.0ustoexecute

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

12

Aloopwhose executiontimeis 24Eclockcycles periteration Notethatwe needtoinitialize registerXprior tothis(thevalue dependsonhow muchdelaytime wewant)

loop

psha pula psha pula psha pula psha pula nop dbne x,loop

; ; ; ; ; ; ; ; ; ;

2 3 2 3 2 3 2 3 1 3

E E E E E E E E E E

cycles cycles cycles cycles cycles cycles cycles cycles cycle cycles

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

13

Writeaprogramlooptocreateadelayof100us(microseconds). Solution: Adelayof100uscanbecreatedbyrepeatingthepreviousloop100times.

ldx #100 loop psha pula psha pula psha pula psha pula nop dbne x,loop

; ; ; ; ; ; ; ; ; ;

2 3 2 3 2 3 2 3 1 3

E E E E E E E E E E

cycles cycles cycles cycles cycles cycles cycles cycles cycle cycles

Ingeneral,todelayfortimeT: T=N*(24cycles)*(1/24MHz) or N=(T)(24000000)/24

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

14

Writeaninstructionsequencetocreateadelayof1second. Solution: Byrepeatingthepreviousinstructionsequence10,000times,wecancreatea delayof1second.

ldy outloop ldx inloop psha pula psha pula psha pula psha pula nop dbne dbne

#10000 #100 ; ; ; ; ; ; ; ; ; x,inloop ; y,outloop ; 2 3 2 3 2 3 2 3 1 3 3

N=(1)(24000000)/24 =1,000,000 Weneedtoruntheloop1,000,000 timestogeta1secdelay ButwecantjustloadregisterX with1,000,000(whynot?) Soinstead,enclosetheloopthat takes100ustoruninsideanother loop,andruntheouterloop 10,000times 10000*(100us)=1sec

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

15

CompareandTestinstructions
Theseinstructionsperformasubtractionoperation Goodtousethemjustbeforeaconditionalbranchinstruction
Thisinstruction (cba)performsthe subtraction(A)(B) However,itthrows theresultaway! Why?

Example:ifA>5,inc A
cmpa ble inca next #5 next

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

16

Example theforloop
Implementthe operation
fori=n1ton2doS

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

17

Example theforloop
Youcanusearegister (A,B,D,X,Y)fortheloop counter However,sometimes youneedtouseallthe registersforother operationsintheloop Sowewillstorethe loopcounterina memoryvariable

n1 n2 i

loop

next

equ xx equ yy ds.b 1 movb #n1,i ldaa i cmpa #n2 bgt next inc i bra loop

; starting index ; ending index ; loop counter variable ; initialize i to n1 ; check index i ; if i>n2, exit loop ; else do ops in loop ; increment loop ctr

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

18

Example
MCU

Problemstatement
Readtemperatureeverysecondfrominput portATDDR0(theanalogtodigitalconverter) Iftemperatureislessthan50,increaseheater poweroutput
Algorithm Set up analog to digital converter Set up Port T for output Set Power = 0 Repeat forever Read temp from ATDDR0 If temp < 50 increment Power write Power to PortT end delay one second end
MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

ATDDR0

Temp sensor

PortT Heater

19

Assembly
Power org rmb RAMSTART 1 ; reserve 1 byte for power value org ROMSTART ; insert code set up ATD (we will see how to do this later) ; set up Port T for output on all pins movb #$ff,DDRT clr movb Loop ldaa cmpa bhs inc movb Next ; insert the code to delay one second bra Loop ; repeat forever ATDDR0 #50 Next Power Power,PTT ; Read temp from ATDDR0 ; If temp < 50 ; increment Power ; write Power to PortT Power Power,PTT ; initialize Power output to zero ;write initial Power to PortT

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

20

Example
MCU

Problemstatement
Readtemperatureeverysecondfrominputport ATDDR0(theanalogtodigitalconverter) Iftempislessthan30,increaseheaterpower outputby3 Elseiftempislessthan50,increaseheaterpower by1 Elseiftempisgreaterthan60,decreaseheater powerby1

ATDDR0

Temp sensor

PortT Heater

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

21

Algorithmpsuedocode orflowchart

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

22

Assembly

MicrocomputerArchitectureandInterfacingColoradoSchoolofMinesProfessorWilliamHoff

23

You might also like