You are on page 1of 42

TheARMSim#UserGuide

R.N.Horspool,W.D.Lyons,M.Serra
DepartmentofComputerScience,UniversityofVictoria

1. Overview
ARMSim#isadesktopapplicationrunninginaWindowsenvironment.Itallowsusersto
simulatetheexecutionofARMassemblylanguageprogramsonasystembasedonthe
ARM7TDMIprocessor.ARMSim#includesbothanassemblerandalinker;whenafileis
loaded,thesimulatorautomaticallyassemblesandlinkstheprogram.ARMSim#also
providesfeaturesnotoftenfoundinsimilarapplications.Theyenableusersbothto
debugARMassemblyprogramsandtomonitorthestateofthesystemwhileaprogram
executes.Themonitoringinformationincludesbothcachestatesandclockcyclescon
sumed.
Thepurposeofthisuserguideistoexplainhowtousethetoolsandviews1providedby
ARMSim#.Therefore,thescopeofthedocumenthasbeenlimitedtothefeaturesofthe
simulator.ItdoesnotcoverARMassemblyprogrammingorcomputerarchitecture.
Userswhoareunfamiliarwiththesetopicsshouldconsultothermaterial,someofwhich
islistedinthereferences.

Thetopicsinthisdocumenthavebeenorganizedtoprovideastepbystepintroduction
toARMSim#,includingtheextrafeaturesregardingI/Oinstructions,basedoncustom
SWIcodes,andplugins.Thetableofcontentsbelowsummarizestheitemsdescribed.

1.Inthisdocument,aviewisawindowdisplayedbytheARMSim#simulatorthatshowsthestateofsome
aspectoftheprogrambeingrun.

ARMSim#UserGuide

TableofContents
1.

Overview..................................................................................................................1

2.

Features ....................................................................................................................3
2.1
2.2

3.

Setting up the Simulator ..........................................................................................4


3.1
3.2
3.3
3.4

4.

Creating a File ..................................................................................................................... 6


Opening and Loading a File ................................................................................................ 6
Running a Program.............................................................................................................. 7
Stopping a Program ............................................................................................................. 7
Code View ........................................................................................................................... 7
Registers View..................................................................................................................... 8

Debugging a Program ..............................................................................................9


5.1
5.2
5.3
5.4
5.5

6.

Docking Windows ............................................................................................................... 4


Board Controls View: the plug-ins and the SWI instructions ............................................. 5
Fonts .................................................................................................................................... 6
Colours ................................................................................................................................ 6

Getting Started .........................................................................................................6


4.1
4.2
4.3
4.4
4.5
4.6

5.

Toolbar................................................................................................................................. 3
Views ................................................................................................................................... 3

Stepping Through a Program............................................................................................... 9


Restarting a Program ........................................................................................................... 9
Reloading a Program ........................................................................................................... 9
Opening Multiple Files........................................................................................................ 9
Breakpoints........................................................................................................................ 10

Additional Views ...................................................................................................11


6.1
6.2
6.3
6.4
6.5

Watch View........................................................................................................................ 11
Memory View.................................................................................................................... 12
Output View....................................................................................................................... 14
Stack View......................................................................................................................... 15
Cache Views ...................................................................................................................... 16

7.

Some ARMSim# Limitations ................................................................................18

8.

SWI Codes for I/O in ARMSim#: the first Plug-in ...............................................19


8.1

9.

Basic SWI Operations for I/O ........................................................................................... 19


8.1.1
Detailed Descriptions and Examples for SWI Codes for I/O ............................. 20

SWI Operations for Other Plug-Ins: the Embest Board Plug-In ...........................24
9.0.1

10.

Code Examples ......................................................................................................30


10.1
10.2
10.3
10.4
10.5
10.6

Detailed Descriptions and Examples for SWI Codes for the Embest Board Plug-in26

Example: Print Strings, Characters and Integers to Stdout using SWI Instructions for I/O30
Example: Open and close files, read and print integers using SWI Instructions for I/O .. 31
Example: Useful patterns for using SWI Instructions for a Plug-In ................................. 33
Example: Subroutine to implement a wait cycle with the 32-bit timer............................. 33
Example: Subroutine to check for an interval with a 15-bit timer (Embest Board).......... 34
Example: Using the SWI Instructions for a Plug-In (Embest Board View)...................... 35

ARMSimUserGuide

Sections2and3beginwiththefeaturesofthesimulatorandexplainhowtocustomizeitslayout.Sec
tion4describesthemostcommonlyuseddebuggingfeaturesandviews.Sections5and6concludeby
detailingadditionaldebuggingfeatures,viewsandperformancemonitoringtools.Section8includes
detailsabouttheextrafeaturesofARMSim#,namelytheI/OinstructionsbuiltoncustomSWIcodes
(implementedasasexternalPlugin).Section9introducesthePluginfeature,withdetailedexamplesof
usebasedonthecurrentlyavailablemodules.

2. Features
TheARMSim#toolbarandviewsgivetheuseraccesstoavarietyoftoolstodebugandmonitorARM
assemblylanguageprograms.Thefollowingsectionsdescribethecontrolsprovidedbythetoolbarand
theinformationdisplayedintheviews.

2.1Toolbar
TheARMSim#toolbarprovideseasyaccesstomanyofthedebuggingfeaturesofthesimulator,espe
ciallythosefeaturesthatallowtheusertocontroltheexecutionofaprogram.Thefunctionsofthebut
tonsonthetoolbararesummarizedinTable1.

Table1.ToolbarButtons.
TheStepIntobuttoncausesthesimulatortoexecutethehighlightedinstructionandmoveto
thenextinstructionintheprogram.Ifthehighlightedinstructionisasubroutinecall(BLorBX
instruction)thenthenexthighlightedinstructionwillbethefirstinstructionofthesubroutine.
TheStepOverbuttoncausesthesimulatortoexecutethehighlightedinstructionandmoveto
thenextinstructioninthecurrentsubroutine.Ifthehighlightedinstructionisasubroutinecall
(BLorBXinstruction)thentheprogramisrununtilthesubroutinereturns.Thus,unlessa
breakpointisencountered,thenexthighlightedinstructionwillbeatthereturnpointfromthe
subroutinecall.
TheStopbuttoncausesthesimulatortostoptheexecutionoftheprogram.
TheContinuebuttoncausesthesimulatortoruntheprogramuntilitencountersabreakpoint,
anSWI0x11instruction(endofexecution),oraruntimeerror.
TheRestartbuttoncausesthesimulatortostarttheexecutionoftheprogramfromthebegin
ning.
TheReloadbuttoncausesthesimulatortoloadanewversionoftheprogramfilefromthe
harddriveandstarttheexecutionoftheprogramfromthebeginning.

2.2Views
TheARMSim#viewsdisplaythesimulatorsoutputandthecontentsofthesystemsstorage.ARMSim#
providesseveralviews,whicharesummarizedinTable2.

ARMSim#UserGuide

Table2.ARMSim#Views
CodeView

Itdisplaystheassemblylanguageinstructionsoftheprogramthatiscur
rentlyopen.Thisviewisalwaysvisibleandcannotbeclosed.

RegistersView

Itdisplaysthecontentsofthe16generalpurposeuserregistersavailablein
theARMprocessor,aswellasthestatusoftheCurrentProgramStatusReg
ister(CPSR)andtheconditioncodeflags.Thecontentsoftheregisterscan
bedisplayedinhexadecimal,unsigneddecimal,orsigneddecimalformats.
AdditionallythecontentsoftheVectorFloatingPointCoprocessor(VFP)
registerscanbedisplayed.TheyincludetheoverlappedSinglePrecision
Registers(s0s31)andtheDoublePrecisionFloatingPointRegisters(d0
d15).

OutputView:Console Itdisplaysanyautomaticsuccessanderrormessagesproducedbythesim
ulator.
OutputView:
Stdin/Stdout/Stderr

Itdisplaysanytextprintedtostandardoutput,Stdout.

StackView

Itdisplaysthecontentsofthesystemstack.Inthisview,thetopwordinthe
stackishighlighted.

WatchView

Itdisplaysthevaluesofvariablesthattheuserhasaddedtothewatchlist,
thatis,thelistofvariablesthattheuserwishestomonitorduringtheexecu
tionofaprogram.

CacheViews

TheydisplaythecontentsoftheL1cache.Thiscachecanconsistofeithera
unifieddataandinstructioncache,displayedintheUnifiedCacheView,or
separatedataandinstructioncaches,displayedintheDataCacheand
InstructionCacheViews,respectively,dependingonthecacheproperties
selectedbytheuser.

BoardControlsView

Itdisplaystheuserinterfacesofanyloadedplugins.Ifnopluginswere
loadedatapplicationstart,thisviewisdisabled.

MemoryView

Itdisplaysthecontentsofmainmemory,as8bit,16bit,or32bitwords.
Therecanbemultiplememoryviews,eachdisplayingadifferentregionof
memory.

3. SettinguptheSimulator
TheappearanceofARMSim#,includingthelocation,font,andcolouroftheviews,canbecustomizedto
suittheuserspreferences.Whenthesimulatorisclosed,thesettingsarerememberedfornexttimethe
userstartsupARMSim#.ThefollowingsectionsdescribehowtocustomizeARMSim#sappearance.

3.1DockingWindows
Alloftheviewsdescribedinsection2.2,excepttheCodeView,appearindockingwindows(seeFigure
1).Eachwindowcanbedockedalonganysideoftheapplicationwindow,oritcanfloatabovetheappli

ARMSimUserGuide

cationwindow.Inaddition,eachdockingwindowcanbedisplayedorhidden,andeachdisplayedwin
dowhasanautohideoption.
Tomoveadockingwindow,clickthetitlebarofthewindow,anddragthewindowtothedesiredloca
tion.Ifmultipleviewshavebeenstackedwithinasingledockingwindow,selectthetabwiththedesired
viewnamefromthetabsalongthebottomofthedockingwindow,clickthistab,anddragittothe
desiredlocation.
Totoggleadockingwindowbetweentheshowandhidestates,selecttheviewnamefromtheView
menu.Alternatively,tohideadockingwindowthatiscurrentlydisplayed,clicktheXinthetopright
cornerofthedockingwindow.Totoggleadockingwindowbetweentheshowandautohidemodes,
clickthepininthetoprightcorner.

DockedWindowin
AutohideMode

DockedWindow

FloatingWindow

Usethepintotogglebetweentheshowand
autohidemodes,andusetheXtohidetheview

Usethetabstoselectone
viewfromastackofviews

Figure1.DockingWindows

