Vous êtes sur la page 1sur 47

TheARMSim#UserGuide1

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.
Thepurposeofthisuserguideistoexplainhowtousethetoolsandviewsprovidedby
ARMSim#.Inthisdocument,aviewisawindowdisplayedbytheARMSim#simulator
thatshowsthestateofsomeaspectoftheprogrambeingrun.Thescopeofthedocument
hasbeenlimitedtothefeaturesofthesimulator.ItdoesnotcoverARMassemblypro
grammingorcomputerarchitecture.Userswhoareunfamiliarwiththesetopicsshould
consultothermaterial,someofwhichislistedinthereferences.

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

1.LastupdatedJuly2010forARMSim#.191

ARMSim#UserGuide

TableofContents
1.
2.

3.

4.

5.

6.

7.
8.

9.
10.

11.

Overview ................................................................................................................................................................ 1
Features ................................................................................................................................................................... 3
2.1
Toolbar....................................................................................................................................................... 3
2.2
Views ......................................................................................................................................................... 3
SettinguptheSimulator ..................................................................................................................................... 6
3.1
DockingWindows ................................................................................................................................... 6
3.2
BoardControlsView:thepluginsandtheSWIinstructions ........................................................... 7
3.3
Fonts .......................................................................................................................................................... 7
3.4
Colours ...................................................................................................................................................... 7
GettingStarted ...................................................................................................................................................... 7
4.1
CreatingaFile .......................................................................................................................................... 7
4.2
OpeningandLoadingaFile................................................................................................................... 7
4.3
RunningaProgram ................................................................................................................................. 8
4.4
StoppingaProgram ................................................................................................................................ 8
4.5
CodeView ................................................................................................................................................ 8
4.6
RegistersView.......................................................................................................................................... 9
DebuggingaProgram ........................................................................................................................................ 10
5.1
SteppingThroughaProgram .............................................................................................................. 10
5.2
RestartingaProgram ............................................................................................................................ 10
5.3
ReloadingaProgram ............................................................................................................................ 10
5.4
OpeningMultipleFiles ......................................................................................................................... 10
5.5
Breakpoints............................................................................................................................................. 11
AdditionalViews ................................................................................................................................................ 12
6.1
WatchView............................................................................................................................................. 12
6.2
MemoryView......................................................................................................................................... 13
6.3
OutputView........................................................................................................................................... 15
6.4
StackView .............................................................................................................................................. 16
6.5
CacheViews ........................................................................................................................................... 17
SomeARMSim#Limitations ............................................................................................................................ 19
SWICodesforI/OinARMSim#:thefirstPlugin....................................................................................... 20
8.1
BasicSWIOperationsforI/O ............................................................................................................... 20
8.1.1
Detailed Descriptions and Examples for SWI Codes for I/O .................................................... 21
SWIOperationsforOtherPlugIns:theEmbestBoardPlugIn................................................................ 25
9.1
DetailsandExamplesforSWICodesfortheEmbestBoardPlugin............................................. 27
CombiningCandARMCode .......................................................................................................................... 31
10.1
CompilingaProgramwithCandARM ............................................................................................ 31
10.2
CompilingaCProgramtoARMwithCodeSourcery .................................................................... 32
10.3
LinkingandExecutingthePrograminARMSim# ........................................................................... 33
10.4
ARMParameterPassingConventions................................................................................................ 33
10.5
Example2forcombiningCandARM ............................................................................................... 34
CodeExamples .................................................................................................................................................... 34
11.1
Example:PrintStrings,CharactersandIntegerstoStdoutusingSWIInstructionsforI/O....... 34
11.2
Example:Openandclosefiles,readandprintintegersusingSWIInstructionsforI/O ............ 36
11.3
Example:UsefulpatternsforusingSWIInstructionsforaPlugIn............................................... 37
11.4
Example:Subroutinetoimplementawaitcyclewiththe32bittimer ......................................... 38

ARMSim#UserGuide

11.5
11.6

Example:Subroutinetocheckforanintervalwitha15bittimer(EmbestBoard) ..................... 38
Example:UsingtheSWIInstructionsforaPlugIn(EmbestBoardView) ................................... 39

