Upload
claudir-nunes-cavalheiro
View
96
Download
2
Embed Size (px)
Citation preview
1
MPLABX/ICD3TutorialThisdocumentisadaptedforMPLABXandtheICD3IncircuitDebuggerfromthetutorialsthatformchapter3oftheMPLABICD2InCircuitDebuggerUsersGuideandchapter3oftheMPLABICD3InCircuitDebuggerUsersGuide.
1 INTRODUCTIONThistutorialwalksyouthroughtheprocessofdevelopingasimpleprojectusingasampleprogram,TUT452.asm.Thisprogramusestheanalogtodigital(A/D)converterofthePIC18F452onthePICDEM2PlusDemoBoard(DM163022).TheprogramconfigurestheA/DmoduletoconvertinputfromA/Dchannel0(connectedtothepotentiometeronthedemoboard)anddisplaytheresultsasabinarynumberonthefourPORTBLEDs.Topicscoveredinthistutorial:
CreatingadirectoryontheLabfileserver Settingupthedevelopmentenvironment Creatingandconfiguringaproject Addingsourcefilestotheproject Buildingtheproject Debuggingtheproject Programmingtheapplication TUT452.asmsourcecode
2 CREATINGADIRECTORYONTHEFILESERVERIntheMechatronicsLabwemayupdatetheimageonthecomputersatanytimewithoutwarning.ThismeansthatanyfilesthatyouhavestoredlocallyonaMxLabPCwillbedestroyed.Youmustalways(andonly)storeyourfilesontheFileServer,mxlabserver.Forthistutorial,thefirstthingthatyoumustdoiscreateadirectoryontheFileServertoworkin.
1. Dependingonwhetheryouareworkingaloneforthistutorial,orwithalabpartner,followtheinstructionsinsection1.1oftheMechatronicsLaboratoryFacilitiesdocumenttoeithera. createapersonaldirectoryontheU:drive(\\mxlabserver\Users)ORb. createandassignpermissionstoadirectoryontheV:drive(\\mxlabserver\Groups)that
youcansharewithyourlabpartner.2. MakeanewdirectorysayDemointhedirectorythatyoucreatedinstep1.
3 SETTINGUPTHEDEVELOPMENTENVIRONMENTTheMPLABXintegrateddevelopmentenvironment(IDE)softwareisinstalledandconfiguredbeforeyoubeginthistutorial.IntheMechatronicsLabwewillalwayspowertheICD3fromtheUSBcablethatconnectsittothehostPC.Anexternalpowersupplywillalwaysbeusedtopowerthetargetboard(thePICDEM2PlusDemoBoardforthistutorial).Remember:YoumustnotinjectasignalintotheICD3whenitisnotpowered.ThismeansthattheICD3mustbeconnectedtothehostPCfirstanddisconnectedlast.Usethefollowingconnection/powerupsequence:
1. PlugthePCsUSBcableintoMPLABICD3pucktoapplypowertoit.ThePowerandActiveLEDsonthepuckshouldgoon.PluggingintheICD3willensurethatMPLABXcanfinditduringcreationofaproject.DONOTpowerthetargetboardyet.DONOTconnecttheICD3tothetargetyet.
2. StarttheMPLABXIDEapplication,whichshouldinitiallylooksimilartoFigure1.ItwillbeusefultomaximisetheMPLABXwindow.
2
Figure1:InitialviewofMPLABX,withnoprojectopen.
4 CREATINGANDCONFIGURINGAPROJECTMPLABXisanintegrateddevelopmentenvironmentbasedontheopensource,crossplatformNetBeansIDE.WithinMPLABXeverythingisprojectbased;youmustcreateaprojecttodevelopyourapplication.Creatingaprojectinvolvesselectingaspecificmicrocontrollerdevice,aswellasselectingandsettinguplanguagetools,debugtools,programmingtoolsandotherprojectspecifics.Thisensuresallitemsneededforsuccessfullydevelopinganapplicationarepresent.4.1CreatingaprojectTocreateanewproject,selectFile>NewProject.TheNewProjectDialoguewillopen.Followthestepsbelowtoconfiguretheproject.
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.InProjectLocationbrowsetotheDemodirectorythatyoucreatedinstep3.2ofthistutorial.TicktheSetasmainprojecttickbox.LeaveEncoding(thecharacterset)atISO88591.Click[Finish].
MPLABXshouldnowlooksimilartoFigure2.
3
Figure2:MPLABXafterprojectcreation.
Figure2showsthefourmainMPLABXwindowsintheirdefaultarrangement.TheFileWindowshowsdifferentviewsofallofthefilesintheproject.EventhoughwehavenotyetputevenonesourcefileintheprojecttherearealotoffilesthatcanbeseeninFigure2intheFiletaboftheFileWindow.AllofthefilesthatyoucanseeareautomaticallycreatedandmaintainedbyMPLABX.Thesefilesdefinetheproject,includingtheexactmicrocontroller,thesoftwaretoolchain(assembler,compiler,linker,etc.)andthehardwaredebuggingtools.Donoteditanyofthefilesinthenbprojecttree!DoubleclickingonanyfilenameintheFileWindowopensthefileintheEditorWindow.Thisiswhereyouwilledityoursourcefilesandviewthemwhendebugging.TheNavigatorWindowiswhereyoucanviewtheprojectconfigurationandmakechangestoit.TheTaskWindowiswhereoutputfromtheIDEisshown,suchasoutputfromthesoftwaretoolchainduringaprojectbuildandstatusmessagesfromthedebugginghardwareforexample,togetherwiththeinternalstateofthemicrocontrollersmemory.Memoryvaluescanonlybeinspectedorchangedwhenthemicrocontrollerisnotexecutinginstructions.4.2ConfiguringtheprojectToinspecttheprojectconfiguration,clickontheProjectname(hereitiscalledTute0)intheFileWindowandselectFile>ProjectProperties(Tute0)fromthemainmenubar.YouwillseesomethingliketheviewshowninFigure3.
4
Figure3:ProjectPropertiesinitialview.
Havealookatwhatcanbeconfigured.Youshouldnothavetochangeanythingforthisprojectasitshouldhaveallbeencorrectlyconfiguredduringprojectcreation.IntheGeneralconfiguration(Figure4)youwillseethatMPLABXhascreatedaprojectfoldercalledTute0.XunderyourDemodirectorytostoretheproject,andwillignoresubfoldersaccordingtotheregularexpression^(nbproject|build|test)$.
Figure4:ProjectPropertiesGeneralconfiguration.
PleasechecktomakesurethatinthePoweroptionscategoryoftheICD3configuration(Figure5)thatPowertargetcircuitfromICD3isNOTselectedsincewewillalwayspowerthetargetmicrocontrollerboardandothercircuitryfromanexternalpowersupply.
5
Figure5:ProjectPropertiesICD3Powerconfiguration.
5 ADDINGSOURCEFILESTOTHEPROJECT5.1ObtainthesourcefilesYoufirstneedtoobtainthetwoassemblylanguagefilesthatyouwillneedforthetutorialandplacetheminthedirectorythatyoumadeinstep2.
1. OnthedesktopthereisalinktoCoursework Files on Server.OpenthatlinkandgotoMtrx3700\Initial Workspace\
2. CopythefilesfromInitial WorkspaceintothedirectoryDemo\Tute0.XthatwascreatedbyMPLABXwhentheprojectwascreated.Makethesefileswritable.
5.2Addsourcefilestotheproject1. Toaddanexistingsourcefiletotheproject,rightclickontheprojectnameintheFileWindowand
selectAddexistingitem...2. SelectTUT452.asm,makesurethatStorepathasRelativeisactiveandclick[Select].Usingrelative
pathsmakesitmucheasiertomoveaprojectfromonecomputertoanother.3. NowifyoudoubleclickonthefilenameTUT452.asmintheFilesWindowthefilewillopenintheEditor
WindowascanbeseeninFigure6.
6. BUILDINGTHEPROJECTWecannowbuildtheproject.Sincethisprojectcontainsassemblylanguagesourcecode,buildingitmeansassemblingthesourcecodeusingtheMPASMassemblertoproducerelocatableobjectcode,andlinkingthatcodewiththeMPLINKlinkertocreateanexecutablebinaryfile.BuildinginMPLABXusestheUNIXmaketooltobuildandlinkallsourcefilesintheproject(onlyoneinthissimpletutorialexample)inthecorrectorder,accountingfordependenciesbetweensourcefiles.Onlyfilesthathavebeenchangedbetweenbuilds,andtheirdependantfiles,willberebuiltbymake.
1. Tobuildtheproject,clickontheHammericon.IftheHammericonisnotvisible,clickView>Toolbars>Run.TheHammerandBroomicondoesacleanandbuild,deletingintermediatefiles(forexamplerelocatableobjectfiles)beforebuilding.Thiswillforceallsourcefilesintheprojecttoberebuilt.
2. Astheprojectbuilds,outputfrommakeisshownintheOutputwindow(Figure7).Youwillfirstseetheresultofassemblerexecution.Iftheassemblersucceeds,thelinkerwillthenexecute.Theprojectshouldbuildsuccessfully,producingtwooutputfiles:
a. Demo/Tute0.X/dist/default/production/Tute0.X.production.hexThisistheexecutablebinaryfilereadytobeloadedintotheparticularmicrocontrollerandexecuted.
6
b. Demo/Tute0.X/dist/default/production/Tute0.X.production.cofThisisafileincommonobjectfileformat(COFF)thatcontainssymbols(variablenames,etc)fromthesourcecodeandassociatedaddresses.ItallowstheIDEtoshowyouthesourcecodeinsteadofmemoryaddresseswhendebugging.
c. IntermediatefilesarealsoproducedfilesTUT452.err,TUT452.lst, TUT452.oand TUT452.o.dinthedirectoryDemo/Tute0.X/build/default/production/
Figure6:Projectwithasingleassemblylanguagefileadded.
Figure7:OutputWindowaftersuccessfulbuild.
7. DEBUGGINGTHEPROJECTNowthattheprojectbuildswecandownloadittothetargetboardinthiscaseaPICDEM2Plusandattempttorunthecode.
1. Important:TheICD3shouldbeconnectedtothePCviaaUSBcableatthispoint,providingpowertotheICD3.
2. MakesurethePICDEM2PlusDemoBoardissetupasfollows:
7
d. ThepackagedoscillatorhasbeenselectedbyremovingjumperJ7.ThisselectstheclockhardwarethatmatchesthewaythatthemicrocontrollerclockcircuitshavebeenconfiguredbytheECOSCselectioninconfigReg.incwhichisincludedfromTUT452.asm.
a. TheLEDshavebeenenabledbyfittingjumperJ6.3. PowerthePICDEM2Plusboardusingthe5Vplugpacksuppliedandthenconnecttheboardtothe
ICD3usingtheshortRJ11cable.4. ClicktheMakeandProgramDeviceMainProjecticon(bluerectanglewithdownwardsgreen
arrow).MPLABwillattempttoconnecttothetargetboardthroughtheICD3.YouwillseeaCautionmessagepopup,warningyoutocheckthatthedeviceselectedinMPLABisthesameoneasisactuallyonthetargetboard;youcansafelydismissthismessage.
5. MPLABshouldconnecttothetargetboard,programthemicrocontrollerandverifythatprogrammingwascorrect.TheOutputWindowshouldappearasinFigure8.
Figure8:OutputWindowafterexecutablesuccessfullydownloadedtotarget.
7.1WhatshouldtheTUT452.asmprogramdo?Whenrun,theprogramTUT452.asmrepeatedlyconvertstheanalogvoltagethatispresentonanalogtodigitalchannel0toaneightbitnumber,scalesthatnumbertolieintherange0to15andthenwritesthescalednumbertothedigitaloutputportPORTB.WhenrunonaPICDEM2PlusDemoBoard(MicrochipDM163022)theanalogvoltagevariesbetween0Vand+5VasthepotentiometerRA0isturned,andthescalednumbervariesbetween0and15.IfthesoftwareandhardwareareworkingtogethercorrectlyyoushouldseetheLEDschangingbetween1and15inbinaryasyouturnthepotentiometer.7.2RunTUT452.asmprogramtoverifythatitworkscorrectlyTheMPLABICD3executesusercodeineitherrealtimemodeorinstepmode.RealtimeexecutionoccurswhenthePIC18F452inthePICDEM2PlusdemoboardisputintheMPLABIDEsrunmode.Theuserprogramexecutesatthefullspeedofthehardwareclockonthetargetboard4MHzinthiscase.Instepmode,executionofthetargetprocessoriscontrolledbyMPLABthroughtheICD3.Theusercan,forexample,executeasingleassemblylanguageinstruction,orexecutethecodeuntilabreakpointisreached.TheiconsintheMPLABXRunToolbararedescribedinFigure9.WhenexecutionofusercodeishaltedundercontroloftheICD3theusercaninspectorchangethevaluesinanyofthemicrocontrollersregisters.
1. NowletusseeiftheTUT452.asmprogramexecutescorrectly.Duringadebugsession,executionoftheprogramiscontrolledbytheICD3throughMPLABX,sowemustfirstlaunceadebugsession.ClickontheDebugMainProjecticon(codelistingschematicwithsmallrightfacinggreenarrow)andseveralthingswilloccur:firstlytheprojectwillberebuiltifnecessary.SeveraltabswillopenintheOutputWindowandyouwillagainseeaCautionmessagepopup,warningyoutocheckthatthedeviceselectedintheMPLABprojectconfigurationisthesameoneasisactuallyonthetargetboard;youcansafelydismissthismessage.Theexecutablecodewillthenbedownloadedtothetargetboardandexecuted.MPLABXwillthenlooksomethinglikeFigure9.
2. YoucanturnthepotentiometerallyoulikebutnoneofthePORTBLEDswilllightbecausetheprogramTUT452.asmisdeliberatelybroken...
8
Figure9:Startofdebuggingsession.
Table1:ButtonsontheRuntoolbar.DebuggerMenu Button ActionFinishDebuggerSession Exitfromthedebuggersession.Pause FinishthecurrentinstructionandgivecontroltoMPLABReset SetthePCtotheresetaddress(0x0000)Continue ResumerunningtheuserprogramStepOver Atafunctioncall,stepoverthefunctionStepInto Atafunctioncall,stepintothefunctionRuntoCursor Resumerunninguserprogram,pauseatcursorSetPCtoCursor Whatitsays!Equivalentofjumptocursor.FocusCursoratPC
9
7.3DebugTUT452.asmAnyofthefollowingcouldpreventtheTUT452programfromworking.
ThejumperJ6isnotfitted,sotheLEDswillneverlight.Checkit! TheA/DconvertervalueisnotbeingproperlywrittentothePORTBLEDs. TheA/Dconverterisnotenabledorhasnotbeensettostartaconversion. Atypingerrorinthesourcecodeiscausingtheprogramtofunctionimproperly.
WewillinvestigatethesepossibilitiesintheDebugsession.Toexplorethesecondpossibility,wewanttosetabreakpointatthelineofthefilethatwritesthevalueoftheA/DresulttoPORTBsothatuserprogramexecutionwillpausethere.Whentheprogramispausedwecaninspectvaluesinthemicrocontrollersregisters.
1. First,clickonthePauseiconNOTtheFinishDebugSessioniconsincethiswillclosethesession,disconnectingtheICD3fromMPLAB.OnPause,thecurrentlyexecutinginstructionfinishesandMPLABshowsthenextinstructiontobeexecutedbyhighlightingthewholelinewithalightgreenbackground.
2. Next,clicktheReseticon.ThisresetsthemicrocontrollersPC(programcounterregister)totheresetaddressandsetsallotherregisterstotheirresetvalues.Runningtheprogramfromhereisthesameasitcomingoutofreset.
3. Now,clickthecursoronthefollowinglineofcodefromTUT452.asmintheEditorWindow:movwf PORTB ;Write A/D result to PORTB
4. RightclickonthelinetodisplayashortcutmenuandselectToggleLineBreakpoint.ThissetsabreakpointatthelinewhichismarkedascanbeseeninFigure10.
Figure10:Breakpointsetatline56.
10
5. Next,clicktheRunicontoagainfreeruntheuserprogram.Ifprogramexecutioneverreachesthebreakpointtheprogramwillpausebeforeexecutingthelineatwhichthebreakpointisset.However,thesampleprogramdoesnotpausesoitisneverreachingthebreakpoint.
6. ClickPausetopausetheprogramwhereverithappenstobe.IntheEditWindow,theprogramwillhavehaltedononeofthetwolinesunderthelabelWaitForAdConversion.TryRunandPauseafewmoretimestheprogramwillalwayspauseatoneofthesetwolines.Basedonthepauselocationandthefactthattheprogramneverreachesthebreakpoint,itcanbeconcludedthattheproblemisintheA/Dconversion.Theprogramatline51testsabitforA/Dconversioncomplete;thisbitneverbecomesset.A/DinitializationoccursundertheSetuplabelatthebeginningoftheprogram.
7. Toverifythattheflagbit(bitADIFinregisterPIR1)isnotbeingset,ClickontheSFRtabintheOutputWindow.ThisshowstheSpecialFunctionRegisterswhicharethemicrocontrollerscontrolandstatusregisters.ClickonNametosorttheSFRsbyname,thenscrolldownandclickonPIR1.IfyouhoverthemouseoverthetextPIR1,MPLABwillshowthesymbolicnamesofthebitsintheregisterascanbeseeninFigure11.ADIFisbit6anditisalwayszerotheA/Dconversionnevercompletes.TheA/DconverterinthePIC18F452hasanorganisationsuchthatifaconversionstartsthenitmustcomplete.TheA/Dconversionisthereforenotstarting.
Figure11:InspectingthevalueofbitsinthePIR1registerwiththeprogrampaused.
8. A/DconversionnotstartingcouldbecausedbyincorrectconfigurationoftheA/Dhardware,orbytheprogramsfailuretoinitiateaconversion.Toinvestigate,firstclickReset.ThensetabreakpointatthefirstinstructionafterthelabelSetup.ClickonthefollowinglineofcodefromTUT452.asm:
clrf PORTB ;Clear PORTB Thenrightclickonthelineandtogglethebreakpointattheline.
11
9. WewillwanttoinspectthevaluesthatarewrittenintothetworegistersADCON0andADCON1.ThesetworegisterscontainthecontrolandstatusbitsfortheA/Dconverterhardware.WewanttoinspecthowtheA/Dconverterisconfigured.AWatchWindowisanotherwaytoinspectregisters(andvariables).ClickDebugandthenselectNewWatch.Inthepopup,clickonSFRs,thenselectADCON0andADCON1andclick[OK].TheVariablesWindowwillopen,showingthestateofthetworegistersthatwehaveadded.
10. Beforecontinuing,makesurethatUnlimitedBP(S/W)isEnabledunderDebugResourcesintheDashboard.Thisenablessoftwarebreakpoints.Onlyonehardwarebreakpointcanbeactive,butanunlimitednumberofsoftwarebreakpointscanbeused.
11. Nowrunthecodeagain:clickResetthenContinue.Executionwillpausebeforeexecutingthelineofcodeatthebreakpoint.MPLABwilllooklikeFigure12.Line31(thebreakpoint)hasnotexecuted.Thelittlegreenarrowpointstothenextinstructiontobeexecuted.
Figure12:Programpausedatbreakpointatline31.
12. Now,singlestepthecodefivetimes,inspectingthevaluesinADCON0andADCON1aftereachstep.YoucanuseStepOverorStepInto:itdoesntmatterhereasthereisnofunctioncall.PayparticularattentiontothevaluesinADCON0andADCON1whentheinstructionsmovwf ADCON0andmovwf ADCON1execute.Theseinstructionsmovevaluesintotheregisters.Youwillseethatthevalueschange;theyareshowninredtoindicatethattheychangedasaresultofthepreviousinstruction.Thefollowinglineofcodeshouldbeindicatedwhenfinished:
movlw B11000111 ;TMR0 prescaler, 1:256 13. NoticethatADCON0hasavalueof0x40.Thiscorrespondstothebinaryvaluedesignatedinthe
program,butisthisvaluecorrect?IfyouexpandthedisplayofADCON0intheVariablesWindowthevalueofeachbitwillbeshownascanbeseeninFigure13.
12
Figure13:VariablesWindowshowingvaluesofADCON0bits.
14. InFigure13,bit0ofADCON0hasthesymbolicnameADON,andthevalue0.AreviewofthePIC18F452DataSheetsectiononA/D(Chapter17)indicatesthatfunctionofthisbitistoenabletheA/Dcircuitry.Theconversionisneverfinishingbecauseitisneverstarting,anditisneverstartingbecausetheA/Dhardwaremoduleisnotenabled.
15. TheleastsignificantbitofADCON0shouldbeaone,notazero,toenabletheA/Dmodule.Tofixthisbug,change:
movlw B01000000 ;Fosc/8, A/D enabled to:
movlw B01000001 ;Fosc/8, A/D enabled 16. Torebuildtheprojectwehavetogetoutofthedebuggingsession,soclickonFinishDebugger
Session.ClickingonDebugMainProjectwillforcearebuildoftheproject,followedbydownloadingandrunningonthetargetboard.
17. WhenthecodeexecutesyoushouldseetheLEDscountinginbinaryasthepotentiometerRA0isturned.
Thesourcecodeinthistutorialcontainedonlyonesimplebug.Realcodeiscertaintohavemore,particularlywhenyouarelearninganewprocessor.UsingtheMPLABICD3andMPLABIDEdebuggingfunctions,togetherwithcarefulthoughtandsimpleexperimentation,userscansuccessfullyfindandfixallproblemsintheircode.
8 PROGRAMMINGTHEAPPLICATIONWhentheprogramissuccessfullydebuggedandrunning,usuallythelaststepistoprogramthemicrocontrollerforstandaloneoperationinthefinisheddesign.Whendoingthis,theresourcesreservedbytheICDarereleasedforusebytheapplication.ThedevicecanbeprogrammedfromwithinMPLABXbyfollowingthesesteps:
1. EndthedebuggingsessionbyclickingFinishDebuggerSession.2. ClickonMakeandProgramDeviceMainProject.Thiswillrebuildtheprojectasaproductionbuild
(whichdoesnotincludethesmalldebugmonitorprogramforcommunicatingwiththeICD3),programthemicrocontrollerandruntheprogram.YouwillbeabletodisconnecttheICD3fromthetargetboard,powercyclethetargetboardandtheprogramwillexecute.
13
;********************************************************** ;* 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 ; Include file, change directory if needed include "p18f452.inc" include "configReg.inc" ; Start at the reset address. There *must* be code at address ; 0x000 since the PC is loaded with address 0 when the processor ; comes out of reset. This declares a code section named 'RST'. RST code 0x0000 goto Setup ; Start application beyond vector area. ; This declares an 'unnamed' code section. code 0x0030 Setup: clrf PORTB ; Clear PORTB clrf TRISB ; PORTB all outputs, display 4 MSB's ; of A/D result on LEDs movlw B'01000000' ; Fosc/8, A/D enabled movwf ADCON0 movlw B'00001110' ; Left justify, 1 analog channel movwf ADCON1 ; VDD and VSS references movlw B'11000111' ; TMR0 prescaler, 1:256 movwf T0CON Main: btfss INTCON, TMR0IF ; Wait for Timer0 to timeout goto Main bcf INTCON, TMR0IF bsf ADCON0, GO ; Start A/D conversion WaitForAdConversion: btfss PIR1, ADIF ; Wait for conversion to complete goto WaitForAdConversion swapf ADRESH, W ; Swap A/D result nibbles andlw 0x0f ; Mask off lower 4 bits movwf PORTB ; Write A/D result to PORTB clrf PORTB WaitForSwitchRelease: ; Pause while switch is pressed btfss PORTA, 4 goto WaitForSwitchRelease movwf PORTB goto Main ; Do it again end