Вы находитесь на странице: 1из 13

1

MPLABX/ICD3Tutorial
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(\ \ mxl abser ver \ User s)OR
b. createandassignpermissionstoadirectoryontheV: drive( \ \ mxl abser ver \ Gr oups)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
Tut e0. XunderyourDemodirectorytostoretheproject,andwillignoresubfoldersaccordingtotheregular
expression^( nbpr oj ect | bui l d| t est ) $.

Figure4:ProjectPropertiesGeneralconfiguration.
PleasechecktomakesurethatinthePoweroptionscategoryoftheICD3configuration(Figure5)that
PowertargetcircuitfromICD3isNOTselectedsincewewillalwayspowerthetargetmicrocontrollerboard
andothercircuitryfromanexternalpowersupply.

Figure5:ProjectPropertiesICD3Powerconfiguration.
5 ADDINGSOURCEFILESTOTHEPROJECT
5.1Obtainthesourcefiles
Youfirstneedtoobtainthetwoassemblylanguagefilesthatyouwillneedforthetutorialandplacethemin
thedirectorythatyoumadeinstep2.
1. OnthedesktopthereisalinktoCour sewor k Fi l es on Ser ver .Openthatlinkandgoto
Mt r x3700\ I ni t i al Wor kspace\
2. CopythefilesfromI ni t i al Wor kspaceintothedirectoryDemo\ Tut e0. 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/ Tut e0. X/ di st / def aul t / pr oduct i on/ Tut e0. X. pr oduct i on. hexThis
istheexecutablebinaryfilereadytobeloadedintotheparticularmicrocontrollerand
executed.
6

b. Demo/ Tut e0. X/ di st / def aul t / pr oduct i on/ Tut e0. X. pr oduct i on. cof
Thisisafileincommonobjectfileformat(COFF)thatcontainssymbols(variablenames,
etc)fromthesourcecodeandassociatedaddresses.ItallowstheIDEtoshowyouthesource
codeinsteadofmemoryaddresseswhendebugging.
c. IntermediatefilesarealsoproducedfilesTUT452. er r ,TUT452. l st , TUT452. oand
TUT452. o. dinthedirectoryDemo/ Tut e0. X/ bui l d/ def aul t / pr oduct i on/

Figure6:Projectwithasingleassemblylanguagefileadded.

Figure7:OutputWindowaftersuccessfulbuild.
7. DEBUGGINGTHEPROJECT
NowthattheprojectbuildswecandownloadittothetargetboardinthiscaseaPICDEM2Plusand
attempttorunthecode.
1. Important:TheICD3shouldbeconnectedtothePCviaaUSBcableatthispoint,providingpowerto
theICD3.
2. MakesurethePICDEM2PlusDemoBoardissetupasfollows:
7

d. ThepackagedoscillatorhasbeenselectedbyremovingjumperJ7.Thisselectstheclock
hardwarethatmatchesthewaythatthemicrocontrollerclockcircuitshavebeenconfigured
bytheECOSCselectioninconf i gReg. i ncwhichisincludedfromTUT452. 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 ; Wr i t e A/ D r esul t t o PORTB
4. RightclickonthelinetodisplayashortcutmenuandselectToggleLineBreakpoint.Thissetsa
breakpointatthelinewhichismarkedascanbeseeninFigure10.

Figure10:Breakpointsetatline56.
10

5. Next,clicktheRunicontoagainfreeruntheuserprogram.Ifprogramexecutioneverreachesthe
breakpointtheprogramwillpausebeforeexecutingthelineatwhichthebreakpointisset.However,
thesampleprogramdoesnotpausesoitisneverreachingthebreakpoint.
6. ClickPausetopausetheprogramwhereverithappenstobe.IntheEditWindow,theprogramwillhave
haltedononeofthetwolinesunderthelabelWai t For AdConver si on.TryRunandPauseafew
moretimestheprogramwillalwayspauseatoneofthesetwolines.
Basedonthepauselocationandthefactthattheprogramneverreachesthebreakpoint,itcanbe
concludedthattheproblemisintheA/Dconversion.Theprogramatline51testsabitforA/D
conversioncomplete;thisbitneverbecomesset.A/DinitializationoccursundertheSetuplabelatthe
beginningoftheprogram.
7. Toverifythattheflagbit(bitADI FinregisterPI R1)isnotbeingset,ClickontheSFRtabintheOutput
Window.ThisshowstheSpecialFunctionRegisterswhicharethemicrocontrollerscontrolandstatus
registers.ClickonNametosorttheSFRsbyname,thenscrolldownandclickonPIR1.Ifyouhoverthe
mouseoverthetextPIR1,MPLABwillshowthesymbolicnamesofthebitsintheregisterascanbe
seeninFigure11.ADI Fisbit6anditisalwayszerotheA/Dconversionnevercompletes.TheA/D
converterinthePIC18F452hasanorganisationsuchthatifaconversionstartsthenitmustcomplete.
TheA/Dconversionisthereforenotstarting.