3.2BoardControlsView:thepluginsandtheSWIinstructions
WhileARMSim#canbeusedcompletelyonitsown,theextrafeaturesofpluginsandI/Oinstructions
canbeextremelyuseful.Theyhavetobeenabledexplicitlyevenwheninstalledatthesametime.Plug
ins(seebelow)areseenasconfigurableadditionstoprovideextrafunctionality,normallyasagraphical
viewofI/O(e.g.aboardwithbuttonsandlights).Oneotherveryimportantextensionistheuseofpre
selectedSWIinstructionstoimplementI/Ofunctionalities,suchasreadingandwritingfromstan
dardinputoroutputorfiles(seebelow).

ARMSim#UserGuide

Inordertoenablethesefeatures.clickonFileandPreferencesandthenselectthetabPlugins.Theavail
ablemodulesasloadedintheARMSim#directoryarelistedandneedtobecheckedforenabling.

3.3Fonts
Tochangethefont,size,style,orcolourofthetextinaview,movethecursorintotheview,clicktheright
mousebutton,andselectFontfromthecontextmenu.Then,makechangesintheFontdialogbox,and
clickOK.Torestoretheoriginalfontsettings,movethecursorintotheview,clicktherightmousebut
ton,andselectRestoreDefaultsfromthecontextmenu.NotethatRestoreDefaultswillalsorestorethe
defaultbackgroundandhighlightcolours.

3.4Colours
Tochangethebackground(highlight)colourinaview,movethecursorintotheview,clicktheright
mousebutton,andselectBackgroundColour(HighlightColour)fromthecontextmenu.Then,make
thechangesintheColordialogbox,andclickOK.Torestoretheoriginalbackgroundandhighlight
colours,movethecursorintotheview,clicktherightmousebutton,andselectRestoreDefaultsfrom
thecontextmenu.NotethatRestoreDefaultswillalsorestorethedefaultfontsettings.
Theuseofthehighlightcolourdependsoncontext.Forexample,intheCodeandStackViews,itisused
asabackgroundcolouronthehighlightedline,butintheRegisterandCacheViews,itisusedasatext
colourforstoragelocationsthathavebeenwrittento.

4. GettingStarted
UsingARMSim#tosimulatetheexecutionofaprogramonanARMprocessorinvolvestwoactivities
actuallyrunningtheprogramandobservingtheoutput.Sections4.1to4.4provideinformationonrun
ningprogramswiththesimulator,whilesections4.5and4.6describetwooftheviewsavailableinthe
simulator.

4.1CreatingaFile
ARMSim#acceptsbothARMassemblysourcefilesthatusetheGnuAssembler(gas)syntaxandARM
objectfilesgeneratedbytheGnutoolsprovidedwithCygwinorCodeSourcery.ARMassemblysource
filescanbecreatedusinganytexteditor(e.g.TextPad)andmustbesavedwitha.sfilenameextension.
ARMobjectfilescanbegeneratedfromARMassemblyfilesorCsourcefilesandmustbecompiled
accordingtotheinstructionsintheaccompanyingdocumentonCandARM.FordetailsonARM
assemblyprogrammingconsultthereferences.

4.2OpeningandLoadingaFile
Toopenafile,selectFile>Load.Thennavigatetothefolderinwhichthefileisstoredanddoubleclick
thefiletobeopened.Whenafileisopened,itisautomaticallyassembled(ifitisasourcefile)and
linked.Iftheassemblyandlinkingprocessesaresuccessful,thecontentsofthefileappearinthe
CodeViewwiththefirstinstructioninthe_start(ormain)subroutinehighlighted.Ifthecontentsofthe
fileappearintheCodeView,butthefirstinstructionisnothighlighted,onemustchecktheOutput
Viewforcompilererrors(seesection6.3).
Notes:
Thefiletobeopenedmustbeasource(.s)fileoranobject(.o)file.
Ifthefiletobeopeneddoesnotappearinthedirectorylistinginthedialogbox,checktomake
surethattheappropriatefiletypehasbeenselected.
6

ARMSimUserGuide

ThesourcecodecannotbeeditedintheCodeViewwindow,butmustbechangedintheoriginal
texteditorandthenreloaded.

4.3RunningaProgram
ToruntheprogramdisplayedintheCodeView,selectDebug>Run,orclicktheContinuebuttonon
thetoolbar(seeTable1).Theprogramrunsuntilthesimulatorencountersabreakpoint(seesection5.5
foranexplanationofbreakpoints)oranSWI0x11instruction(toexittheexecution),orafatalerror.

4.4StoppingaProgram
Tostopaprogramthatiscurrentlyrunning,selectDebug>Stop,orclicktheStopbuttononthetoolbar
(seeTable1).Whentheprogramhasstopped,anystoragelocationsintheRegister,Cache,andMemory
Viewsthathavebeenwrittentosincetheprogramstartedrunningarehighlighted.

4.5CodeView
TheCodeViewdisplaystheassemblylanguageinstructionsoftheprogramthatiscurrentlyactive.
Nexttoeachinstruction,thesimulatorshowsthememoryaddressoftheinstructionandthebinaryrep
resentationoftheinstruction,separatedbyacolonanddisplayedinhexadecimalformat(seeFigure2).

Usethetabstoselectthefileto
bedisplayedintheCodeView

Thenextinstructiontobe
executedishighlighted

Theaddressofaninstruction
(displayedinhexadecimalform)

Thebinaryrepresentationofaninstruction
(displayedinhexadecimalform)

Figure2.CodeView
Whenafileisopenedandsuccessfullyassembledandlinked,itscontentsaredisplayedintheCode
View,asdescribedabove,andthefirstinstructiontobeexecutedishighlighted.Whenmultiplefilesare
opened(seesection5.4),thefileinwhichexecutionmuststartisdisplayedintheCodeViewwiththe
firstinstructionhighlighted.TheotherfilescanbeviewedbyclickingonthetabsatthetopoftheCode
View.

ARMSim#UserGuide

4.6RegistersView
TheRegistersViewdisplaysthecontentsofthe16generalpurposeuserregistersavailableintheARM
processor,aswellasthestatusoftheCurrentProgramStatusRegister(CPSR)andtheconditioncode
flags(theleftmost4bitsoftheCPSR,asdisplayedbelowtheconditioncodeflagsinthesimulator).
Additionally,theVectorFloatingPoint(VFP)registersareavailablefordisplayinthetablabelledFloat
ingPoint.Theseregistersrepresentthe32SinglePrecisionregistersorthe16DoublePrecisionRegis
tersoftheVFP.Notethatthesetwosetsofregistersareoverlapped.
TheGeneralPurposeRegistersareselectedbyclickingontheGeneralPurposeRegisterstabinthe
RegistersView.Thecontentsofthegeneralpurposeregisterscanbedisplayedinhexadecimal,signed
decimal,orunsigneddecimalformats.UsetheHexadecimal,SignedDecimal,andUnsignedDecimal
buttonsatthetopoftheRegistersViewtoswitchbetweendisplayformats(seeFigure3).
Whenaninstructionisexecutedusingoneofthestepcommands(seesection5.1)orwhenasequenceof
instructionsisexecutedusingtheDebug>RunoptionortheContinuebutton(seesection4.3),anyreg
istersandconditioncodeflagsthatwerewrittentoduringtheexecutionoftheinstruction(s)arehigh
lightedaftertheexecutionoftheinstruction(s)hasfinished.
RegistersR10R15arealsolabelled:
Usethesebuttonstoswitch
Use these buttons to
switch between the
betweentheHexadecimal,
Hexadecimal, Unsigned
Table 3.
UnsignedDecimaland
Decimal and Signed
Decimal display modes.
SignedDecimaldisplay
stacklimit
R10 sl
modes
Registersthatwere
Registers that were
written to during the
writtentoduringthe
execution of the last
executionofthelast
instruction (or sequence
instruction(or
of instructions)
sequenceofinstruc
tions)

R11

fp

framepointer

R12

ip

intraprocedurecallscratch
register

R13

sp

stackpointer

R14

lr

linkregister

R15

pc

programcounter

Condition
Condition
Code Flags
CodeFlags
CPSR(CurrentProgram
CPSR (Current Program
StatusRegister)
Status Register)

Figure3.GeneralPurposeRegistersView.

TheFloatingPointRegistersareselectedbyclickingontheFloatingPointtabintheRegistersView.
TheFloatingPointRegisterscanbeviewedasSinglePrecisionorDoublePrecisionregisters.UsetheSin
glePrecisionorDoublePrecisiontabsatthetopoftheRegistersViewtoswitchbetweenthedisplay
types(seeFigure4).

ARMSimUserGuide

5. DebuggingaProgram
ARMSim#providesanumberoffeaturesthatenableuserstodebugARMassemblyprograms,includ
ingexecutioncontrolstostepthroughandrestartprograms,ReloadandOpenMultiplecommands,
andbreakpoints.Sections5.1and5.2describetheexecutioncontrols.Sections5.3and5.4describethe
ReloadandOpenMultiplecommands,respectively,andsection5.5explainshowtomanagebreak
points.

5.1SteppingThroughaProgram
Tostepthroughaprogramoneinstructionatatime,useeithertheStepIntobuttonortheStepOver
buttononthetoolbar,oralternatively,selectDebug>StepIntoorDebug>StepOver.
AfteraninstructionhasbeenexecutedusingeitherStepIntoorStepOver,boththenextinstructionto
beexecutedandanymemorylocationsintheRegisters,Memory,andCacheViewsthatwerewrittento
duringtheexecutionoftheinstructionarehighlighted.
Formostinstructions,theresultsofbothStepIntoandStepOverareidentical;however,whenan
instructionisabranchtoasubroutine,StepIntoexecutesthebranchandmovestothefirstinstruction
ofthesubroutine.Incontrast,theStepOverexecutesthewholesubroutineandmovestotheinstruction
afterthebranchintheoriginalsubroutine.Therefore,ifaprogramconsistsofmultiplefilesandthereis
abranchfromasubroutineinonefiletoasubroutineinanotherfile,executingthebranchusingStep
IntoalsochangesthefiledisplayedintheCodeView.

5.2RestartingaProgram
Torestartaprogram,clicktheRestartbuttononthetoolbar,orselectDebug>Restart.Restartingapro
gramresetstheregisters,cache,andmemory;itsetstheprogramcountertotheaddressofthefirst
instructionintheprogram;andithighlightsthisinstruction(thenextinstructiontobeexecuted).

5.3ReloadingaProgram
Toreloadaprogram,clicktheReloadbuttononthetoolbar,orselectFile>Reload.Reloadingapro
gramloadsanewcopyofthefilefromtheharddrive;itresetstheregisters,cache,memory,stack,and
watches;itsetstheprogramcountertotheaddressofthefirstinstructionintheprogram;andithigh
lightsthisinstruction(thenextinstructiontobeexecuted).