ARMSim#UserGuide

2. Features
TheARMSim#toolbarandviewsgivetheuseraccesstoavarietyoftoolstodebugandmonitorARM
assemblylanguageprograms.Thefollowingsectionsdescribethecontrolsprovidedbythetoolbarand
theinformationdisplayedintheviews.

2.1Toolbar
TheARMSim#toolbarprovideseasyaccesstomanyofthe
debuggingfeaturesofthesimulator,especiallythosefea
turesthatallowtheusertocontroltheexecutionofapro
gram.Thefunctionsofthebuttonsonthetoolbarare
summarizedinTable1.

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,asshowninFigure1andsummarizedinTable2.
AllviewsareenabledbyselectingtheappropriateitemfromViewmenuabovethetoolbar.Allviews,
excepttheCodeView,appearindockingwindows(seeFigure2).Theirplacementandmovementis
describedbelow.

ARMSim#UserGuide

Figure1.Views

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.

ARMSim#UserGuide

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

3.1DockingWindows
Allviews,excepttheCodeView,appearindockingwindows(seeFigure2).Eachwindowcanbe
dockedalonganysideoftheapplicationwindow,oritcanfloatabovetheapplicationwindow.Inaddi
tion,eachdockingwindowcanbedisplayedorhidden,andeachdisplayedwindowhasanautohide
option.
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

Figure2.DockingWindows

ARMSim#UserGuide

3.2BoardControlsView:thepluginsandtheSWIinstructions
WhileARMSim#canbeusedcompletelyonitsown,theextrafeaturesofpluginsandI/Oinstructions
canbeextremelyuseful.Theyhavetobeenabledexplicitlyevenwheninstalledatthesametime.Plug
ins(seebelow)areseenasconfigurableadditionstoprovideextrafunctionality,normallyasagraphical
viewofI/O(e.g.aboardwithbuttonsandlights).Oneotherveryimportantextensionistheuseofpre
selectedSWIinstructionstoimplementI/Ofunctionalities,suchasreadingandwritingfromstandardin
putoroutputorfiles(seebelow).
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
accordingtotheinstructionsinSectionXXonCandARM.FordetailsonARMassemblyprogram
mingconsultthereferences.

4.2OpeningandLoadingaFile
Toopenafile,selectFile>Load.Thennavigatetothefolderinwhichthefileisstoredanddoubleclick
thefiletobeopened.Whenafileisopened,itisautomaticallyassembled(ifitisasourcefile)and
linked.Iftheassemblyandlinkingprocessesaresuccessful,thecontentsofthefileappearinthe
8

ARMSim#UserGuide

CodeViewwiththefirstinstructioninthe_start(ormain)subroutinehighlighted.Ifthecontentsofthe
fileappearintheCodeView,butthefirstinstructionisnothighlighted,onemustchecktheOutput
Viewforcompilererrors(seesection6.3).
Notes:
Thefiletobeopenedmustbeasource(.s)fileoranobject(.o)file.
Ifthefiletobeopeneddoesnotappearinthedirectorylistinginthedialogbox,checktomake
surethattheappropriatefiletypehasbeenselected.
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)

Figure3.CodeView

ARMSim#UserGuide

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

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(seeFigure4).
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)

Figure4.GeneralPurposeRegistersView.

10

ARMSim#UserGuide

TheFloatingPointRegistersareselectedbyclickingontheFloatingPointtabintheRegistersView.
TheFloatingPointRegisterscanbeviewedasSinglePrecisionorDoublePrecisionregisters.UsetheSin
glePrecisionorDoublePrecisiontabsatthetopoftheRegistersViewtoswitchbetweenthedisplay
types(seeFigure5).

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.
11

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

Figure5.FloatingPointRegistersView.
Notes:
ThefilestobeopenedmustbeARMassemblersource(.s)files,ARMobject(.o)files,oracombi
nationofsourceandobjectfiles.
Ifafiledoesnotappearinthedirectorylistinginthedialogbox,onemustcheckthattheappro
priatefiletypehasbeenselected.
IfthecontentsofthefileappearintheCodeView,butthefirstinstructionisnothighlighted,
checktheOutputViewforcompilererrors(seesection6.3).
Whenthefileisopened,itisautomaticallyassembled(ifitisasourcefile)andlinked.

