Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ThisdocumentisadaptedforMPLABXandtheICD3IncircuitDebuggerfromthetutorialsthatformchapter3
oftheMPLABICD2InCircuitDebuggerUsersGuideandchapter3oftheMPLABICD3InCircuitDebugger
UsersGuide.
1 INTRODUCTION
Thistutorialwalksyouthroughtheprocessofdevelopingasimpleprojectusingasampleprogram,
TUT452.asm.Thisprogramusestheanalogtodigital(A/D)converterofthePIC18F452onthePICDEM2Plus
DemoBoard(DM163022).TheprogramconfigurestheA/DmoduletoconvertinputfromA/Dchannel0
(connectedtothepotentiometeronthedemoboard)anddisplaytheresultsasabinarynumberonthefour
PORTBLEDs.
Topicscoveredinthistutorial:
CreatingadirectoryontheLabfileserver
Settingupthedevelopmentenvironment
Creatingandconfiguringaproject
Addingsourcefilestotheproject
Buildingtheproject
Debuggingtheproject
Programmingtheapplication
TUT452.asmsourcecode
2 CREATINGADIRECTORYONTHEFILESERVER
IntheMechatronicsLabwemayupdatetheimageonthecomputersatanytimewithoutwarning.Thismeans
thatanyfilesthatyouhavestoredlocallyonaMxLabPCwillbedestroyed.
Youmustalways(andonly)storeyourfilesontheFileServer,mxlabserver.Forthistutorial,thefirstthingthat
youmustdoiscreateadirectoryontheFileServertoworkin.
1. Dependingonwhetheryouareworkingaloneforthistutorial,orwithalabpartner,followthe
instructionsinsection1.1oftheMechatronicsLaboratoryFacilitiesdocumenttoeither
a. createapersonaldirectoryontheU:drive(\\mxlabserver\Users)OR
b. createandassignpermissionstoadirectoryontheV:drive(\\mxlabserver\Groups)that
youcansharewithyourlabpartner.
2. MakeanewdirectorysayDemointhedirectorythatyoucreatedinstep1.
3 SETTINGUPTHEDEVELOPMENTENVIRONMENT
TheMPLABXintegrateddevelopmentenvironment(IDE)softwareisinstalledandconfiguredbeforeyoubegin
thistutorial.IntheMechatronicsLabwewillalwayspowertheICD3fromtheUSBcablethatconnectsittothe
hostPC.Anexternalpowersupplywillalwaysbeusedtopowerthetargetboard(thePICDEM2PlusDemo
Boardforthistutorial).
Remember:YoumustnotinjectasignalintotheICD3whenitisnotpowered.ThismeansthattheICD3
mustbeconnectedtothehostPCfirstanddisconnectedlast.
Usethefollowingconnection/powerupsequence:
1. PlugthePCsUSBcableintoMPLABICD3pucktoapplypowertoit.ThePowerandActiveLEDsonthe
puckshouldgoon.PluggingintheICD3willensurethatMPLABXcanfinditduringcreationofa
project.DONOTpowerthetargetboardyet.DONOTconnecttheICD3tothetargetyet.
2. StarttheMPLABXIDEapplication,whichshouldinitiallylooksimilartoFigure1.Itwillbeusefulto
maximisetheMPLABXwindow.
Figure1:InitialviewofMPLABX,withnoprojectopen.
4 CREATINGANDCONFIGURINGAPROJECT
MPLABXisanintegrateddevelopmentenvironmentbasedontheopensource,crossplatformNetBeansIDE.
WithinMPLABXeverythingisprojectbased;youmustcreateaprojecttodevelopyourapplication.Creatinga
projectinvolvesselectingaspecificmicrocontrollerdevice,aswellasselectingandsettinguplanguagetools,
debugtools,programmingtoolsandotherprojectspecifics.Thisensuresallitemsneededforsuccessfully
developinganapplicationarepresent.
4.1Creatingaproject
Tocreateanewproject,selectFile>NewProject.TheNewProjectDialoguewillopen.Followthesteps
belowtoconfiguretheproject.
1. ChooseProjectSelectCategoryMicrochipEmbeddedandProjectStandaloneProject.Click
[Next>]
2. SelectDeviceChooseFamily:Advanced8bitMCUs(PIC18)andDevice:PIC18F452.Click[Next>]
4. SelectToolUnderHardwareTools,clickontheserialnumber(SN:JITxxxx)oftheICD3thatis
shown.Thereshouldonlybeone;thisistheICD3thatisconnectedtothePC.Click[Next>]
6. SelectCompilerUnderCompilerToolchains,clickonmpasm(v5.51)undermpasm.Click[Next>]
7. SelectProjectNameandFolderIntheProjectNamebox,typeasuitablenameTute0for
example,fortheproject.InProjectLocationbrowsetotheDemodirectorythatyoucreatedin
step3.2ofthistutorial.TicktheSetasmainprojecttickbox.LeaveEncoding(thecharacterset)at
ISO88591.Click[Finish].
MPLABXshouldnowlooksimilartoFigure2.
Figure2:MPLABXafterprojectcreation.
Figure2showsthefourmainMPLABXwindowsintheirdefaultarrangement.TheFileWindowshows
differentviewsofallofthefilesintheproject.Eventhoughwehavenotyetputevenonesourcefileinthe
projecttherearealotoffilesthatcanbeseeninFigure2intheFiletaboftheFileWindow.Allofthefilesthat
youcanseeareautomaticallycreatedandmaintainedbyMPLABX.Thesefilesdefinetheproject,includingthe
exactmicrocontroller,thesoftwaretoolchain(assembler,compiler,linker,etc.)andthehardwaredebugging
tools.Donoteditanyofthefilesinthenbprojecttree!
DoubleclickingonanyfilenameintheFileWindowopensthefileintheEditorWindow.Thisiswhereyouwill
edityoursourcefilesandviewthemwhendebugging.
TheNavigatorWindowiswhereyoucanviewtheprojectconfigurationandmakechangestoit.
TheTaskWindowiswhereoutputfromtheIDEisshown,suchasoutputfromthesoftwaretoolchainduringa
projectbuildandstatusmessagesfromthedebugginghardwareforexample,togetherwiththeinternalstate
ofthemicrocontrollersmemory.Memoryvaluescanonlybeinspectedorchangedwhenthemicrocontroller
isnotexecutinginstructions.
4.2Configuringtheproject
Toinspecttheprojectconfiguration,clickontheProjectname(hereitiscalledTute0)intheFileWindowand
selectFile>ProjectProperties(Tute0)fromthemainmenubar.Youwillseesomethingliketheview
showninFigure3.
Figure3:ProjectPropertiesinitialview.
Havealookatwhatcanbeconfigured.Youshouldnothavetochangeanythingforthisprojectasitshould
haveallbeencorrectlyconfiguredduringprojectcreation.
IntheGeneralconfiguration(Figure4)youwillseethatMPLABXhascreatedaprojectfoldercalled
Tute0.XunderyourDemodirectorytostoretheproject,andwillignoresubfoldersaccordingtotheregular
expression^(nbproject|build|test)$.
Figure4:ProjectPropertiesGeneralconfiguration.
PleasechecktomakesurethatinthePoweroptionscategoryoftheICD3configuration(Figure5)that
PowertargetcircuitfromICD3isNOTselectedsincewewillalwayspowerthetargetmicrocontrollerboard
andothercircuitryfromanexternalpowersupply.
Figure5:ProjectPropertiesICD3Powerconfiguration.
5 ADDINGSOURCEFILESTOTHEPROJECT
5.1Obtainthesourcefiles
Youfirstneedtoobtainthetwoassemblylanguagefilesthatyouwillneedforthetutorialandplacethemin
thedirectorythatyoumadeinstep2.
1. OnthedesktopthereisalinktoCoursework Files on Server.Openthatlinkandgoto
Mtrx3700\Initial Workspace\
2. CopythefilesfromInitial WorkspaceintothedirectoryDemo\Tute0.Xthatwascreatedby
MPLABXwhentheprojectwascreated.Makethesefileswritable.
5.2Addsourcefilestotheproject
1. Toaddanexistingsourcefiletotheproject,rightclickontheprojectnameintheFileWindowand
selectAddexistingitem...
2. SelectTUT452.asm,makesurethatStorepathasRelativeisactiveandclick[Select].Usingrelative
pathsmakesitmucheasiertomoveaprojectfromonecomputertoanother.
3. NowifyoudoubleclickonthefilenameTUT452.asmintheFilesWindowthefilewillopenintheEditor
WindowascanbeseeninFigure6.
6. BUILDINGTHEPROJECT
Wecannowbuildtheproject.Sincethisprojectcontainsassemblylanguagesourcecode,buildingitmeans
assemblingthesourcecodeusingtheMPASMassemblertoproducerelocatableobjectcode,andlinkingthat
codewiththeMPLINKlinkertocreateanexecutablebinaryfile.
BuildinginMPLABXusestheUNIXmaketooltobuildandlinkallsourcefilesintheproject(onlyoneinthis
simpletutorialexample)inthecorrectorder,accountingfordependenciesbetweensourcefiles.Onlyfiles
thathavebeenchangedbetweenbuilds,andtheirdependantfiles,willberebuiltbymake.
1. Tobuildtheproject,clickontheHammericon.IftheHammericonisnotvisible,clickView>
Toolbars>Run.TheHammerandBroomicondoesacleanandbuild,deletingintermediatefiles
(forexamplerelocatableobjectfiles)beforebuilding.Thiswillforceallsourcefilesintheprojecttobe
rebuilt.
2. Astheprojectbuilds,outputfrommakeisshownintheOutputwindow(Figure7).Youwillfirstsee
theresultofassemblerexecution.Iftheassemblersucceeds,thelinkerwillthenexecute.Theproject
shouldbuildsuccessfully,producingtwooutputfiles:
a. Demo/Tute0.X/dist/default/production/Tute0.X.production.hexThis
istheexecutablebinaryfilereadytobeloadedintotheparticularmicrocontrollerand
executed.
5
b. Demo/Tute0.X/dist/default/production/Tute0.X.production.cof
Thisisafileincommonobjectfileformat(COFF)thatcontainssymbols(variablenames,
etc)fromthesourcecodeandassociatedaddresses.ItallowstheIDEtoshowyouthesource
codeinsteadofmemoryaddresseswhendebugging.
c. IntermediatefilesarealsoproducedfilesTUT452.err,TUT452.lst, TUT452.oand
TUT452.o.dinthedirectoryDemo/Tute0.X/build/default/production/
Figure6:Projectwithasingleassemblylanguagefileadded.
Figure7:OutputWindowaftersuccessfulbuild.
7. DEBUGGINGTHEPROJECT
NowthattheprojectbuildswecandownloadittothetargetboardinthiscaseaPICDEM2Plusand
attempttorunthecode.
1. Important:TheICD3shouldbeconnectedtothePCviaaUSBcableatthispoint,providingpowerto
theICD3.
2. MakesurethePICDEM2PlusDemoBoardissetupasfollows:
d. ThepackagedoscillatorhasbeenselectedbyremovingjumperJ7.Thisselectstheclock
hardwarethatmatchesthewaythatthemicrocontrollerclockcircuitshavebeenconfigured
bytheECOSCselectioninconfigReg.incwhichisincludedfromTUT452.asm.
a. TheLEDshavebeenenabledbyfittingjumperJ6.
3. PowerthePICDEM2Plusboardusingthe5Vplugpacksuppliedandthenconnecttheboardtothe
ICD3usingtheshortRJ11cable.
4. ClicktheMakeandProgramDeviceMainProjecticon(bluerectanglewithdownwardsgreen
arrow).MPLABwillattempttoconnecttothetargetboardthroughtheICD3.YouwillseeaCaution
messagepopup,warningyoutocheckthatthedeviceselectedinMPLABisthesameoneasis
actuallyonthetargetboard;youcansafelydismissthismessage.
5. MPLABshouldconnecttothetargetboard,programthemicrocontrollerandverifythatprogramming
wascorrect.TheOutputWindowshouldappearasinFigure8.
Figure8:OutputWindowafterexecutablesuccessfullydownloadedtotarget.
7.1WhatshouldtheTUT452.asmprogramdo?
Whenrun,theprogramTUT452.asmrepeatedlyconvertstheanalogvoltagethatispresentonanalogto
digitalchannel0toaneightbitnumber,scalesthatnumbertolieintherange0to15andthenwritesthe
scalednumbertothedigitaloutputportPORTB.WhenrunonaPICDEM2PlusDemoBoard(Microchip
DM163022)theanalogvoltagevariesbetween0Vand+5VasthepotentiometerRA0isturned,andthescaled
numbervariesbetween0and15.Ifthesoftwareandhardwareareworkingtogethercorrectlyyoushouldsee
theLEDschangingbetween1and15inbinaryasyouturnthepotentiometer.
7.2RunTUT452.asmprogramtoverifythatitworkscorrectly
TheMPLABICD3executesusercodeineitherrealtimemodeorinstepmode.
RealtimeexecutionoccurswhenthePIC18F452inthePICDEM2PlusdemoboardisputintheMPLABIDEs
runmode.Theuserprogramexecutesatthefullspeedofthehardwareclockonthetargetboard4MHzin
thiscase.
Instepmode,executionofthetargetprocessoriscontrolledbyMPLABthroughtheICD3.Theusercan,for
example,executeasingleassemblylanguageinstruction,orexecutethecodeuntilabreakpointisreached.
TheiconsintheMPLABXRunToolbararedescribedinFigure9.Whenexecutionofusercodeishaltedunder
controloftheICD3theusercaninspectorchangethevaluesinanyofthemicrocontrollersregisters.
1. NowletusseeiftheTUT452.asmprogramexecutescorrectly.Duringadebugsession,executionof
theprogramiscontrolledbytheICD3throughMPLABX,sowemustfirstlaunceadebugsession.
ClickontheDebugMainProjecticon(codelistingschematicwithsmallrightfacinggreenarrow)
andseveralthingswilloccur:firstlytheprojectwillberebuiltifnecessary.Severaltabswillopenin
theOutputWindowandyouwillagainseeaCautionmessagepopup,warningyoutocheckthatthe
deviceselectedintheMPLABprojectconfigurationisthesameoneasisactuallyonthetargetboard;
youcansafelydismissthismessage.Theexecutablecodewillthenbedownloadedtothetargetboard
andexecuted.MPLABXwillthenlooksomethinglikeFigure9.
2. YoucanturnthepotentiometerallyoulikebutnoneofthePORTBLEDswilllightbecausethe
programTUT452.asmisdeliberatelybroken...
Figure9:Startofdebuggingsession.
Table1:ButtonsontheRuntoolbar.
DebuggerMenu Button Action
FinishDebuggerSession Exitfromthedebuggersession.
Pause FinishthecurrentinstructionandgivecontroltoMPLAB
Reset SetthePCtotheresetaddress(0x0000)
Continue Resumerunningtheuserprogram
StepOver Atafunctioncall,stepoverthefunction
StepInto Atafunctioncall,stepintothefunction
RuntoCursor Resumerunninguserprogram,pauseatcursor
SetPCtoCursor Whatitsays!Equivalentofjumptocursor.
FocusCursoratPC
7.3DebugTUT452.asm
AnyofthefollowingcouldpreventtheTUT452programfromworking.
ThejumperJ6isnotfitted,sotheLEDswillneverlight.Checkit!
TheA/DconvertervalueisnotbeingproperlywrittentothePORTBLEDs.
TheA/Dconverterisnotenabledorhasnotbeensettostartaconversion.
Atypingerrorinthesourcecodeiscausingtheprogramtofunctionimproperly.
WewillinvestigatethesepossibilitiesintheDebugsession.
Toexplorethesecondpossibility,wewanttosetabreakpointatthelineofthefilethatwritesthevalueofthe
A/DresulttoPORTBsothatuserprogramexecutionwillpausethere.Whentheprogramispausedwecan
inspectvaluesinthemicrocontrollersregisters.
1. First,clickonthePauseiconNOTtheFinishDebugSessioniconsincethiswillclosethesession,
disconnectingtheICD3fromMPLAB.OnPause,thecurrentlyexecutinginstructionfinishesandMPLAB
showsthenextinstructiontobeexecutedbyhighlightingthewholelinewithalightgreenbackground.
2. Next,clicktheReseticon.ThisresetsthemicrocontrollersPC(programcounterregister)tothereset
addressandsetsallotherregisterstotheirresetvalues.Runningtheprogramfromhereisthesameas
itcomingoutofreset.
3. Now,clickthecursoronthefollowinglineofcodefromTUT452.asmintheEditorWindow:
movwf PORTB ;Write A/D result to PORTB
4. RightclickonthelinetodisplayashortcutmenuandselectToggleLineBreakpoint.Thissetsa
breakpointatthelinewhichismarkedascanbeseeninFigure10.
Figure10:Breakpointsetatline56.
5. Next,clicktheRunicontoagainfreeruntheuserprogram.Ifprogramexecutioneverreachesthe
breakpointtheprogramwillpausebeforeexecutingthelineatwhichthebreakpointisset.However,
thesampleprogramdoesnotpausesoitisneverreachingthebreakpoint.
6. ClickPausetopausetheprogramwhereverithappenstobe.IntheEditWindow,theprogramwillhave
haltedononeofthetwolinesunderthelabelWaitForAdConversion.TryRunandPauseafew
moretimestheprogramwillalwayspauseatoneofthesetwolines.
Basedonthepauselocationandthefactthattheprogramneverreachesthebreakpoint,itcanbe
concludedthattheproblemisintheA/Dconversion.Theprogramatline51testsabitforA/D
conversioncomplete;thisbitneverbecomesset.A/DinitializationoccursundertheSetuplabelatthe
beginningoftheprogram.
7. Toverifythattheflagbit(bitADIFinregisterPIR1)isnotbeingset,ClickontheSFRtabintheOutput
Window.ThisshowstheSpecialFunctionRegisterswhicharethemicrocontrollerscontrolandstatus
registers.ClickonNametosorttheSFRsbyname,thenscrolldownandclickonPIR1.Ifyouhoverthe
mouseoverthetextPIR1,MPLABwillshowthesymbolicnamesofthebitsintheregisterascanbe
seeninFigure11.ADIFisbit6anditisalwayszerotheA/Dconversionnevercompletes.TheA/D
converterinthePIC18F452hasanorganisationsuchthatifaconversionstartsthenitmustcomplete.
TheA/Dconversionisthereforenotstarting.
Figure11:InspectingthevalueofbitsinthePIR1registerwiththeprogrampaused.
8. A/DconversionnotstartingcouldbecausedbyincorrectconfigurationoftheA/Dhardware,orbythe
programsfailuretoinitiateaconversion.Toinvestigate,firstclickReset.Thensetabreakpointatthe
firstinstructionafterthelabelSetup.ClickonthefollowinglineofcodefromTUT452.asm:
clrf PORTB ;Clear PORTB
Thenrightclickonthelineandtogglethebreakpointattheline.
10
9. WewillwanttoinspectthevaluesthatarewrittenintothetworegistersADCON0andADCON1.These
tworegisterscontainthecontrolandstatusbitsfortheA/Dconverterhardware.Wewanttoinspect
howtheA/Dconverterisconfigured.AWatchWindowisanotherwaytoinspectregisters(and
variables).ClickDebugandthenselectNewWatch.Inthepopup,clickonSFRs,thenselectADCON0
andADCON1andclick[OK].TheVariablesWindowwillopen,showingthestateofthetworegisters
thatwehaveadded.
10. Beforecontinuing,makesurethatUnlimitedBP(S/W)isEnabledunderDebugResourcesinthe
Dashboard.Thisenablessoftwarebreakpoints.Onlyonehardwarebreakpointcanbeactive,butan
unlimitednumberofsoftwarebreakpointscanbeused.
11. Nowrunthecodeagain:clickResetthenContinue.Executionwillpausebeforeexecutingthelineof
codeatthebreakpoint.MPLABwilllooklikeFigure12.Line31(thebreakpoint)hasnotexecuted.The
littlegreenarrowpointstothenextinstructiontobeexecuted.
Figure12:Programpausedatbreakpointatline31.
12. Now,singlestepthecodefivetimes,inspectingthevaluesinADCON0andADCON1aftereachstep.
YoucanuseStepOverorStepInto:itdoesntmatterhereasthereisnofunctioncall.Payparticular
attentiontothevaluesinADCON0andADCON1whentheinstructionsmovwf ADCON0andmovwf
ADCON1execute.Theseinstructionsmovevaluesintotheregisters.Youwillseethatthevalues
change;theyareshowninredtoindicatethattheychangedasaresultofthepreviousinstruction.
Thefollowinglineofcodeshouldbeindicatedwhenfinished:
movlw B11000111 ;TMR0 prescaler, 1:256
13. NoticethatADCON0hasavalueof0x40.Thiscorrespondstothebinaryvaluedesignatedinthe
program,butisthisvaluecorrect?IfyouexpandthedisplayofADCON0intheVariablesWindowthe
valueofeachbitwillbeshownascanbeseeninFigure13.
11
Figure13:VariablesWindowshowingvaluesofADCON0bits.
14. InFigure13,bit0ofADCON0hasthesymbolicnameADON,andthevalue0.Areviewofthe
PIC18F452DataSheetsectiononA/D(Chapter17)indicatesthatfunctionofthisbitistoenablethe
A/Dcircuitry.Theconversionisneverfinishingbecauseitisneverstarting,anditisneverstarting
becausetheA/Dhardwaremoduleisnotenabled.
15. TheleastsignificantbitofADCON0shouldbeaone,notazero,toenabletheA/Dmodule.Tofixthis
bug,change:
movlw B01000000 ;Fosc/8, A/D enabled
to:
movlw B01000001 ;Fosc/8, A/D enabled
16. Torebuildtheprojectwehavetogetoutofthedebuggingsession,soclickonFinishDebugger
Session.ClickingonDebugMainProjectwillforcearebuildoftheproject,followedbydownloading
andrunningonthetargetboard.
17. WhenthecodeexecutesyoushouldseetheLEDscountinginbinaryasthepotentiometerRA0is
turned.
Thesourcecodeinthistutorialcontainedonlyonesimplebug.Realcodeiscertaintohavemore,particularly
whenyouarelearninganewprocessor.UsingtheMPLABICD3andMPLABIDEdebuggingfunctions,together
withcarefulthoughtandsimpleexperimentation,userscansuccessfullyfindandfixallproblemsintheircode.
8 PROGRAMMINGTHEAPPLICATION
Whentheprogramissuccessfullydebuggedandrunning,usuallythelaststepistoprogramthe
microcontrollerforstandaloneoperationinthefinisheddesign.Whendoingthis,theresourcesreservedby
theICDarereleasedforusebytheapplication.ThedevicecanbeprogrammedfromwithinMPLABXby
followingthesesteps:
1. EndthedebuggingsessionbyclickingFinishDebuggerSession.
2. ClickonMakeandProgramDeviceMainProject.Thiswillrebuildtheprojectasaproductionbuild
(whichdoesnotincludethesmalldebugmonitorprogramforcommunicatingwiththeICD3),
programthemicrocontrollerandruntheprogram.YouwillbeabletodisconnecttheICD3fromthe
targetboard,powercyclethetargetboardandtheprogramwillexecute.
12
;**********************************************************
;* TUT452.asm
;**********************************************************
;* Microchip Technology Incorporated
;* 17 March 2003
;* Assembled with MPASM V3.20 and MPLINK v3.20
;**********************************************************
;* This program configures the A/D Module to convert on
;* A/D channel 0 (the potentiometer) and display the
;* results on the LEDS on PORTB.
;**********************************************************
list p=18f452
Main:
btfss INTCON, TMR0IF ; Wait for Timer0 to timeout
goto Main
bcf INTCON, TMR0IF
WaitForAdConversion:
btfss PIR1, ADIF ; Wait for conversion to complete
goto WaitForAdConversion
clrf PORTB
movwf PORTB
goto Main ; Do it again
end
13