5.4OpeningMultipleFiles
Toopenmultiplefiles,selectFile>OpenMultiple.Then,clicktheAddbuttonintheMultiFileOpen
dialogbox;navigatetothefolder,inwhichthefilesarestored;anddoubleclickthefiletobeopened.
Repeatthethreestepsintheprevioussentenceuntilallofthefilestobeopenedhavebeenaddedtothe
listinthedialogbox.Then,clickOKtoopenthefiles.Whenthefileshavebeensuccessfullyopened,the
contentsofthefilethatcontainsthe_start(ormain)subroutinewillappearintheCodeViewwiththe
firstinstructioninthissubroutinehighlighted.
Toremoveafilefromthelistoffilestobeopened,selectthefilenameinthedialogbox,andclickthe
Removebutton.Toremoveallofthefilesfromthelistoffilestobeopened,clicktheClearbutton.
Notes:
ThefilestobeopenedmustbeARMassemblersource(.s)files,ARMobject(.o)files,oracombi
nationofsourceandobjectfiles.
Ifafiledoesnotappearinthedirectorylistinginthedialogbox,onemustcheckthattheappro
priatefiletypehasbeenselected.
9

ARMSim#UserGuide

Usethesebuttonstoswitch
Use these buttons to switch between the
Single or Double precision Floating Point
betweentheSingleorDouble
registers
precisionFloatingPoint
Registers
Registersthatwerewritten
toduringtheexecutionofthe
Registers that were written to during the
execution of the last instruction (or sequence
lastinstruction(orsequence
of instructions)
ofinstructions)

ConditionCodeFlags
Condition Code Flags