5.5Breakpoints
Abreakpointisauserdefinedstoppingpointinaprogram(i.e.apointotherthananSWI0x11instruc
tion,atwhichexecutionofaprogramshouldterminate).Whenaprogramisbeingdebugged,break
pointsareusedtohaltexecutionoftheprogramatpredefinedpointssothatthecontentsofstorage
locations,suchasregistersandmainmemory,canbeexaminedtoensurethattheprogramisworking
correctly.
12

ARMSim#UserGuide

WhenabreakpointissetandtheprogramisrunusingeithertheDebug>RunoptionortheContinue
button(seesection4.3),executionoftheprogramstopsjustbeforeexecutionoftheinstructionatwhich
thebreakpointisset(seeFigure6).
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

Figure6.Breakpoints.

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

6.1WatchView
TheWatchViewdisplaysthevaluesofvariablesthattheuserhasaddedtothewatchlist,whichisalist
ofvariablesthattheuserwishestomonitorduringtheexecutionofaprogram.
13

ARMSim#UserGuide

Toaddavariabletothewatchlist,selectWatch>AddWatch.Alternatively,rightclickintheWatch
View,andselectAddWatchfromthecontextmenu.IntheAddWatchdialogbox(seeFigure7),select
thefile,inwhichthevariableappears;thelabelthatisattachedtothevariable;andthedisplaytypeof
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.

Figure7.AddingaWatch.

6.2MemoryView
AMemoryViewdisplaysthecontentsofmainmemory.Inthisview,eachrowcontainsanaddressfol
lowedbyaseriesofwordsfrommemory(seeFigure8).

14

ARMSim#UserGuide

SincetheentiremainmemorycannotbedisplayedinasingleMemoryView,eachMemoryViewshows
onlyapartofmemory.Theaddressinthetopleftcorneroftheviewspecifiestheword,atwhichthe
partofmemorydisplayedintheviewbegins,andthesizeoftheviewdeterminesthenumberofwords
displayed.
Todisplayadifferentpartofmemory,enterahexadecimaladdressfrom0toFFFFFFFFintothetextbox
inthetopleftcorneroftheMemoryView.Alternatively,usetheupanddownarrowsbesidethetext
boxtoselectlowerandhighermemoryaddresses,respectively.Thecontentsofmemorycanbedis
playedas8bitbytes,16bithalfwords,or32bitwords.UsethethreebuttonsintheWordSizeboxinthe
toprightcorneroftheMemoryViewtoswitchamongthethreedisplayformats.

Theaddressofthefirstwordwherethe
displayofmemoryinthisviewbegins

Usethesebuttonstoswitch
betweenthe8bit,16bit
and32bitdisplaymodes
Memorylocationsthatwerewrittentoduringtheexecution
ofthelastinstruction(orsequenceofinstructions)

Address

MemoryValues

Figure8.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(seeFigure9).ClickOK,and
thenreloadtheprogram(seesection5.3)torefreshtheMemoryView(s).
Notes:
Ifastore(STR)instructionisexecuted,butthevalueinmemorydoesnotchange,checkthe
CachePreferencestomakesurethattheWritePolicyisnotsettoWriteBack.Ifitis,setitto
WriteThrough.(Seesection6.5forinformationonsettingtheCachePreferences.)
15

ARMSim#UserGuide

ThesimulatorcanhavemultipleMemoryViews,eachofwhichdisplaysadifferentregionof
memory.ToopenadditionalMemoryViews,selectView>Memory.
Whenthedisplaysizeissetto8bit,theASCIIrepresentationofeachrowofbytesisdisplayedat
theendoftherow.
Whenthedisplaysizeis16bitor32bit,theassignmentofbyteaddressesislittleendian.
IntheMemoryView,allcellsthatarepartofthememoryregionallocatedtotheprogramare
showninhexadecimalnotation(e.g.E1A03000,00000000);cellsoutsidetheallocatedmemory
regionareshownasquestionmarks(e.g.????????).