Figure11:InspectingthevalueofbitsinthePIR1registerwiththeprogrampaused.
8. A/DconversionnotstartingcouldbecausedbyincorrectconfigurationoftheA/Dhardware,orbythe
programsfailuretoinitiateaconversion.Toinvestigate,firstclickReset.Thensetabreakpointatthe
firstinstructionafterthelabelSetup.ClickonthefollowinglineofcodefromTUT452. asm:
cl r f PORTB ; Cl ear PORTB
Thenrightclickonthelineandtogglethebreakpointattheline.
11

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:
movl w B 11000111 ; TMR0 pr escal er , 1: 256
13. NoticethatADCON0hasavalueof0x40.Thiscorrespondstothebinaryvaluedesignatedinthe
program,butisthisvaluecorrect?IfyouexpandthedisplayofADCON0intheVariablesWindowthe
valueofeachbitwillbeshownascanbeseeninFigure13.

12

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:
movl w B 01000000 ; Fosc/ 8, A/ D enabl ed
to:
movl w B 01000001 ; Fosc/ 8, A/ D enabl ed
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.

13

; **********************************************************
; * TUT452. asm
; **********************************************************
; * Mi cr ochi p Technol ogy I ncor por at ed
; * 17 Mar ch 2003
; * Assembl ed wi t h MPASM V3. 20 and MPLI NK v3. 20
; **********************************************************
; * Thi s pr ogr amconf i gur es t he A/ D Modul e t o conver t on
; * A/ D channel 0 ( t he pot ent i omet er ) and di spl ay t he
; * r esul t s on t he LEDS on PORTB.
; **********************************************************

l i st p=18f 452

; I ncl ude f i l e, change di r ect or y i f needed
i ncl ude " p18f 452. i nc"
i ncl ude " conf i gReg. i nc"


; St ar t at t he r eset addr ess. Ther e *must * be code at addr ess
; 0x000 si nce t he PC i s l oaded wi t h addr ess 0 when t he pr ocessor
; comes out of r eset . Thi s decl ar es a code sect i on named ' RST' .
RST code 0x0000
got o Set up


; St ar t appl i cat i on beyond vect or ar ea.
; Thi s decl ar es an ' unnamed' code sect i on.
code 0x0030
Set up:
cl r f PORTB ; Cl ear PORTB
cl r f TRI SB ; PORTB al l out put s, di spl ay 4 MSB' s
; of A/ D r esul t on LEDs

movl w B' 01000000' ; Fosc/ 8, A/ D enabl ed
movwf ADCON0
movl w B' 00001110' ; Lef t j ust i f y, 1 anal og channel
movwf ADCON1 ; VDD and VSS r ef er ences

movl w B' 11000111' ; TMR0 pr escal er , 1: 256
movwf T0CON

Mai n:
bt f ss I NTCON, TMR0I F ; Wai t f or Ti mer 0 t o t i meout
got o Mai n
bcf I NTCON, TMR0I F

bsf ADCON0, GO ; St ar t A/ D conver si on

Wai t For AdConver si on:
bt f ss PI R1, ADI F ; Wai t f or conver si on t o compl et e
got o Wai t For AdConver si on

swapf ADRESH, W ; Swap A/ D r esul t ni bbl es
andl w 0x0f ; Mask of f l ower 4 bi t s
movwf PORTB ; Wr i t e A/ D r esul t t o PORTB

cl r f PORTB

Wai t For Swi t chRel ease: ; Pause whi l e swi t ch i s pr essed
bt f ss PORTA, 4
got o Wai t For Swi t chRel ease

movwf PORTB
got o Mai n ; Do i t agai n

end

Вам также может понравиться