FPCPSR(FloatingPoint
FCPSR (Floating Point Current Program
Status Register)
CurrentProgramStatus

Figure4.FloatingPointRegistersView.

IfthecontentsofthefileappearintheCodeView,butthefirstinstructionisnothighlighted,
checktheOutputViewforcompilererrors(seesection6.3).
Whenthefileisopened,itisautomaticallyassembled(ifitisasourcefile)andlinked.

5.5Breakpoints
Abreakpointisauserdefinedstoppingpointinaprogram(i.e.apointotherthananSWI0x11instruc
tion,atwhichexecutionofaprogramshouldterminate).Whenaprogramisbeingdebugged,break
pointsareusedtohaltexecutionoftheprogramatpredefinedpointssothatthecontentsofstorage
locations,suchasregistersandmainmemory,canbeexaminedtoensurethattheprogramisworking
correctly.
WhenabreakpointissetandtheprogramisrunusingeithertheDebug>RunoptionortheContinue
button(seesection4.3),executionoftheprogramstopsjustbeforeexecutionoftheinstructionatwhich
thebreakpointisset(seeFigure5).

10

ARMSimUserGuide

Tosetabreakpoint,doubleclickthelineofcode,atwhichthebreakpointshouldbeset.Alternatively,
stepthroughthecodetotheline,atwhichthebreakpointshouldbeset,andthenselectDebug>Toggle
Breakpoint.Whenthebreakpointisset,alargereddotappearsintheCodeViewnexttotheaddressof
theinstructionatwhichthebreakpointwasset.
Toclearabreakpoint,doubleclickthelineofcode,atwhichthebreakpointisset.Alternatively,step
throughthecodetotheline,atwhichthebreakpointisset,andthenselectDebug>ToggleBreakpoint.
Toclearallofthebreakpointsinaprogram,selectDebug>ClearAllBreakpoints.
Note:
ClearAllBreakpointsclearsthebreakpointsinallfilesthatarecurrentlyopen.

Whentheprogramisrun,executionstops
justbeforeexecutionoftheinstruction
wherethebreakpointisset

Abreakpoint

Figure5.Breakpoints.

6. AdditionalViews
InadditiontotheCodeandRegisterViewsdiscussedinsections4.5and4.6,respectively,ARMSim#
includesWatch,Memory,Output,Stack,andCacheViewsthatenableuserstoobservethedatatrans
ferswithinthesystem,aswellastheoutputofthesystem.Thefollowingsectionsdescribetheseaddi
tionalviewsandexplainanycommandsandsettingsassociatedwiththem.

6.1WatchView
TheWatchViewdisplaysthevaluesofvariablesthattheuserhasaddedtothewatchlist,whichisalist
ofvariablesthattheuserwishestomonitorduringtheexecutionofaprogram.
Toaddavariabletothewatchlist,selectWatch>AddWatch.Alternatively,rightclickintheWatch
View,andselectAddWatchfromthecontextmenu.IntheAddWatchdialogbox(seeFigure6),select
thefile,inwhichthevariableappears;thelabelthatisattachedtothevariable;andthedisplaytypeof
11

ARMSim#UserGuide

thevariable.Ifapplicable,specifytheintegerformatofthevariable,andselectthebase,inwhichthe
integerrepresentationofthevariableshouldbedisplayed.ClickOK.
Toremoveavariablefromthewatchlist,selectthevariableintheWatchView,andthenselectWatch>
RemoveWatch.Toremoveallofthevariablesfromthewatchlist,selectWatch>ClearAll.Alterna
tively,rightclickintheWatchView,andselectClearAllfromthecontextmenu.
Notes:
AlthoughRemoveWatchappearsintheWatchmenu,thisoptionhasnotyetbeenimplemented.
TheWatchViewdoesnotdisplayarrays;however,itispossibletodisplaythefirstitemofan
arraybytreatingitasascalarvariableandaddingittothewatchlist,asdescribedabove.

Figure6.AddingaWatch.
6.2MemoryView
AMemoryViewdisplaysthecontentsofmainmemory.Inthisview,eachrowcontainsanaddressfol
lowedbyaseriesofwordsfrommemory(seeFigure7).
SincetheentiremainmemorycannotbedisplayedinasingleMemoryView,eachMemoryViewshows
onlyapartofmemory.Theaddressinthetopleftcorneroftheviewspecifiestheword,atwhichthepart

12

ARMSimUserGuide

ofmemorydisplayedintheviewbegins,andthesizeoftheviewdeterminesthenumberofwordsdis
played.
Todisplayadifferentpartofmemory,enterahexadecimaladdressfrom0toFFFFFFFFintothetextbox
inthetopleftcorneroftheMemoryView.Alternatively,usetheupanddownarrowsbesidethetext
boxtoselectlowerandhighermemoryaddresses,respectively.Thecontentsofmemorycanbedis
playedas8bitbytes,16bithalfwords,or32bitwords.UsethethreebuttonsintheWordSizeboxinthe
toprightcorneroftheMemoryViewtoswitchamongthethreedisplayformats.

Theaddressofthefirstwordwherethe
displayofmemoryinthisviewbegins

Usethesebuttonstoswitch
betweenthe8bit,16bit
and32bitdisplaymodes
Memorylocationsthatwerewrittentoduringtheexecution
ofthelastinstruction(orsequenceofinstructions)

Address

MemoryValues

Figure7.MemoryView.
Whenaninstructionisexecutedusingoneofthestepcommands(seesection5.1)orwhenasequenceof
instructionsisexecutedusingtheDebug>RunoptionortheContinuebutton(seesection4.3),any
memorylocationsthatwerewrittentoduringtheexecutionoftheinstruction(s)arehighlightedafterthe
executionoftheinstruction(s)hasfinished.
Thepropertiesofmainmemory,includingitsstartingaddress,thestackarea,andtheheaparea,canbe
customizedtosuittheuserspreferences.Tochangetheseproperties,selectFile>Preferences,andclick
theMainMemorytab.Typeinnewvaluesforthestartingaddress,stackarea,andheaparea,orusethe
arrowbuttonsbesideeachpropertytoadjustthevalueofthatproperty(seeFigure8).ClickOK,and
thenreloadtheprogram(seesection5.3)torefreshtheMemoryView(s).
Notes:
Ifastore(STR)instructionisexecuted,butthevalueinmemorydoesnotchange,checkthe
CachePreferencestomakesurethattheWritePolicyisnotsettoWriteBack.Ifitis,setitto
WriteThrough.(Seesection6.5forinformationonsettingtheCachePreferences.)
ThesimulatorcanhavemultipleMemoryViews,eachofwhichdisplaysadifferentregionof
memory.ToopenadditionalMemoryViews,selectView>Memory.
13

ARMSim#UserGuide

Whenthedisplaysizeissetto8bit,theASCIIrepresentationofeachrowofbytesisdisplayedat
theendoftherow.
Whenthedisplaysizeis16bitor32bit,theassignmentofbyteaddressesislittleendian.
IntheMemoryView,allcellsthatarepartofthememoryregionallocatedtotheprogramare
showninhexadecimalnotation(e.g.E1A03000,00000000);cellsoutsidetheallocatedmemory
regionareshownasquestionmarks(e.g.????????).

Figure8.MainMemoryPreferencesForm.
6.3OutputView
TheOutputViewcontainsarowoftwotabslabelledConsoleandStdin/Stdout/Stderr.Selectingthe
tablabelledConsolebringsawindowtothefrontwherethesimulatoroutputssuccessanderrormes
sages.Afterthesimulatorhasloadedtheprogram,anyassemblerorlinkererrorsaredisplayedhere(see
Figure9foranexample).TofindthesourceofanerrormessagedisplayedintheOutputView(seeFig
ure9),doubleclickthemessage,andscrolluponelineintheCodeView.Additionalinformationwillbe
displayedheresuchasinstructioncountsandruntimes.
SelectingthetablabelledStdin/Stdout/Stderrbringsawindowtothefrontwhereoutputfromthe
userprogramisdisplayedasaresultofusingsoftwareinterrupts(SWIinstructions)toperformI/O.
Outputdirectedtoeitherthestandardoutputorstandarderror(Stdin/Stdout)aredisplayedinthis
tabbedwindow.Anyrequesttoreadfromthestandardinputdevice(Stdin)causestheprogramto
freezeuntiltheinputisprovidedonthekeyboard;thatinputisechoedinthistabbedwindowaswell.
14

ARMSimUserGuide

TocopytextfromtheoneoftheOutputViewtabbedwindows,rightclickintheview,andselectCopy
toClipboardfromthecontextmenu.ToclearthecontentsoftheOutputViewtabbedwindow,right
clickinthetab,andselectClearfromthecontextmenu.

6.4StackView
TheStackViewdisplaysthecontentsofthesystemstack.Inthisview,thememoryaddressofavalue
anditsbinaryrepresentationaredisplayedonasingleline,separatedbyacolonanddisplayedinhexa
decimalformat.Furthermore,thetopwordinthestackishighlighted(seeFigure10).Notethatthesys
temstackisafulldescendingstack.

Figure9.ErrorMessage.

15

ARMSim#UserGuide

TopoftheStack

Stack
Value

Figure10.StackView.
MemoryAddress

6.5CacheViews
TheCacheViewsdisplaythecontentsoftheL1cache.Thecachecanhavedifferentorganizations.The
oneusedbyARMSim#canbeselectedbytheuserbeforeanARMprogramisexecuted.Thecachecan
consistofeitheraunifieddataandinstructioncache,displayedintheUnifiedCacheView,orseparate
dataandinstructioncaches,displayedintheDataandInstructionCacheViews,respectively,depend
ingonthecachepropertiesselectedbytheuser.
Tosetthecacheproperties,selectFile>Preferences,andclicktheCachetab.Then,useeithertheCache
PreferencesForm(seeFigure11)ortheCacheWizardtochangethecurrentcachesettings,andclick
OK.Torestorethedefaultcacheproperties,selecttheRestoreDefaultsbuttonontheCachePreferences
Form.
WhenusingtheCachePreferencesFormtosetthecacheproperties,beginbyselectingthetypeofcache.
Table3liststheavailablecacheconfigurations.Then,setthesizeofthecache(s).OncetheCacheSizehas
beenset,selectingavalueforeithertheBlockSizeortheNumberofBlockscausestheremainingset
tingsintheCacheSizeboxtoassumetheappropriatevalues,sothatthethreepropertiessatisfythefol
lowingequation:
CacheSize(bytes) = BlockSize(bytes) NumberofBlocks

16

ARMSimUserGuide

Next,selecttheAssociativityofthecache(s).IfSetAssociativeisselected,settheBlocksperSet,and
selectaReplacementStrategy.Finally,selecttheWriteandAllocatePoliciesfortheCacheorData
Cache.

Table3.CacheConfigurations.
Configuration

Settings

UnifiedDataandInstructionCache

EnabletheUnifiedDataandInstructionCache.

SeparateDataandInstructionCaches

DisabletheUnifiedDataandInstructionCache,andenable
theDataCacheandtheInstructionCache.

DataCacheOnly

DisabletheUnifiedDataandInstructionCacheandthe
InstructionCache,andenabletheDataCache.

InstructionCacheOnly

DisabletheUnifiedDataandInstructionCacheandthe
DataCache,andenabletheInstructionCache.

NoCache

DisabletheUnifiedDataandInstructionCache,theData
Cache,andtheInstructionCache.

Figure11.CachePreferencesForm.

17

ARMSim#UserGuide

IntheCacheViews,theboundariesofsetsaremarkedbythebluesquarebracketsalongthelefthand
sideoftheview(seeFigure12).Eachrowconsistsofamemoryaddress,followedbyacacheblockthat
showsthecontentsoftheblockatthisaddressinmemory.
Whenaninstructionisexecutedusingoneofthestepcommands(seesection5.1)orwhenasequenceof
instructionsisexecutedusingtheDebug>RunoptionortheContinuebutton(seesection4.3),any
cacheblocksthatwerewrittentoduringtheexecutionoftheinstruction(s)arehighlightedaftertheexe
cutionoftheinstruction(s)hasfinished.
WhentheWritePolicyissettoWriteBack,adirtyblockismarkedbyareddottotheleftoftherow.
Toclearallofthecacheblocks,selectCache>Reset.Resettingthecachepurgesallofthedirtyblocks,
invalidatesallofthecacheblocks,andsetsallofthecachestatisticstozero.Topurgeallofthedirty
blocksinthecache,selectCache>Purge.ThiscommandhasnoeffectunlesstheWritePolicyissetto
WriteBack.
Toviewthecachestatistics,includingthehitandmissrates,selectCache>Statistics.Toclearallthe
cachestatistics,clicktheResetbuttonontheCacheStatisticsdisplay.
Note:
TheInstructionCacheissometimesreferredtoastheCodeCache.

CacheSet

CacheBlock
MemoryAddress
Cacheblockthatwaswrittento
duringtheexecutionofthelast
instruction(orsequenceof
instructions)
DirtyBlock

Figure12.CacheView.

7. SomeARMSim#Limitations
TheARMSim#isanaidforlearningtheoperationoftheARMarchitecture.Itdoesnotimplementevery
featurethatcanbefoundontheARM.Someofthemoreimportantlimitationsarelistedbelow.

18

ARMSimUserGuide

TheARMarchitecturesupportsbothlittleendianandbigendianaccesstomemory.TheARM
Sim#supportsonlythelittleendianformat(thesameastheIntelarchitecturewhichhoststhe
ARMSim#).
TheARMarchitecturehasaspecialmodeofexecutioncalledThumbmodewhichisintended
forembeddedsystemapplicationswherememoryisascarceresource.Eachthumbinstruction
occupiesonly2bytes.ThumbmodeisnotcurrentlysupportedbyARMSim#.

8. SWICodesforI/OinARMSim#:thefirstPlugin
PluginshavebeenusedtoextendthefunctionalityofARMSim#inamodularfashion.Afulldescrip
tionofthePlugindesignsisbeyondthescopeofthisdocument.ThedefaultinstallationofARMSim#
comeswithtwoPluginsmoduleextensions:SWIInstructionsandEmbestBoard.TheSWIInstructions
pluginimplementsSWIcodestoextendthefunctionalityofARMSim#forcommonI/Ooperationsand
itsuseisdetailedinthissection.ImportantNote:AllPluginshavetobeenabledexplicitlybycheckingtheir
optionintheFile>PreferencesmenuandselectingtheappropriatelinefromwithinthetablabelledPlugins.

8.1BasicSWIOperationsforI/O
TheSWIcodesnumberedintherange0to255inclusivearereservedforbasicinstructionsthatARM
Sim#needsforI/Oandshouldnotbealtered.TheirlistisshowninTable4andexamplesoftheirusefol
low.TheuseofEQUisstronglyadvisedtosubstitutetheactualnumericalcodevalues.Therighthand
column showstheEQUpatternsusedthoughoutthisdocumentintheexamples.

Table4.SWII/Ooperations(0x000xFF)
Opcode

DescriptionandAction

Inputs

Outputs

swi 0x00 DisplayCharacteron


Stdout

r0:thecharacter

swi 0x02 DisplayStringon

r0: addressofanullter (seealso0x69


minatedASCIIstring
below)

Stdout
swi 0x11 HaltExecution

EQU

SWI_PrChr

SWI_Exit

swi 0x12 AllocateBlockofMem r0:blocksizeinbytes


oryonHeap
swi 0x13 DeallocateAllHeap
Blocks

r0:addressofblock SWI_MeAlloc

SWI_DAlloc

swi 0x66 OpenFile


(modevaluesinr1are:0
forinput,1foroutput,2
forappending)

r0:filename,i.e.addressof
anullterminatedASCII
stringcontainingthename
r1:mode

swi 0x68 CloseFile

r0:filehandle

swi 0x69 WriteStringtoaFileor r0:filehandleorStdout


toStdout
r1:addressofanulltermi
natedASCIIstring

r0:filehandle
SWI_Open
Ifthefiledoesnot
open,aresultof1
isreturned

SWI_Close
SWI_PrStr

19

ARMSim#UserGuide

Table4.SWII/Ooperations(0x000xFF)
Opcode

DescriptionandAction

Inputs

Outputs

swi 0x6a ReadStringfromaFile r0:filehandle


r1:destinationaddress
r2:maxbytestostore
swi 0x6b WriteIntegertoaFile

r0:numberof
bytesstored

r0:filehandle
r1:integer

EQU

SWI_RdStr

SWI_PrInt

swi 0x6c ReadIntegerfromaFile r0:filehandle

r0:theinteger

swi 0x6d Getthecurrenttime


(ticks)

r0:thenumberof SWI_Timer
ticks(milliseconds)

SWI_RdInt

8.1.1DetailedDescriptionsandExamplesforSWICodesforI/O
DisplayCharacteronStdout:swi0x00
Acharacterisa1byteentity.TheSWI 0x00instructionfromtheSWItableofthesimulator(normally
usedwith.equ SWI_PrChr,0x00)canprintsuchacharactertothestdoutviewwhenassignedto
registerr0.
ThelinesofcodebelowprintthecharacterlabelledAtotheStdout,followedbythenewlinecharacter.
Notethattheassignmentofacharactertoaregisterneedsthesingleleftquoteinthesyntaxforthe
immediateoperand.

Displaysonecharacterintheoutputwindow.

mov
swi
mov
swi

r0,#A
PrChr
r0,#\n
PrChr

DisplayStringonStdout:swi0x02
Displaysastringintheoutputwindow.Seealso
themoregeneralswi 0x69below.

ldr
swi
...
MyString:

r0,=MyString
0x02
.asciz "Hello There\n"

HaltExecution:swi0x11
Stopstheprogram.

swi

SWI_Exit

AllocateBlockofMemoryonHeap:swi0x12
Obtainanewblockofmemoryfromtheheap
areaoftheprogramspace.Ifnomorememoryis
available,thespecialresult1isreturnedandthe
CbitissetintheCPSR.

20

mov
swi
ldr
str
...
Address:

r0,#28
@get 28 bytes
SWI_MeAlloc
r1,=Address
r0,[r1]
.word

ARMSimUserGuide

DeallocateAllHeapBlocks:swi0x13
Causesallpreviouslyallocatedblocksofmemory
intheheapareatobeconsideredasdeallocated
(thusallowingthememorytobereusedbyfuture
requestsformemoryblocks).

swi

DAlloc

OpenFile:swi0x66
Openingafileforinput.Assume the following in the data section:
InFileName: .asciz
InFileError: .asciz
.align
InFileHandle:.word

"Infile1.txt"
"Unable to open input file\n"
0

ThefollowinglinesofcodeopenthefilecalledInfile1.txtforinputandstoreitsfilehandle,
returnedinR0bytheopeningcall,intotheappropriatememorylocation:.
ldr
mov
swi
bcs
ldr
str

r0,=InFileName
r1,#0
SWI_Open
InFileError
r1,=InFileHandle
r0,[r1]

@
@
@
@
@
@

set Name for input file


mode is input
open file for input
if error?
load input file handle
save the file handle

Thustoopenafileforinput,oneneedstoloadtheaddressofthestringcontainingthefilenameintoR0,
settheinputmode=0intoR1,andexecutetheSWIinstructionwith0x66asoperand.Bytestingthe
carrybituponreturnusingtheBCSinstruction,onemakessurethatthefilehasbeenopenedproperly,
otherwiseamessageshouldbeprintedandtheprogramshouldexit.
Openingafileforoutput.Assume the following in the data section:
OutFileName: .asciz
OutFileError:.asciz
.align
OutFileHandle:.word

"Outfile1.txt"
"Unable to open output file\n"
0

ThefollowinglinesofcodeopenthefilecalledOutfile1.txtforoutputandstoreitsfilehan
dle,returnedinR0bytheopeningcall,intotheappropriatememorylocation:.
ldr
mov
swi
bcs
ldr
str

r0,=OutFileName
r1,#1
SWI_Open
OutFileError
r1,=OutFileHandle
r0,[r1]

@
@
@
@
@
@

set Name for output file


mode is output
open file for output
if error ?
load output file handle
save the file handle

Thustoopenafileforoutput,oneneedstoloadtheaddressofthestringcontainingthefilenameinto
R0,settheoutputmode=1intoR1,andexecutetheSWIinstructionwith0x66asoperand.Bytesting
thecarrybituponreturnusingtheBCSinstruction,onemakessurethatthefilehasbeenopenedprop
erly,orelseamessageshouldbeprintedandtheprogramshouldexit.

21

ARMSim#UserGuide

Summaryoftheswi0x66fileopeninginstruction.

Opensatextfileforinputoroutput.Thefile
nameispassedviar0.Registerr1specifiesthefile
accessmode.Ifr1=0,anexistingtextfileistobe
openedforinput.Ifr1=1,afileisopenedforout
put(ifthatfileexistsalready,itwillbeoverwrit
ten,otherwiseanewfileiscreated).Ifr1=2,an
existingtextfileisopenedinappendmode,so
thatanynewtextwrittentothefilewillbeadded
attheend.
Ifthefileisopenedsuccessfully,apositivenum
ber(thefilehandle)isreturnedinr0.Otherwise,
aresultof1isreturnedandtheCbitisset.

ldr
r0,=InFileName
mov
r1,#0
@ input mode
swi
SWI_Open
bcs
NoFileFound
ldr
r1,=InFileHandle
str
r0,[r1]
...
ldr
r0,=OutFileName
mov
r1,#1
@ output mode
swi
SWI_Open
bcs
NoFileFound
ldr
r1,=OutFileHandle
str
r0,[r1]
...
OutFileHandle: .word 0
InFileHandle: .word 0
InFileName: .asciz "Infile1.txt"
OutFileName: .asciz "Outfile1.txt"

Note:Thedefaultlocationforthefileisthesamefolderastheassemblersourcecodefile.Ifanotherloca
tionisdesired,afullpathtothefilelocationcanbeused.Forexample,thecodeshownbelowopens(or
creates)atextfileintheWindowsTemporarydirectory.
ldrr0,PathName
movr1,#1 @ output mode
swiSWI_Open
...
PathName:
.asciz "C:\\TEMP\\MyFile.txt"

CloseFile:swi0x68
Attheendofexecutionafileshouldbeproperlyclosed,orelseitmaybeinaccessibletootherapplica
tions.Thefollowinglinesofcodeshowhowtocloseboththeinputandoutputfilesusedasexamples
above.

Closesapreviouslyopenedfile.Unlessafileis
closed,itoftencannotbeinspectedoreditedby
anotherprogram(e.g.TextPad).

@ load the file handle


ldr
r0,=InFileHandle
ldr
r0,[r0]
swi
SWI_Close
@ load the file handle
ldr
r0,=OutFileHandle
ldr
r0,[r0]
swi
SWI_Close

WriteStringtoaFile:swi0x69
Assumeyouhavethefollowinginyourdatasection:
MatMsg:

22

.asciz

"\nThis is the resulting matrix:\n"

ARMSimUserGuide

AlsoassumethatanoutputfilehasbeenopenedasshownaboveandthatitsnameisstoredinOutFileNameanditsfilehandleisstoredinOutFileHandle.
Thenthefollowinglinesofcodeprintthestring\nThis is the resulting matrix:\nto
theoutputfileopenedasshownabove.Thestringisprecededandfollowedbyanewlinesincethechar
acter\nisembeddedattheendofthestring.
ldrr0,=OutFileHandle@ load the output file handle
ldrr0,[r0]
@ R0 = file handle
ldrr1,=MatMsg
@ R1 = address of string
swiSWI_PrStr
@ output string to file
Writesthesuppliedstringtothecurrentposition
intheopenoutputfile.Thefilehandle,passedin
r0,musthavebeenobtainedbyanearliercallto
theOpenFileswioperation.

ldr r0,=OutFileHandle
ldr r0,[r0]
ldr r1,=TextString
swi 0x69
bcs WriteError
...
TextString: .asciz "Answer = "

Note:Thespecialfilehandlevalueof1canbe
usedtowriteastringtotheStdoutoutputwin
dowofARMSim#(givingthesamebehaviouras
swi 0x02).Abriefexampleappearsonthe
right.