Figure9.MainMemoryPreferencesForm.

6.3OutputView
TheOutputViewcontainsarowoftwotabslabelledConsoleandStdin/Stdout/Stderr.Selectingthe
tablabelledConsolebringsawindowtothefrontwherethesimulatoroutputssuccessanderrormes
sages.Afterthesimulatorhasloadedtheprogram,anyassemblerorlinkererrorsaredisplayedhere(see
Figure10foranexample).TofindthesourceofanerrormessagedisplayedintheOutputView(seeFig
ure10),doubleclickthemessage,andscrolluponelineintheCodeView.Additionalinformationwill
bedisplayedheresuchasinstructioncountsandruntimes.
SelectingthetablabelledStdin/Stdout/Stderrbringsawindowtothefrontwhereoutputfromthe
userprogramisdisplayedasaresultofusingsoftwareinterrupts(SWIinstructions)toperformI/O.
Outputdirectedtoeitherthestandardoutputorstandarderror(Stdin/Stdout)aredisplayedinthis
16

ARMSim#UserGuide

tabbedwindow.Anyrequesttoreadfromthestandardinputdevice(Stdin)causestheprogramto
freezeuntiltheinputisprovidedonthekeyboard;thatinputisechoedinthistabbedwindowaswell.
TocopytextfromtheoneoftheOutputViewtabbedwindows,rightclickintheview,andselectCopy
toClipboardfromthecontextmenu.ToclearthecontentsoftheOutputViewtabbedwindow,right
clickinthetab,andselectClearfromthecontextmenu.

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

Figure10.ErrorMessage.

17

ARMSim#UserGuide

TopoftheStack

Stack
Value

Figure11.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(seeFigure12)ortheCacheWizardtochangethecurrentcachesettings,andclick
OK.Torestorethedefaultcacheproperties,selecttheRestoreDefaultsbuttonontheCachePreferences
Form.
WhenusingtheCachePreferencesFormtosetthecacheproperties,beginbyselectingthetypeofcache.
Table3liststheavailablecacheconfigurations.Then,setthesizeofthecache(s).OncetheCacheSizehas
beenset,selectingavalueforeithertheBlockSizeortheNumberofBlockscausestheremainingset
tingsintheCacheSizeboxtoassumetheappropriatevalues,sothatthethreepropertiessatisfythefol
lowingequation:
CacheSize(bytes) = BlockSize(bytes) NumberofBlocks

18

ARMSim#UserGuide

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.

Figure12.CachePreferencesForm.

19

ARMSim#UserGuide

IntheCacheViews,theboundariesofsetsaremarkedbythebluesquarebracketsalongthelefthand
sideoftheview(seeFigure13).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

Figure13.CacheView.

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

20

ARMSim#UserGuide

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

21

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.

22

mov
swi
ldr
str
...
Address:

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

ARMSim#UserGuide

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.

23

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:

24

.asciz

"\nThis is the resulting matrix:\n"

ARMSim#UserGuide

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

25

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.
AdiagramrepresentingschematicallythefeaturesoftheEmbestboardisshowninFigure14.

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

Figure14.Adiagrammaticviewoftheavailablecontrolsanddisplaysonthe
EmbestBoardView
Thereare5maincomponentsinthisviewavailableforprogramming:
1. One8segmentdisplay(output).
2. TworedLEDlights(output).
26

ARMSim#UserGuide

3. Twoblackbuttons(input).
4. Sixteenbluebuttonsarrangedinakeyboard4x4grid(input).
5. OneLCDdisplayscreen,whichisagridof40columnsby15rowsofindividualcells.Thecoordi
natesforeachLCDcellarespecifiedbya{column,row}pair.Thetopleftcellhascoordinates{0,0},
whilethebottomrightcellhascoordinates{39,14}.EachcellcancontainexactlyoneASCIIcharacter.

Table5.SWIoperationsgreaterthan0xFFascurrentlyusedfortheEmbestboardPlugIn
Opcode

DescriptionandAction

Inputs

Outputs

swi 0x200

Lightupthe8Segment
Display.

r0:the8segmentPattern Theappropriatesegmentslight
(seebelowinFigure15for 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.

swi 0x203

CheckifoneoftheBlue
None(seebelowinFigure r0=theBlueButtonPattern(see
Buttonshasbeenpressed. 19fordetails)
belowinFigure19).

swi 0x204

Displayastringonthe
LCDscreen

EithertheleftLEDison,orthe
right,orboth

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

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.

27

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.1DetailsandExamplesforSWICodesfortheEmbestBoardPlugin
Setthe8SegmentDisplaytolightup:swi0x200
Theappropriatesegmentslightuptodisplayanumberoracharacter.Thepatternofsegmentstobelit
upisassignedtoregisterR0beforethecalltoswi0x200.Figure15showsthearrangementsofseg
ments,andanexamplefollows.Eachsegmentislogicallylabelledanditsbytecodeisshowninthelist
inTable6.Forexample,inFigure15,todisplaythenumber3,segmentsA,B,C,DandF
mustbeilluminated.ThecodetobeassignedtoR0iscomputedbythelogicalORoftheindividualbyte
codes.

28

ARMSim#UserGuide

Figure15.ThePatternforthe8SegmentDisplay

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
areusefulforaccessingthebytevaluesassociatedwiththelabelsofeachsegmentasshowninFigure15.
AnexampleofapossibledeclarationofdataisalsogiveninFigure17forthedisplayofintegers,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

Figure16.Possibledatadeclarationforbytevaluesforsegments

29

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

Figure17.Possibledatadeclarationforintegerpatterns
Anexampleofapossibleroutinetodisplayanumberinthe8segmentDisplayusingthedeclarations
givenaboveisshowninFigure18.

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}

Figure18.ApossibleDisplay8Segmentroutine
Inline[3],registerr0isassignedthebytevaluecorrespondingtotheindexedelementofthearraydigits
fromFigure17.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.

30

ARMSim#UserGuide

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
tionofthebluebuttonasdepictedinFigure19.
Forexample,ifr0=2thenthebluebuttonin
position2waspressed.

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.
Figure19.ThePatternfortheBlueButtons

31

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.CombiningCandARMCode
ItisusefulfirsttoreviewtheinstructionsonopeningandloadingmultiplefilesinSection5.4.ascom
biningCandARMcoderequirestheloadingofmultiplefiles.