mov r0,#1
ldr r1,=Message
swi 0x69
@ display message
...
Message: .asciz "Hello There\n"

ReadStringfromaFile:swi0x6a
Readsastringfromafile.Theinputfileisidenti
fiedbyafilehandlepassedinR0.R1isthe
addressofanareaintowhichthestringistobe
copied.R2isthemaximumnumberofbytesto
storeintomemory.Onelineoftextisreadfrom
thefileandcopiedintomemoryandanullbyte
terminatorisstoredattheend.Thelineistrun
catedifitistoolongtostoreinmemory.The
resultreturnedinr0isthenumberofbytes
(includingthenullterminator)storedinmemory.

ldr r0,=InFileHandle
ldr r0,[r0]
ldr r1,=CharArray
mov r2,#80
swi 0x6a
bcs ReadError
...
InFileHandle: .word 0
CharArray: .skip 80

WriteIntegertoaFile:swi0x6b
Convertsthesignedintegervaluepassedinr1to
astringandwritesthatstringtothefileidentified
bythefilehandlepassedinr0.Assumesthatan
outputfilehasbeenopenedandthatitsnameis
storedinOutFileNameanditsfilehandleis
storedinOutFileHandle.Thelinesofcode
ontherightprinttheinteger42containedinreg
isterR1totheopenedoutputfile.

ldr
ldr
mov
swi

r0,=OutFileHandle
r0,[r0]
r1,#42
SWI_PrInt

23

ARMSim#UserGuide

Note:Thespecialfilehandlevalueof1canbe
usedtowritetheintegertotheStdoutoutput
window.Anexampleappearsontheright.

mov r0,#1
mov r1,#99
swi 0x6b ; display 99

ReadIntegerfromaFile:swi0x6c
Readsasignedintegerfromafile.Thefileis
identifiedbythefilehandlepassedinr0.The
resultisreturnedinr0.
Ifaproperlyformattednumberisnotfoundin
theinput,theCbitissetandr0isunchanged.By

testing the carry bit upon return using the BCS


instruction, one makes sure that the integer has
been read properly.

ldr
ldr
swi
bcs
@ the
...

r0,=InputFileHandle
r0,[r0]
0x6c
ReadError
integer is now in r0

9. SWIOperationsforOtherPlugIns:theEmbestBoardPlugIn
TheSWIcodesnumberedgreaterthan255havespecialpurposes.Theyaremainlyusedforinteraction
withPluginmoduleswhichcanbeloadedwiththeARMSim#simulator.Table5providesacurrentlist
ofthesecodesastheyareusedintheEmbestBoardPluginView.Examplesoftheirusefollowwithillus
trationsofthecorrespondingcomponent.TheuseofEQUisstronglyadvisedtosubstitutetheactual
numericalcodevalues.Examplesofcodeisalsoprovidedattheendofthesection.
AdiagramrepresentingschematicallythefeaturesoftheEmbestboardisshowninFigure13.

A 8-segment
display
for output

Two LED lights


for output

Two buttons for input

Left

Right

A small display screen


for output with 40 columns
and 15 lines available

10

11

12

13

14

15

A Keyboard for input

Figure 13: A diagrammatic view of the available controls and displays on the
Embest Board View
Thereare5maincomponentsinthisviewavailableforprogramming:

1. One 8-segment display (output).


2. Two red LED lights (output).
24

ARMSimUserGuide

3. Two black buttons (input).


4. Sixteen blue buttons arranged in a keyboard 4 x 4 grid (input).
5. One LCD display screen, which is a grid of 40 columns by 15 rows of individual cells. The coordinates for each LCD cell are specified by a {column, row} pair. The top-left cell has coordinates {0,0},
while the bottom-right cell has coordinates {39,14}. Each cell can contain exactly one ASCII character.
Table5.SWIoperationsgreaterthan0xFFascurrentlyusedfortheEmbestboardPlugIn
Opcode

DescriptionandAction

Inputs

Outputs

swi 0x200

Lightupthe8Segment
Display.

r0:the8segmentPattern Theappropriatesegmentslight
(seebelowinFigure14for uptodisplayanumberora
details)
character

swi 0x201

LightupthetwoLEDs.

r0:theLEDPattern,
where:
LeftLEDon=0x02
RightLEDon=0x01
BothLEDson=0x03
(i.e.thebitsinposition0
and1ofr0musteachbe
setto1appropriately)

swi 0x202

CheckifoneoftheBlack None
Buttonshasbeenpressed.

r0=theBlackButtonPattern,
where:
Leftblackbuttonpressed
returnsr0=0x02;
Rightblackbuttonpressed
returnsr0=0x01;
(i.e.thebitsinposition0and1
ofr0getassignedtheappropri
atevalues).

swi 0x203

CheckifoneoftheBlue
None(seebelowinFig
Buttonshasbeenpressed. urefordetails)

r0=theBlueButtonPattern(see
belowinFigure).

swi 0x204

Displayastringonthe
LCDscreen

EithertheleftLEDison,orthe
right,orboth

r0:xpositioncoordinate Thestringisdisplayedstarting
ontheLCDscreen(039); atthegivenpositionoftheLCD
r1:ypositioncoordinate screen.
ontheLCDscreen(014);
r2:Addressofanullter
minatedASCIIstring.
Note:(x,y)=(0,0)isthetop
leftand(0,14)isthebot
tomleft.Thedisplayis
limitedto40characters
perline.

25

ARMSim#UserGuide

Table5.SWIoperationsgreaterthan0xFFascurrentlyusedfortheEmbestboardPlugIn
Opcode

DescriptionandAction

Inputs

Outputs

swi 0x205

Displayanintegeronthe
LCDscreen

r0:xpositioncoordinate Thestringisdisplayedstarting
ontheLCDscreen(039); atthegivenpositionoftheLCD
r1:ypositioncoordinate screen.
ontheLCDscreen(014);
r2:integertoprint.
Note:(x,y)=(0,0)isthetop
leftand(0,14)isthebot
tomleft.Thedisplayis
limitedto40characters
perline

swi 0x206

Clearthedisplayonthe
LCDscreen

None

swi 0x207