10.1CompilingaProgramwithCandARM
AnexampleprogramshownbelowinFigure20isconstructedfromtwofiles,wherethemainprogram
(infileAddMain.siscodedinARMassemblerandtheotherfile(calledmyAdd.c)iscodedinCand
containsafunction.InordertoexecutetheprograminARMSim#,thefilemyAdd.c mustfirstbecom
piledtoARMassemblysourcefile(myAdd.s)ortoARMobjectcode(myAdd.o).Thiscanbeaccom
plishedusingacrosscompiler.

32

ARMSim#UserGuide

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

1:
2:
3:
4:
5:
6:

@ File: AddMain.s
.text
.global _start
.extern myAdd
_start:
LDR
R0,=Num1
LDR
R0,[R0] @
LDR
R1,=Num2
LDR
R1,[R1] @
BL
myAdd
@
LDR
R4,=Answer
STR
R0,[R4] @
SWI
0x11
.data
Num1: .word 537
Num2: .word -237
Answer:.word0
.end

first parameter passed in R0


second parameter passed in R1
R0 = myAdd(Num1:R0,Num2:R1)
result was returned in R0

/* File: myAdd.c */
int myAdd( int arg1, int arg2 ) {
int result = arg1 + arg2;
return result;
}
Figure20.MixedARMAssemblerandCProgramexample1

10.2CompilingaCProgramtoARMwithCodeSourcery
TheCodeSourcerytoolchaincanbeusedforcrosscompilingandanonprofessionalversionisavail
ablefordownloadfromthesite:
CodeSourceryG++LiteEditionforARM:
http://www.codesourcery.com/sgpp/lite/arm/portal/subscription?@template=lite
ThemostusefulcommandshavealsobeenlinkedintoTextPadtoolsforeasyuseandbothpathsare
shownhere.
TheexamplesassumethatCodeSourceryhasbeeninstalledinthedirectory:

C:\Program Files\CodeSourcery
Allthecommandsbelowthusimplytheprefix:

C:\Program Files\CodeSourcery\Sourcery G++ Lite\bin\


1. Inacmd windowenterthecommand:
33

ARMSim#UserGuide

arm-none-eabi-gcc.exe Wall S mcpu=arm7tdmi myAdd.c


Or,fromTextPaduse:

Tools | C > ARM Assembly (.s)


IftherearenoerrorsintheCprogram,thecrosscompilerwillcreateanARMassemblyfilenamed
myAdd.s.The-Sflagtellsgcctostopafterthestepoftranslatingtoassemblylanguage.
2. Togeneratesimplercodeoneshouldtrytheoptimizerwith:

arm-none-eabi-gcc.exe Wall S -O1 mcpu=arm7tdmi myAdd.c


correspondinginTextPadto

Tools | C > ARM Assembly Optimize:L1(.s)


orwith:

arm-none-eabi-gcc.exe Wall S -O2 mcpu=arm7tdmi myAdd.c


correspondinginTextPadto

Tools | C > ARM Assembly Optimize:L2(.s)


3. TheARMassemblyfilecannowbeconvertedtoanobjectfilewith:

arm-none-eabi-as.exe -warn -mcpu=arm7tdmi myAdd.s -o myAdd.o


correspondinginTextPadto

Tools | ARM Assembly > Binary(.o)


SimilarlythemainprograminARMcanbeconvertedfromARMassemblytoanobjectfileasin:

arm-none-eabi-as.exe -warn -mcpu=arm7tdmi AddMain.s -o AddMain.o


correspondinginTextPadto

Tools | ARM Assembly > Binary(.o)


4. Alternatively,onecancompiledirectlyfromCtoARMobjectcodeusing:

arm-none-eabi-gcc.exe -c -Wall -mcpu=arm7tdmi myAdd.c -o myAdd.o


correspondinginTextPadto

Tools | C > ARM Binary(.o)


10.3LinkingandExecutingthePrograminARMSim#
AtthispointARMSim#isabletocombinethefilesintooneprogram.Thefouracceptablechoicesare
listedbelow.TheMultiFileOpendialogboxshouldbeusedtoloadanyofthecombinationslisted.
ARMSim#loadsandlinksthefiles,afterassemblingifnecessary.ARMSim#isabletolinkandexecute
anyoftheabove.Duringtheexecutionthefocusinthecodewindowshiftsbetweenmodulesasappro
priatewhenaBLinstructionisinvoked.
1

AddMain.s

AddMain.s

AddMain.o

AddMain.o

myAdd.s

myAdd.o

myAdd.s

myAdd.o

10.4ARMParameterPassingConventions
TheGnuCcompilergcccantranslateafunctionintocodewhichconformstotheARMprocedurecall
standard(orAPCSforshort),whengiventheappropriatecommandlineoptions.
TheAPCSrulesareasfollows:

34

ARMSim#UserGuide

ThefirstfourargumentsarepassedinR0,R1,R2andR3respectively.(Iftherearefewerargu
mentsthenonlythefirstfewoftheseregistersareused.)Thus:parameter1alwaysgoesinR0,
parameter2alwaysgoesinR1,parameter3alwaysgoesinR2,parameter4alwaysgoesinR3.
Anyadditionalargumentsarepushedontothestack.
ThereturnvaluealwaysgoesinR0.
ThefunctionisfreetodestroythecontentsofR0R3andR12(usedasscratch).Thatis,the
calledfunctioncanusetheseregistersforcomputationsanddoesnotrestoretheiroriginalvalues
whenthefunctionexits.
Thefunctionmustpreservethecontentsofallotherregisters(excludingPCofcourse).

ThustheCcrosscompilerimplementsthecallingconventions
ThustheversionofthegcccrosscompilerfromCodeSourceryimplementsthecallingconventionsand
treatsR0R3andR12ascallersaveregisters,implyingthatitisthecallerfunctionresponsibilityto
savetheminthestackbeforetheBLinstructionandrestorethemafterreturn.

10.5Example2forcombiningCandARM
Example2isaprogramwith3files:
1. ARM_Main.s contains the main initial program in ARM which calls the function Compute
whichisintheexternalfileARM_Aux.s. Thefunction Print iscalledbyComputeyetitis
includedinthemainARMfileARM_Main.s.
2. ARM_Aux.s containsthefunction Computewhichcallsthefunction Print includedinthe
mainARMfileARM_Main.s.
3. Mystery.c containsthefunctionMysterycalledbyCompute.

11.CodeExamples
11.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
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
35

ARMSim#UserGuide

@ File: ARM_Main.s ==== Main and Print Routines


.equ
SWI_Exit,
0x11
@ Local Constants
.equ
SWI_PrintInt,
0x6B
.equ
SWI_PrintChar, 0x0
.equ
Stdout,
1
.equ
EndInput,
-1
.global_
start
@ Exported Symbols
.global
Print
.extern
Compute
@ Imported Symbols
.text
@ main()
_start:
ldr
r0, =inputs
mov
r1,#EndInput
bl
Compute
MainEnd:
swi
SWI_Exit
@ ==== void Print(R0:value)
Print:
stmfd
sp!, {r0,r1,lr} @ YES, we do need this!
mov
r1, r0
@ R1:value-to-print = R0:arg1
mov
r0, #Stdout
@ print to console
swi
SWI_PrintInt
@ PrintInt(R0:where, R1:value)
mov
r0, #0x0A
@ ASCII new-line character
swi
SWI_PrintChar
@ PrintChar(R0:value)
ldmfd
sp!, {r0,r1,pc} @ YES, we do need this!
.data
inputs:.word0, 1, 2, 3, 4, 5, 6, -1
.end
ARM_Main.s:mainARMroutineforExample2

@ 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
36

ARMSim#UserGuide

swi SWI_PrStr
swiSWI_Exit @ stop executing: end of program
.data
Message1: .asciz"Hello World!"
EOL:
.asciz
"\n"
NewL:
.ascii
"\n"
Blank:
.ascii
" "
.end

11.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
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 ===============================================
37

ARMSim#UserGuide

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
Message1:
.asciz
"Hello World! \n"
.end

11.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
38

ARMSim#UserGuide

.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)

11.4Example:Subroutinetoimplementawaitcyclewiththe32bittimer
@ Wait(Delay:r2) wait for
Wait:
stmfdsp!, {r0-r1,lr}
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}

r2 milliseconds

@ R1: start time

@ R0: time since start


@ fix unsigned subtract

11.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.

39

ARMSim#UserGuide

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:
mov
r6,#0
@ counting the loops (not necessary)
ldr
r8,=Top15bitRange
ldr
r7,=EmbestTimerMask
ldr
r10,=Point1Sec
SWI
SWI_GetTicks
@Get current time T1
mov
r1,r0
@ R1 is T1
and
r1,r1,r7
@ T1 in 15 bits
RepeatTillTime:
add
r6,r6,#1
@ count number of loops (not necessary)
SWI
SWI_GetTicks
@Get current time T2
mov
r2,r0
@ R2 is T2
and
r2,r2,r7
@ T2 in 15 bits
cmp
r2,r1
@ is T2>T1?
bge
simpletime
sub
r9,r8,r1
@ TIME= 32,676 - T1
add
r9,r9,r2
@
+ T2
bal
CheckInt
simpletime:
sub
r9,r2,r1
@ TIME = T2-T1
CheckInt:
cmp
r9,r10
@is TIME < interval?
blt
RepeatTillTime
swi
SWI_EXIT
.end

11.6Example: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
40

ARMSim#UserGuide

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
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
41

ARMSim#UserGuide

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
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
42

ARMSim#UserGuide

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
swi
SWI_CLEAR_LINE
mov
r1,#0
mov
r0,#0
BL Display8Segment
bal CKBLUELOOP