Displayacharacteronthe r0:xpositioncoordinate Thestringisdisplayedstarting


LCDscreen
ontheLCDscreen(039); atthegivenpositionoftheLCD
r1:ypositioncoordinate screen.
ontheLCDscreen(014);
r2:thecharacter.
Note:(x,y)=(0,0)isthetop
leftand(0,14)isthebot
tomleft.Thedisplayis
limitedto40characters
perline

swi 0x208

Clearonelineinthedis
playontheLCDscreen

BlankLCDscreen.

r0:linenumber(ycoordi BlanklineontheLCDscreen.
nate)ontheLCDscreen

9.0.1DetailedDescriptionsandExamplesforSWICodesfortheEmbestBoardPlugin
Setthe8SegmentDisplaytolightup:swi0x200
Theappropriatesegmentslightuptodisplayanumberoracharacter.Thepatternofsegmentstobelit
upisassignedtoregisterR0beforethecalltoswi0x200.Figure14showsthearrangementsofseg
ments,andanexamplefollows.Eachsegmentislogicallylabelledanditsbytecodeisshowninthelist
inTable6.Forexample,inFigure14,todisplaythenumber3,segmentsA,B,C,DandF
mustbeilluminated.ThecodetobeassignedtoR0iscomputedbythelogicalORoftheindividualbyte
codes.

26

ARMSimUserGuide

Figure14.ThePatternforthe8SegmentDisplay
A

Display byte
values

Example: number 3 plus dot

Table 6: Segmen
t byte values

0x80

0x40

0x20

0x10

0x08

0x04

0x02

0x01

Asanexample,thenumber3plusthe
righthanddotwouldhaveapattern
valuecomputedasthelogicalORofthe
valuesofthesegmentsA,B,C,D,F,Pto
formtheinteger:0x80 | 0x40 |

0x20 | 0x08 | 0x02 | 0x10 =


0xFA, tobeassignedtor0.

Belowsomesegmentsofcodeareshownasexamplesforthe8segmentDisplay.The.equstatements
areusefulforaccessingthebytevaluesassociatedwiththelabelsofeachsegmentasshowninFigure14.
AnexampleofapossibledeclarationofdataisalsogiveninFigure16forthedisplayofintegers,where
thebytevaluesrepresentingaparticularnumberarealreadyORedtogetherwithinthearraydata
structureandcanbeindexedappropriately.Itmaybeeasiertouseadatadeclarationforanarrayof
wordsandthenindexintoit.Eachelementcanbeinitializedtocontainthevaluerepresentinganumber
byhavingtheappropriatebytevaluesORedtogether.

Use.equstatementstosetupthebytevalue
ofeachsegmentoftheDisplay.

.equ
.equ
.equ
.equ
.equ
.equ
.equ
.equ

SEG_A,0x80
SEG_B,0x40
SEG_C,0x20
SEG_D,0x08
SEG_E,0x04
SEG_F,0x02
SEG_G,0x01
SEG_P,0x10

Figure 15: Possible data declaration for byte values for segments

27

ARMSim#UserGuide

Apossibledatadec
larationforanarray
ofwordswhichcan
beindexedtoobtain
theappropriate
valueforanumber
{0,...,9}tobedis
played.

Digits:
.word
.word
.word
.word
.word
.word
.word
.word
.word
.word
.word

SEG_A|SEG_B|SEG_C|SEG_D|SEG_E|SEG_G @0
SEG_B|SEG_C
@1
SEG_A|SEG_B|SEG_F|SEG_E|SEG_D @2
SEG_A|SEG_B|SEG_F|SEG_C|SEG_D @3
SEG_G|SEG_F|SEG_B|SEG_C @4
SEG_A|SEG_G|SEG_F|SEG_C|SEG_D @5
SEG_A|SEG_G|SEG_F|SEG_E|SEG_D|SEG_C @6
SEG_A|SEG_B|SEG_C
@7
SEG_A|SEG_B|SEG_C|SEG_D|SEG_E|SEG_F|SEG_G @8
SEG_A|SEG_B|SEG_F|SEG_G|SEG_C @9
0
@Blank display

Figure 16: Possible data declaration forinteger patterns


Anexampleofapossibleroutinetodisplayanumberinthe8segmentDisplayusingthedeclarations
givenaboveisshowninFigure17.

RegisterR0andR1areinput
parameters,whereR0contains
theintegertobedisplayedand
R1contains1todisplaythe
Psegment,or0otherwise.

@ *** Display8Segment (Number:R0; Point:R1) ***


@ Displays the number 0-9 in R0 on the
@ LED 8-segment display
@ If R1 = 1, the point is also shown
[1]Display8Segment:
stmfd
sp!,{r0-r2,lr}
[2]
ldr
r2,=Digits
[3]
ldr
r0,[r2,r0,lsl#2]
[4]
tst
r1,#0x01
@if r1=1,
[5]
orrne
r0,r0,#SEG_P
@then show P
[6]
swi
0x200
[7]
ldmfd
sp!,{r0-r2,pc}

Figure 17: A possible Display8Segment routine


Inline[3],registerr0isassignedthebytevaluecorrespondingtotheindexedelementofthearraydigits
fromFigure16.Forexample,todisplaythenumber3,afterexecutionofline[2],theinputregisterr0
shouldcontaintheintegervalue3andregisterr2containstheaddressofthearrayDigits.Then
thecomputationimpliedby[r2,r0,lsl#2]adds12bytestotheaddresscurrentlyinr2(i.e.r0
shiftedleftby2positions,whichevaluatesto3x4=12)andloadsthewordinposition3ofthearray,
namely:.word SEG_A|SEG_B|SEG_F|SEG_C|SEG_D.Infact,thisusesthesegments
A,B,C,D,F todisplaythecorrectnumber.Inline[4]thecontentofr1istested.Ifr1=1thenthe
segmentPisaddedtothedisplay,withitsvalueORedwiththepreviousonesinr0.

28

ARMSimUserGuide

SetthetwoLEDstolightup:swi0x201

LightuptheLEDs:theleftortherightorboth,
accordingtothevaluesuppliedbyr0.

mov
swi
mov
swi
mov
swi

r0,#0x02
0x201
r0,#0x01
0x201
r0,#0x03
0x201

@ left LED on
@ right LED on
@ both LEDs on

CheckifoneoftheBlackButtonshasbeenpressed:swi0x202
Thecallwithswi0x202setsthecontentofr0
as:r0=2iftheleftblackbuttonwaspressedor
r0=1,iftherightblackbuttonwaspressed.Test
ingr0enablesfollowupactions.

swi
cmp
beq
bal

0x202
r0,#0x02
ActOnLeftBlack
ActOnRightBlack

CheckifoneoftheBlueButtonshasbeenpressed:swi0x203
Afterthecallwithswi0x203,testthecontent
ofr0.Thenumberinr0correspondstotheposi
tionofthebluebuttonasdepictedinFigure.For
example,ifr0=2thenthebluebuttoninposi
tion2waspressed.

10

11

12

13

14

15

swi
0x203
cmp
r0,#1
cmp
r0,#2
cmp
r0,#3
. . . . .

Thekeypadwith16blue
buttonsasdepictedin
theboardview.

A Keyboard for input


Theyarearrangedsuchthateachbuttonhasacorrespondingbitpositioninthe16bitlowerportion
ofawordinregisterR0afterthecalltoswi0x203topollthekeypad.Thenumberlabelsplacedin
thefigure,whichdonotappearontherealkeypad,alsorepresentthecorrespondingbitpositionas
returnedinR0.Whenabuttonispressed,thecorrespondingbitisset.
Forexample,whenthebuttoninposition1ispressed,theswi0x203instructionreturnsr0 =

0x02, thatis,
r0 = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
inbinary,wherethebitinposition1hasbeenset.

Figure18.The Pattern for the Blue Buttons

29

ARMSim#UserGuide

DisplayastringontheLCDscreen:swi0x204
Displaythestringwhoseaddressissuppliedin

r2ontheLCDscreenatposition(x,y),where
r0=xandr1=y.Inthisexample,r0=4and
r1=y=1(thatis,line1atcolumn4)

mov r0,#4
mov r1,#1
ldr r2,=Message
swi 0x204
@ display message
...
Message: .asciz "Hello There\n"

DisplayanintegerontheLCDscreen:swi0x205
DisplayanintegerontheLCDscreen.Theinte
gerisinr2,tobeshownatposition(x,y),where
r0=xandr1=y.Inthisexample,r2=23,r0=4and
r1=y=1(thatis,line1atcolumn4displays23)

mov
mov
mov
swi

r0,#4
r1,#1
r2,#23
0x205

@ display integer

ClearthedisplayontheLCDscreen:swi0x206
ClearthewholeLCDscreen.

swi

0x206

@ clear screen

DisplayacharacterontheLCDscreen:swi0x207
DisplayacharacterontheLCDscreen.Thechar
acterisinr2,tobeshownatposition(x,y),
whereherer0=xandr1=y.Inthisexample,
r2=Z,r0=4andr1=y=1(thatis,line1atcolumn
4displaysZ).

mov
mov
mov
swi

r0,#4
r1,#1
r2,#Z
0x207

@display char

ClearonelineinthedisplayontheLCDscreen:swi0x208
ClearonlyonelineontheLCDscreen,wherethe
linenumberisgiveninr0.

ldr
swi

r0,#5
0x208

@clear line 5

10.CodeExamples
10.1Example:PrintStrings,CharactersandIntegerstoStdoutusingSWIInstructionsforI/O
@@@ PRINT STRINGS, CHARACTERS, INTEGERS TO STDOUT
.equ SWI_PrChr,0x00
@ Write an ASCII char to Stdout
.equ SWI_PrStr, 0x69 @ Write a null-ending string
.equ SWI_PrInt,0x6b
@ Write an Integer
.equ Stdout, 1
@ Set output mode to be Output View
.equ SWI_Exit, 0x11
@ Stop execution
.global _start
.text
_start:
@ print a string to Stdout
mov R0,#Stdout
@ mode is Stdout
30

ARMSimUserGuide

ldr R1, =Message1


@ load address of Message1
swi SWI_PrStr
@ display message to Stdout
@ print a new line as a string to Stdout
mov R0,#Stdout
@ mode is Stdout
ldr r1, =EOL
@ end of line
swi SWI_PrStr
@ print a character to the screen
mov R0, #'A
@ R0 = char to print
swi SWI_PrChr
@ print a blank character (from data)
ldr r0,=Blank
ldrb r0,[r0]
@ R0 = char to print = blank
swi SWI_PrChr
@ print a second character to Stdout
mov R0, #'B
@ R0 = char to print
swi SWI_PrChr
@ print a new line as a character to Stdout
ldr r0,=NewL
ldrb r0,[r0]
@ R0 = char to print = new line
swi SWI_PrChr
@ print an integer to Stdout
mov R0,#Stdout
@ mode is Output view
mov r1, #42
@ integer to print
swi SWI_PrInt
@ print a new line as a string to Stdout
mov R0,#Stdout
@ mode is Output view
ldr r1, =EOL
@ end of line
swi SWI_PrStr
swiSWI_Exit @ stop executing: end of program
.data
Message1: .asciz"Hello World!"
EOL:
.asciz
"\n"
NewL:
.ascii
"\n"
Blank:
.ascii
" "
.end

10.2Example:Openandclosefiles,readandprintintegersusingSWIInstructionsforI/O
@@@ OPEN INPUT FILE, READ INTEGER FROM FILE, PRINT IT, CLOSE INPUT FILE
.equ SWI_Open, 0x66
@open a file
.equ SWI_Close,0x68
@close a file
.equ SWI_PrChr,0x00
@ Write an ASCII char to Stdout
.equ SWI_PrStr, 0x69
@ Write a null-ending string
.equ SWI_PrInt,0x6b
@ Write an Integer
.equ SWI_RdInt,0x6c
@ Read an Integer from a file
.equ Stdout, 1
@ Set output target to be Stdout
.equ SWI_Exit, 0x11
@ Stop execution
.global _start
.text
_start:
@ print an initial message to the screen
31

ARMSim#UserGuide

mov R0,#Stdout
@print an initial message
ldr R1, =Message1
@ load address of Message1 label
swi SWI_PrStr
@ display message to Stdout
@ == Open an input file for reading =============================
@ if problems, print message to Stdout and exit
ldr r0,=InFileName
@ set Name for input file
mov r1,#0
@ mode is input
swi SWI_Open
@ open file for input
bcs InFileError
@ Check Carry-Bit (C): if= 1 then ERROR
@ Save the file handle in memory:
ldr r1,=InputFileHandle
@ if OK, load input file handle
str r0,[r1]
@ save the file handle
@ == Read integers until end of file =============================
RLoop:
ldr r0,=InputFileHandle
@ load input file handle
ldr r0,[r0]
swi SWI_RdInt
@ read the integer into R0
bcs EofReached
@ Check Carry-Bit (C): if= 1 then EOF reached
@ print the integer to Stdout
mov r1,r0
@ R1 = integer to print
mov R0,#Stdout
@ target is Stdout
swi SWI_PrInt
mov R0,#Stdout
@ print new line
ldr r1, =NL
swi SWI_PrStr
bal RLoop
@ keep reading till end of file
@ == End of file ===============================================
EofReached:
mov R0, #Stdout
@ print last message
ldr R1, =EndOfFileMsg
swi SWI_PrStr
@ == Close a file ===============================================
ldr R0, =InFileHandle
@ get address of file handle
ldr R0, [R0]
@ get value at address
swi SWI_Close
Exit:
swiSWI_Exit
@ stop executing
InFileError:
mov R0, #Stdout
ldr R1, =FileOpenInpErrMsg
swi SWI_PrStr
bal Exit
@ give up, go to end
.data
.align
InFileHandle:
.skip
4
InFileName:
.asciz
"whatever.txt"
FileOpenInpErrMsg: .asciz "Failed to open input file \n"
EndOfFileMsg:
.asciz
"End of file reached\n"
ColonSpace:
.asciz": "
NL:
.asciz
"\n "
@ new line
32

ARMSimUserGuide

Message1:
.end

.asciz

"Hello World! \n"

10.3Example:UsefulpatternsforusingSWIInstructionsforaPlugIn
ThisisapossibleinitialtemplatetosettheusefulSWIcodesfortheEmbestBoardPlugin
.equ SWI_SETSEG8,
0x200
@display on 8 Segment
.equ SWI_SETLED,
0x201
@LEDs on/off
.equ SWI_CheckBlack, 0x202
@check Black button
.equ SWI_CheckBlue,
0x203
@check press Blue button
.equ SWI_DRAW_STRING, 0x204
@display a string on LCD
.equ SWI_DRAW_INT,
0x205
@display an int on LCD
.equ SWI_CLEAR_DISPLAY,0x206
@clear LCD
.equ SWI_DRAW_CHAR,
0x207
@display a char on LCD
.equ SWI_CLEAR_LINE, 0x208
@clear a line on LCD
.equ SWI_EXIT,
0x11
@terminate program
.equ SWI_GetTicks,
0x6d
@get current time
.equ SEG_A, 0x80
@ patterns for 8 segment display
.equ SEG_B, 0x40
@byte values for each segment
.equ SEG_C, 0x20
@of the 8 segment display
.equ SEG_D, 0x08
.equ SEG_E, 0x04
.equ SEG_F, 0x02
.equ SEG_G, 0x01
.equ SEG_P, 0x10
.equ LEFT_LED,
0x02
@bit patterns for LED lights
.equ RIGHT_LED,
0x01
.equ LEFT_BLACK_BUTTON,0x02
@bit patterns for black buttons
.equ RIGHT_BLACK_BUTTON,0x01
@and for blue buttons
.equ BLUE_KEY_00, 0x01
@button(0)
.equ BLUE_KEY_01, 0x02
@button(1)
.equ BLUE_KEY_02, 0x04
@button(2)
.equ BLUE_KEY_03, 0x08
@button(3)
.equ BLUE_KEY_04, 0x10
@button(4)
.equ BLUE_KEY_05, 0x20
@button(5)
.equ BLUE_KEY_06, 0x40
@button(6)
.equ BLUE_KEY_07, 0x80
@button(7)
.equ BLUE_KEY_00, 1<<8
@button(8) - different way to set
.equ BLUE_KEY_01, 1<<9
@button(9)
.equ BLUE_KEY_02, 1<<10
@button(10)
.equ BLUE_KEY_03, 1<<11
@button(11)
.equ BLUE_KEY_04, 1<<12
@button(12)
.equ BLUE_KEY_05, 1<<13
@button(13)
.equ BLUE_KEY_06, 1<<14
@button(14)
.equ BLUE_KEY_07, 1<<15
@button(15)

10.4Example:Subroutinetoimplementawaitcyclewiththe32bittimer
@ Wait(Delay:r2) wait for r2 milliseconds
Wait:
stmfdsp!, {r0-r1,lr}
33

ARMSim#UserGuide

swi SWI_GetTicks
mov r1, r0
WaitLoop:
swi SWI_GetTicks
subs r0, r0, r1
rsbltr0, r0, #0
cmp r0, r2
blt WaitLoop
WaitDone:
ldmfdsp!, {r0-r1,pc}

@ R1: start time

@ R0: time since start


@ fix unsigned subtract

10.5Example:Subroutinetocheckforanintervalwitha15bittimer(EmbestBoard)
ThetimerinARMSim#isimplementedusinga32bitquantityandthecurrenttime(asnumberofticks)
isaccessedbyusingtheSWIinstructionwithoperand0x6d(thecorrespondingEQUissettobe
SWI_GetTicks).ItreturnsinR0thenumberofticksinmilliseconds.Ontheotherhand,thetimeron
theEmbestboardusesonlya15bitquantityandthiscancauseaproblemwithrollover.Assumeone
checksthetimeatastartingpointT1andthenlateratpointT2,andoneneedstotestwhetheracertain
amountoftimehaspasse.IdeallycomputingT2T1andcomparingittothedesiredintervalisenough.
TherangeinARMSim#witha32bittimerisbetween0and2321=4,294,967,295.Asmilliseconds,this
givesarangeofabout71,582minutes,whichisnormallyenoughtoensurethatonecankeepchecking
theintervalsT2T1withoutT2evergoingoutofrangeinasingleprogramexecution.
TherangeintheEmbestboardwitha15bittimerisbetween0and2151=32,767,givingarangeofonly
32seconds.WhencheckingtheintervalT2T1,thereisnoproblemaslongasT2>T1andT2<32,767.
HoweveritcanhappenthatT1isobtainedclosetothetopoftherangeandT1subsequentlyhasavalue
aftertherollover,thusT2<T1.Itisnotenoughtoflipthesignasthefollowingexamplesshow.
LetT1=1,000andT2=15,000.ThenT2T1=14,000givesthecorrectanswerfortheinterval.Subse
quentlyletT1=30,000andthelaterT2=2,000(aftethetimerhasrolledover).IfonesimplycalculatesT2
T1=28,000oreventriestogetitsabsolutevalue,theanswerisincorrect.Thevaluefortheinterval
shouldbe:(32,767T1)+T2=32,76730,000+2,000=4,767,whichrepresentsthecorrectnumberofticks
whichpassedbetweenT1andT2.
Twothingsneedtobedoneforcorrectprogramming.Firstofallthetimingvalueobtainedin32bitsin
ARMSim#shouldbemaskedtobeonlya15bitquantity,sothatthecodewillworkbothinthesimula
torandontheboard.Secondly,thetestingfortheintervalincludeatestforrollover.
.equ Sec1, 1000
@ 1 seconds interval
.equ Point1Sec, 100
@ 0.1 seconds interval
.equ EmbestTimerMask, 0x7fff
@ 15 bit mask for timer values
.equ Top15bitRange,0x0000ffff
@(2^15) -1 = 32,767
.text
_start:
movr6,#0
@ counting the loops (not necessary)
ldrr8,=Top15bitRange
ldrr7,=EmbestTimerMask
ldrr10,=Point1Sec
SWISWI_GetTicks @Get current time T1
movr1,r0
@ R1 is T1
andr1,r1,r7
@ T1 in 15 bits
RepeatTillTime:
addr6,r6,#1
@ count number of loops (not necessary)
34

ARMSimUserGuide

SWISWI_GetTicks @Get current time T2


movr2,r0
@ R2 is T2
andr2,r2,r7
@ T2 in 15 bits
cmpr2,r1
@ is T2>T1?
bgesimpletime
subr9,r8,r1
@ TIME= 32,676 - T1
addr9,r9,r2
@
+ T2
balCheckInt
simpletime:
subr9,r2,r1
@ TIME = T2-T1
CheckInt:
cmpr9,r10
@is TIME < interval?
bltRepeatTillTime
swiSWI_EXIT
.end

10.6swiSWI_EXITExample:UsingtheSWIInstructionsforaPlugIn(EmbestBoardView)
@ Demonstration of Embest S3CE40 development board view
@ ===== Assume the EQU declaration from previous examples
@Clear the board, clear the LCD screen
swi SWI_CLEAR_DISPLAY
@Both LEDs off
mov r0,#0
swi SWI_SETLED
@8-segment blank
mov r0,#0
swi SWI_SETSEG8
@draw a message to the lcd screen on line#1, column 4
mov r0,#4
@ column number
mov r1,#1
@ row number
ldr r2,=Welcome @ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
@display the letter H in 7segment display
ldr r0,=SEG_B|SEG_C|SEG_G|SEG_E|SEG_F
swi SWI_SETSEG8
@turn on LEFT led and turn off RIGHT led
mov r0,#LEFT_LED
swi SWI_SETLED
@draw a message to the lcd screen on line#2, column 4
mov r0,#4
@ column number
mov r1,#2
@ row number
ldr r2,=LeftLED @ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
@Wait for 3 second
ldr r3,=3000
BL Wait
@turn on RIGHT led and turn off LEFT led
mov r0,#RIGHT_LED
swi SWI_SETLED
@draw a message to the lcd screen on line#2, column 4
35

ARMSim#UserGuide

mov r0,#4
@ column number
mov r1,#2
@ row number
ldr r2,=RightLED @ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
@Wait for 3 second
ldr r3,=3000
BL Wait
@turn on both led
mov r0,#(LEFT_LED|RIGHT_LED)
swi SWI_SETLED
@clear previous line 2
mov r0,#2
swi SWI_CLEAR_LINE
@draw a message to inform user to press a black button
mov r0,#6
@ column number
mov r1,#2
@ row number
ldr r2,=PressBlackL @ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
@wait for user to press a black button
mov r0,#0
LB1:
swi SWI_CheckBlack
@get button press into R0
cmp r0,#0
beq LB1
@ if zero, no button pressed
cmp r0,#RIGHT_BLACK_BUTTON
bne LD1
ldr r0,=SEG_B|SEG_C|SEG_F @right button, show -|
swi SWI_SETSEG8
mov r0,#RIGHT_LED
@turn on right led
swi SWI_SETLED
bal NextButtons
LD1:
@left black pressed
ldr r0,=SEG_G|SEG_E|SEG_F
@display |- on 8segment
swi SWI_SETSEG8
mov r0,#LEFT_LED
@turn on LEFT led
swi SWI_SETLED
NextButtons:
@Wait for 3 second
ldr r3,=3000
BL Wait
@Test the blue buttons 0-9 with prompting, then display
@number on 8-segment for 3 seconds. If >9, invalid.
@Draw a message to inform user to press a blue button
mov r0,#2
@clear previous line 2
swi SWI_CLEAR_LINE
mov r0,#6
@ column number
mov r1,#2
@ row number
ldr r2,=PressBlue
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
mov r4,#16
36

ARMSimUserGuide

BLUELOOP:
@wait for user to press blue button
mov r0,#0
BB1:
swi SWI_CheckBlue
@get button press into R0
cmp r0,#0
beq BB1
@ if zero, no button pressed
cmp r0,#BLUE_KEY_15
beq FIFTEEN
cmp r0,#BLUE_KEY_14
beq FOURTEEN
cmp r0,#BLUE_KEY_13
beq THIRTEEN
cmp r0,#BLUE_KEY_12
beq TWELVE
cmp r0,#BLUE_KEY_11
beq ELEVEN
cmp r0,#BLUE_KEY_10
beq TEN
cmp r0,#BLUE_KEY_09
beq NINE
cmp r0,#BLUE_KEY_08
beq EIGHT
cmp r0,#BLUE_KEY_07
beq SEVEN
cmp r0,#BLUE_KEY_06
beq SIX
cmp r0,#BLUE_KEY_05
beq FIVE
cmp r0,#BLUE_KEY_04
beq FOUR
cmp r0,#BLUE_KEY_03
beq THREE
cmp r0,#BLUE_KEY_02
beq TWO
cmp r0,#BLUE_KEY_01
beq ONE
cmp r0,#BLUE_KEY_00
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r1,#0
mov r0,#0
BL Display8Segment
bal CKBLUELOOP
ONE:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r1,#0
mov r0,#1
BL Display8Segment
37

ARMSim#UserGuide

bal CKBLUELOOP
TWO:
mov
swi
mov
mov
BL
bal
THREE:
mov
swi
mov
mov
BL
bal
FOUR:
mov
swi
mov
mov
BL
bal
FIVE:
mov
swi
mov
mov
BL
bal
SIX:
mov
swi
mov
mov
BL
bal
SEVEN:
mov
swi
mov
mov
BL
bal
EIGHT:
mov
swi
mov
mov
BL
bal
38

r0,#5
@clear previous line
SWI_CLEAR_LINE
r1,#0
r0,#2
Display8Segment
CKBLUELOOP
r0,#5
@clear previous line
SWI_CLEAR_LINE
r1,#0
r0,#3
Display8Segment
CKBLUELOOP
r0,#5
@clear previous line
SWI_CLEAR_LINE
r1,#0
r0,#4
Display8Segment
CKBLUELOOP
r0,#5
@clear previous line
SWI_CLEAR_LINE
r1,#0
r0,#5
Display8Segment
CKBLUELOOP
r0,#5
@clear previous line
SWI_CLEAR_LINE
r1,#0
r0,#6
Display8Segment
CKBLUELOOP
r0,#5
@clear previous line
SWI_CLEAR_LINE
r1,#0
r0,#7
Display8Segment
CKBLUELOOP
r0,#5
@clear previous line
SWI_CLEAR_LINE
r1,#0
r0,#8
Display8Segment
CKBLUELOOP

ARMSimUserGuide

NINE:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r1,#0
mov r0,#9
BL Display8Segment
bal CKBLUELOOP
TEN:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#6
@ column number
mov r1,#5
@ row number
ldr r2,=InvBlue
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
mov r1,#0
mov r0,#10
@ clear 8-segment
BL Display8Segment
bal CKBLUELOOP
ELEVEN:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#6
@ column number
mov r1,#5
@ row number
ldr r2,=InvBlue
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
mov r1,#0
mov r0,#10
@ clear 8-segment
BL Display8Segment
bal CKBLUELOOP
TWELVE:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#6
@ column number
mov r1,#5
@ row number
ldr r2,=InvBlue
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
mov r1,#0
mov r0,#10
@ clear 8-segment
BL Display8Segment
bal CKBLUELOOP
THIRTEEN:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#6
@ column number
mov r1,#5
@ row number
ldr r2,=InvBlue
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
mov r1,#0
mov r0,#10
@ clear 8-segment
BL Display8Segment
39

ARMSim#UserGuide

bal CKBLUELOOP
FOURTEEN:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#6
@ column number
mov r1,#5
@ row number
ldr r2,=InvBlue
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
mov r1,#0
mov r0,#10
@ clear 8-segment
BL Display8Segment
bal CKBLUELOOP
FIFTEEN:
mov r0,#5
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#6
@ column number
mov r1,#5
@ row number
ldr r2,=InvBlue
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
mov r1,#0
mov r0,#10
@ clear 8-segment
BL Display8Segment
CKBLUELOOP:
mov r0,#10
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#4
@clear previous line
swi SWI_CLEAR_LINE
mov r0,#1
@ display number of tests
mov r1,#4
ldr r2,=TestBlue
swi SWI_DRAW_STRING
mov r0,#10
mov r1,#4
mov r2,r4
swi SWI_DRAW_INT
subs r4,r4,#1
bne BLUELOOP
@give only 15 tests
@Prepare to exit: lst message and clear the board
@draw a message to the lcd screen on line#10, column 1
mov r0,#1
@ column number
mov r1,#10
@ row number
ldr r2,=Bye
@ pointer to string
swi SWI_DRAW_STRING @ draw to the LCD screen
@Turn off both LED's
ldr r0,=0
swi SWI_SETLED
@8-segment blank
mov r0,#0
swi SWI_SETSEG8
ldr r3,=2000
@delay a bit
40

ARMSimUserGuide

BL Wait
@Clear the LCD screen
swi SWI_CLEAR_DISPLAY
swi SWI_EXIT
@all done, exit
@ ===== Display8Segment (Number:R0; Point:R1)
@ Displays the number 0-9 in R0 on the 8-segment display
@ If R1 = 1, the point is also shown
Display8Segment:
stmfd
sp!,{r0-r2,lr}
ldr
r2,=Digits
ldr
r0,[r2,r0,lsl#2]
tst
r1,#0x01 @if r1=1,
orrne
r0,r0,#SEG_P
@then show P
swi
SWI_SETSEG8
ldmfd
sp!,{r0-r2,pc}
@ ===== Wait(Delay:r3) wait for r3 milliseconds
@ Delays for the amount of time stored in r3 for a 15-bit timer
Wait:
stmfd
sp!,{r0-r5,lr}
ldr
r4,=0x00007FFF
@mask for 15-bit timer
SWI
SWI_GetTicks
@Get start time
and
r1,r0,r4
@adjusted time to 15-bit
Wloop:
SWI
SWI_GetTicks
@Get current time
and
r2,r0,r4
@adjusted time to 15-bit
cmp
r2,r1
blt
Roll
@rolled above 15 bits
sub
r5,r2,r1
@compute easy elapsed time
bal
CmpLoop
Roll: sub
r5,r4,r1
@compute rolled elapsed time
add
r5,r5,r2
CmpLoop:cmp r5,r3
@is elapsed time < delay?
blt
Wloop
@Continue with delay
Xwait:ldmfd sp!,{r0-r5,pc}
@ ================================================
.data
Welcome:
.asciz
"Welcome to Board Testing"
LeftLED:
.asciz
"LEFT light"
RightLED:
.asciz
"RIGHT light"
PressBlackL: .asciz
"Press a BLACK button"
Bye:
.asciz
"Bye for now."
Blank:
.asciz
" "
Digits:
.word SEG_A|SEG_B|SEG_C|SEG_D|SEG_E|SEG_G @0
.word SEG_B|SEG_C @1
.word SEG_A|SEG_B|SEG_F|SEG_E|SEG_D @2
.word SEG_A|SEG_B|SEG_F|SEG_C|SEG_D @3
.word SEG_G|SEG_F|SEG_B|SEG_C @4
.word SEG_A|SEG_G|SEG_F|SEG_C|SEG_D @5
.word SEG_A|SEG_G|SEG_F|SEG_E|SEG_D|SEG_C @6
41

ARMSim#UserGuide

.word SEG_A|SEG_B|SEG_C @7
.word SEG_A|SEG_B|SEG_C|SEG_D|SEG_E|SEG_F|SEG_G @8
.word SEG_A|SEG_B|SEG_F|SEG_G|SEG_C @9
.word 0 @Blank display
PressBlue:
.asciz
"Press a BLUE button 0-9 only - 15 tests"
InvBlue:
.asciz
"Invalid blue button - try again"
TestBlue:
.asciz
"Tests ="
.end

42

You might also like