@clear previous line

ONE:
mov
swi
mov
mov
BL
bal

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#1
Display8Segment
CKBLUELOOP

@clear previous line

mov
swi
mov
mov
BL
bal
THREE:
mov
swi
mov
mov
BL
bal
FOUR:
mov
swi
mov
mov
BL
bal
FIVE:
mov
swi

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#2
Display8Segment
CKBLUELOOP

@clear previous line

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#3
Display8Segment
CKBLUELOOP

@clear previous line

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#4
Display8Segment
CKBLUELOOP

@clear previous line

r0,#5
SWI_CLEAR_LINE

@clear previous line

TWO:

43

ARMSim#UserGuide

mov
mov
BL
bal

r1,#0
r0,#5
Display8Segment
CKBLUELOOP

mov
swi
mov
mov
BL
bal
SEVEN:
mov
swi
mov
mov
BL
bal
EIGHT:
mov
swi
mov
mov
BL
bal
NINE:
mov
swi
mov
mov
BL
bal
TEN:
mov
swi
mov
mov
ldr
swi
mov
mov
BL
bal
ELEVEN:
mov
swi
mov
mov
ldr
swi

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#6
Display8Segment
CKBLUELOOP

@clear previous line

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#7
Display8Segment
CKBLUELOOP

@clear previous line

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#8
Display8Segment
CKBLUELOOP

@clear previous line

r0,#5
SWI_CLEAR_LINE
r1,#0
r0,#9
Display8Segment
CKBLUELOOP

@clear previous line

r0,#5
SWI_CLEAR_LINE
r0,#6
r1,#5
r2,=InvBlue
SWI_DRAW_STRING
r1,#0
r0,#10
Display8Segment
CKBLUELOOP

@clear previous line

SIX:

44

r0,#5
SWI_CLEAR_LINE
r0,#6
r1,#5
r2,=InvBlue
SWI_DRAW_STRING

@
@
@
@

column number
row number
pointer to string
draw to the LCD screen

@ clear 8-segment

@clear previous line


@
@
@
@

column number
row number
pointer to string
draw to the LCD screen

ARMSim#UserGuide

mov r1,#0
mov r0,#10
BL Display8Segment
bal CKBLUELOOP
TWELVE:
mov r0,#5
swi SWI_CLEAR_LINE
mov r0,#6
mov r1,#5
ldr r2,=InvBlue
swi SWI_DRAW_STRING
mov r1,#0
mov r0,#10
BL Display8Segment
bal CKBLUELOOP
THIRTEEN:
mov r0,#5
swi SWI_CLEAR_LINE
mov r0,#6
mov r1,#5
ldr r2,=InvBlue
swi SWI_DRAW_STRING
mov r1,#0
mov r0,#10
BL Display8Segment
bal CKBLUELOOP
FOURTEEN:
mov r0,#5
swi SWI_CLEAR_LINE
mov r0,#6
mov r1,#5
ldr r2,=InvBlue
swi SWI_DRAW_STRING
mov r1,#0
mov r0,#10
BL Display8Segment
bal CKBLUELOOP
FIFTEEN:
mov r0,#5
swi SWI_CLEAR_LINE
mov r0,#6
mov r1,#5
ldr r2,=InvBlue
swi SWI_DRAW_STRING
mov r1,#0
mov r0,#10
BL Display8Segment
CKBLUELOOP:
mov r0,#10
swi SWI_CLEAR_LINE

@ clear 8-segment

@clear previous line


@
@
@
@

column number
row number
pointer to string
draw to the LCD screen

@ clear 8-segment

@clear previous line


@
@
@
@

column number
row number
pointer to string
draw to the LCD screen

@ clear 8-segment

@clear previous line


@
@
@
@

column number
row number
pointer to string
draw to the LCD screen

@ clear 8-segment

@clear previous line


@
@
@
@

column number
row number
pointer to string
draw to the LCD screen

@ clear 8-segment

@clear previous line

45

ARMSim#UserGuide

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
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
46

ARMSim#UserGuide

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

47