0% found this document useful (0 votes)
53 views

Appendix A - Programming A Microcontroller - Book - PIC Microcontrollers

Uploaded by

anon_448550364
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Appendix A - Programming A Microcontroller - Book - PIC Microcontrollers

Uploaded by

anon_448550364
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 1/17
TOC Introduction Ch. 1 Ch. 2 Ch. 3 Ch 4. Ch. 5 Ch. 6 Ch. 7 Ch. 8 Ch. 9 App. A App. B App. C
Book:PICMicrocontrollers
AppendixA:ProgrammingaMicrocontroller
MicrocontrollersandhumanscommunicatethroughthemediumoftheprogramminglanguagecalledAssemblylanguage.Theword
Assembleritselfdoesnothaveanydeepermeaning,itcorrespondstothenamesofotherlanguagessuchasEnglishorFrench.More
precisely,assemblylanguageisonlyapassingsolution.Inorderthatthemicrocontrollercanunderstandaprogramwritteninassembly
language,itmustbecompiledintoalanguageofzerosandones.AssemblylanguageandAssemblerdonothavethesamemeaning.The
firstonereferstothesetofrulesusedforwritingprogramforthemicrocontroller,whilethelaterreferstoaprogramonapersonalcomputer
usedtotranslateassemblylanguagestatementsintothelanguageofzerosandones.AcompiledprogramisalsocalledMachineCode.A
"Program"isadatafilestoredonacomputerharddisc(orinmemoryofthemicrocontroller,ifloaded)andwrittenaccordingtotherulesof
assemblyorsomeotherprogramminglanguage.Assemblylanguageisunderstandableforhumansbecauseitconsistsofmeaningfulwords
andsymbolsofthealphabet.Letustake,forexamplethecommand"RETURN"whichis,asitsnameindicates,usedtoreturnthe
microcontrollerfromasubroutine.Inmachinecode,thesamecommandisrepresentedbya14bitarrayofzerosandonesunderstandableby
themicrocontroller.Allassemblylanguagecommandsaresimilarlycompiledintothecorrespondingarrayofzerosandones.Adatafileused
forstoringcompiledprogramiscalledan"executivefile",i.e."HEXdatafile".Thenamecomesfromthehexadecimalpresentationofadata
fileandhasasuffixof"hex"aswell,forexample"probe.hex".Afterhasbeengenerated,thedatafileisloadedintothemicrocontrollerusinga
programmer.Assemblylanguageprogramsmaybewritteninanyprogramfortextprocessing(editor)abletocreateASCIIdatafilesonahard
discorinaspecializedworkenvironmentsuchasMPLABdescribedlater.
ELEMENTSOFASSEMBLYLANGUAGE
Aprogramwritteninassemblylanguageconsistsofseveralelementsbeingdifferentlyinterpretedwhilecompilingtheprogramintoan
executabledatafile.Theuseoftheseelementsrequiresstrictrulesanditisnecessarytopayspecialattentiontothemduringprogramwriting
inordertoavoiderrors.
ASSEMBLYLANGUAGESYNTAX
Asmentioned,itisnecessarytoobservesomespecificrulesinordertoenabletheprocessofcompilingintoexecutiveHEXcodetorun
withouterrors.Compulsoryrulesexplaininghowsequencesofexpressionsareputtogethertoformthestatementsthatmakeupanassembly
languageprogramarecalledsyntax.Thereareonlyseveralofthem:
Everyprogramlinemayconsistofamaximumof255characters
Everyprogramlinethatistobecompiledmuststartwithasymbol,label,mnemonicsordirective
Textfollowingthemark""inaprogramlinerepresentsacommentwhichisignoredbytheassembler(notcompiled)
and
Alltheelementsofoneprogramline(labels,instructionsetc.)mustbeseparatedbyatleastonespacecharacter.For
thesakeofbetterclearness,apushbuttonTABiscommonlyusedinsteadofit,sothatitiseasytodelimitcolumns
withlabels,directivesetc.inaprogram.
LABELS
AlabelrepresentsatextualversionofsomeaddressinROMorRAMmemory.Eachlabelhastostartinthefirstcolumnwithaletterof
alphabetor"_"andmayconsistofmaximumof32characters.Besides,itiseasilyused:
Itissufficienttoenterthenameofalabelinsteadofa16bitaddressininstructionwhichcallssomesubroutineora
jump.Thelabelwiththesamenameshouldalsobewrittenatthebeginningofaprogramlineinwhichasubroutine
startsorwhereajumpshouldbeexecuted.Asageneralrule,labelshaveeasilyrecognizablenames.
Duringprogramcompiling,theassemblerwillautomaticallyreplacethelabelsbythecorrespondingaddresses.
FeaturedDevelopmentTools
FreeOnlineBooks
EasyPICv7DevelopmentSystem
EasyPICv7istopsellingPIC
DevelopmentBoardfor250Microchip
PICMCUsinDIPpackaging.Itfeatures
USB2.0programmer/debuggerandover
17essentialmodulesnecessaryin
development.Boardcomeswith
PIC18F45K22.[moreinfo]
Book:PICMicrocontrollers
ProgramminginC
Whataremicrocontrollers,anyway?
Electroniccomponentsbuiltintoone
singlechipcapableofcontrollingasmall
submarine,acraneoranelevator
anything.Itsuptoyoutodecidewhat
youwantthemtodo.Youjusthaveto
writeaprogramanddumpitintothe
microcontroller.[moreinfo]
Login | Cart (0)
Products Solutions Store Distributors Libstock Contact Us search here
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 2/17
COMMENTS
Acommentisoftenanexplanatorytextwrittenbytheprogrammerinordertomakeaprogramclearerandeasiertounderstand.Itisnot
necessarytocommenteveryline.Whenthreeorfourlinesofcodeworktogethertoaccomplishsomehigherleveltask,itisbettertohavea
singlehigherlevelcommentforthegroupoflines.Therefore,itisaddedifneededandhastostartwith"".Commentsaddedtoassembly
sourcecodearenotcompiledintomachinecode.
INSTRUCTIONS
Instructionsaredefinedforeachmicrocontrollerfamilybythemanufacturer.Therefore,itisuptotheusertofollowtherulesoftheirusage.
Thewayofwritinginstructionsisalsocalledinstructionsyntax.Theinstructions"movlp"and"gotto",inthefollowingexample,are
recognizedbythePIC16F887microcontrollerasanerrorsincetheyarenotcorrectlywritten.
OPERANDS
Anoperandisavalue(anargument)uponwhichtheinstruction,namedbymnemonic,operates.Theoperandsmaybearegister,avariable,
aliteralconstant,alabeloramemoryaddress.
DIRECTIVES
Unlikeinstructionsbeingwrittentoonchipprogrammemoryaftercompilation,directivesarecommandsofassemblylanguageitselfanddo
notdirectlyaffecttheoperationofthemicrocontroller.Someofthemmustbeusedineveryprogramwhileothersareonlyusedtofacilitateor
enhancetheoperation.Directivesarewrittentothecolumnreservedforinstructions.Therulewhichmustbeobservedallowsonlyone
directiveperprogramline.
Thissectioncoversonlyafewofthemostcommonlyuseddirectives.Itwouldcertainlytakeuptoomuchspaceandtimetodescribeallthe
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 3/17
directivesrecognizedbytheMPLABprogram.Anyway,acompletelistcontainingalldirectiveswhichtheMPLABassemblercanunderstand
isprovidedinHelp.
PROCESSORDirective
Thisdirectivemustbewrittenatthebeginningofeachprogram.Itdefinesthetypeofthemicrocontrollerwhichtheprogramiswrittenfor.For
example:
Processor16f887
EQUdirective
Thisdirectiveisusedtoreplaceanumericvaluebyasymbol.Inthisway,someaspecificlocationinmemoryisassignedaname.For
example:
MAXIMUMEQUH25
Thismeansthatamemorylocationataddress25(hex.)isassignedthename"MAXIMUM".Everyappearanceofthelabel"MAXIMUM"inthe
programwillbeinterpretedbytheassemblerastheaddress25(MAXIMUM=H25).Symbolsmaybedefinedthiswayonlyonceina
program.Thatthisdirectiveismostlyusedatthebeginningoftheprogram.
ORGdirective
Thisdirectivespecifiesalocationinprogrammemorywheretheprogramfollowingdirectiveistobeplaced.Forexample:
ORG0x100
START......
...
ORG0x1000
TABLE...
...
Thisprogramstartsatlocation0x100.Thetablecontainingdataistobestoredatlocation1024(1000h).
ENDdirective
Eachprogrammustbeendedbyusingthisdirective.Onceaprogramencountersthisdirective,theassemblerimmediatelystopscompiling.
Forexample:
...
ENDEndofprogram
\$INCLUDEdirective
Thenameofthisdirectivefullyindicatesitspurpose.Duringcompiling,itenablestheassemblertousedatacontainedinanotherfileona
computerharddisc.Forexample:
...
#include<p16f887.inc>
CBLOCKandENDCdirectives
Allvariables(theirnamesandaddresses)thatwillbeusedinaprogrammustbedefinedatthebeginningoftheprogram.Becauseofthisitis
notnecessarytospecifytheaddressofeachspecifiedvariablelaterintheprogram.Instead,itisenoughtospecifytheaddressofthefirstone
byusingdirectiveCBLOCKandlistallothersafterwards.Thecompilerautomaticallyassignsthesevariablesthecorrespondingaddressesas
pertheordertheyarelisted.Lastly,thedirectiveENDCindicatestheendofthelistofvariables.
CBLOCK0x20
STARTaddress0x20
RELEaddress0x21
STOPaddress0x22
LEFTaddress0x23
RIGHTaddress0x24
ENDC
...
IF,ENDIFandELSEdirectives
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 4/17
Thesedirectivesareusedtocreatesocalledconditionalblocksinaprogram.EachoftheseblocksstartswiththedirectiveIFandendswith
thedirectiveENDIForELSE.Astatementorasymbol(inparentheses)followingthedirectiveIFrepresentsaconditionwhichdetermines
whichpartoftheprogramistobecompiled:
Ifthestatementiscorrectorthevalueofasymbolisequaltoone,programcompilesallinstructionswrittenbefore
directiveELSEorENDIFand
Ifthestatementisnotcorrectorthevalueofasymbolisequaltozero,onlyinstructionswrittenafterdirectivesELSE
orENDIFaretobecompiled.
Example1:
IF(VERSION>3)
CALLTable_2
CALL
ENDIF
...
Iftheprogramisreleasedaftertheversion3(statementisright)thensubroutines"Table2"and"Extension"areexecuted.Ifthestatementin
parenthesesiswrong(VERSION<3),twoinstructionscallingsubroutinesareignoredandwillnotbecompiledtherefore.
Example2:
Ifthevalueofsymbol"Model"isequaltoonethenfirsttwoinstructionsafterdirectiveIFarecompiledaswellasinstructionsafterdirective
ENDIF(allinstructionsbetweenELSEandENDIFareignored).Otherwise,ifModel=0theninstructionsbetweenIFandELSEareignored,
whereasinstructionsafterdirectiveELSEarecompiled.
IF(Model)
MOVFWBUFFER
MOVWFMAXIMUM
ELSE
MOVFWBUFFER1
MOVWFMAXIMUM
ENDIF
...
BANKSELdirective
InordertoaccessanSFRregisteritisnecessarytoselecttheappropriatebankinRAMmemorybyusingbitsRP0andRP1oftheSTATUS
register.Thisdirectiveisusedinthiscase.Simply,since"inc"datafilecontainsthelistofallregistersalongwiththeiraddresses,the
assemblerknowswhichbankcorrespondstowhichregister.Afterencounteringthisdirective,assemblerselectsthebitsRP0andRP1forthe
specifiedregisteronitsown.Forexample:
...
BANKSELTRISB
CLRFTRISB
MOVLWB01001101
BANKSELPORTB
MOVWFPORTB
...
EXAMPLEOFHOWTOWRITEAPROGRAM
Thefollowingexampleillustrateswhatasimpleprogramwritteninassemblylanguagelookslike.
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 5/17
Apartfromtheregularrulesofassemblylanguage,therearealsosomeunwrittenruleswhichshouldbeobservedduringprogramwriting.One
ofthemistowriteinafewwordsatthebeginningofaprogramwhattheprogramsnameis,whatitisusedfor,version,releasedate,typeof
themicrocontrolleritiswrittenforandthenameoftheprogrammer.Sincethisinformationisnotofimportancefortheassembler,itiswritten
asacommentwhichalwaysstartswithsemicolonandcanbewritteninanewlineorimmediatelyafteracommand.
Afterwritingthisgeneralcomment,itistimetoselectthemicrocontrollerbyusingdirectivePROCESSOR.Thisdirectiveisfollowedbyanother
oneusedtoincludeallthedefinitionsofthePIC16F887microcontrollersinternalregistersintheprogram.Thesedefinitionsarenothingbut
theabilitytoaddressportBandotherregistersasPORTBinsteadof06h,whichmakestheprogramclearerandmorelegible.
Inorderthatthemicrocontrollerwilloperateproperly,aseveralparameterssuchasthetypeofoscillator,stateofthewatchdogandinternal
resetcircuitmustbedefined.Itisdonebyutilizingthefollowingdirective:
_CONFIG_CP_OFF&_WDT_OFF&PWRTE_ON&XT_OSC
Whenallnecessaryelementsaredefined,theprocessofprogramwritingcanstart.Firstandforemost,itisnecessarytospecifytheaddress
fromwhichthemicrocontrollerstartswhenthepowergoeson(org0x00)aswellastheaddressfromwhichtheprogramproceedswith
executionifaninterruptoccurs(org0x04).Sincethisprogramisverysimple,itisenoughtousecommand"gotoMain"inordertodirect
themicrocontrollertothebeginningoftheprogram.Thenextcommandselectsmemorybank1inordertoenableaccesstotheTRISB
registertoconfigureportBasoutput(bankselTRISB).Themainprogramendsbyselectingmemorybank0andsettingallportBpinsto
logicone(1)(movlw0xFF,movwfPORTB).
Itisnecessarytocreatealooptokeepprogramfrom"gettinglost"incaseanerroroccurs.Forthispurpose,thereisanendlessloopexecuted
allthetimewhilethemicrocontrollerisswitchedon.
"end"isrequiredattheendofeveryprogramtoinformtheassemblerthattherearenomorecommandstobecompiled.
DATAFILESRESULTINGFROMPROGRAMCOMPILING
Theresultofcompilingaprogramwritteninassemblylanguagearedatafiles.Themostimportantandmostcommonlyuseddatafilesare:
Executivedatafile(Program_Name.HEX)
Errordatafile(Program_Name.ERR)and
Listdatafile(Program_Name.LST).
Thefirstfilecontainscompiledprogramwhichisloadedintothemicrocontroller.Itscontentsgivenoinformationofimportancetothe
programmersoitwillnotbediscussedhere.Thesecondfilecontainserrorsmadeinwritingprocessanddetectedbythecompilerduring
compilingprocess.Errorscanbedetectedinlistdatafile,whichtakesmoretime,sotheerrordatafileismoresuitableforlongprograms.
Thethirdfileisthemostusefulfortheprogrammer.Itcontainslotsofinformationoncommandsandvariableslocationsinonchipmemoryas
wellaserrorsignalization.Thereisasymboltableattheendofeachdatafilelistcontainingallthesymbolsusedinaprogram.Otheruseful
elementsoflistdatafilearememoryusagemapsanderrorstatisticsprovidedattheveryendofthefilelist.
MACROSANDSUBROUTINES
Thesamesequenceofcomputinginstructionsisusuallyusedrepeatedlywithinaprogram.Assemblylanguageisverydemanding.The
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 6/17
programmerisrequiredtotakecareofthelastlittledetailwhenwritingaprogram,becauseonlyonewrongcommandorlabelnamemay
causetheprogramtonotworkproperlyoritmaynotworkatall.Therefore,itislesstediousandlesserrorpronetouseasequenceof
instructionsasasingleprogramstatementwhichworksproperlyforsure.Toimplementthisidea,macrosandsubroutinesareused.
MACROS
Amacrocontainsprogrammerdefinedsymbolsthatstandforasequenceoftextlines.Itisdefinedbyusingdirectivemacrowhichnames
macroandargumentsifneeded.Macromustbedefinedprioritisused.Onceamacrohasbeendefined,itsnamemaybeusedinthe
program.Whentheassemblerencountersmacrosname,itreplacesitbytheappropriatesequenceofinstructionsandprocessesthemjustas
thoughtheyhaveappearedintheprogram.Manydifferentmacroinstructionsareavailableforvariouspurposes,eliminatingsomeofthe
repetitivenessoftheprogramming,aswellassimplifyingthewriting,readingandunderstandingoftheprogram.Thesimplestuseofmacros
maybegivinganametoaninstructionsequencebeingrepeated.Letustake,forexample,globalinterruptenableprocedure,SFRs'bank
selection.
macro_namemacroarg1,arg2...
...
sequenceofinstructions
...
endm
Thefollowingexampleshowsfourmacros.Thefirsttwomacrosselectbanks,thethirdoneenablesinterrupt,whereasthefourthonedisables
interrupt.
bank0macroMacrobank0
bcfSTATUS,RP0ResetRP0bit
bcfSTATUS,RP1ResetRP1bit
endmEndofmacro
bank1macroMacrobank1
bsfSTATUS,RP0SetRP0bit
bcfSTATUS,RP1ResetRP1bit
endmEndofmacro
enableintmacroGlobalinterruptenable
bsfINTCON,7Setbit
endmEndofmacro
disableintmacroGlobalinterruptdisable
bcfINTCON,7Resetbit
endmEndofmacro
MacrosdefinedinthiswayaresavedinaparticulardatafilewithextensionINCwhichstandsforINCLUDEdatafile.Asseen,thesefour
macrosdonothavearguments.However,macrosmayincludeargumentsifneeded.
Thefollowingexampleshowsmacroswitharguments.PinisconfiguredasinputifthecorrespondingbitoftheTRISregisterissettologicone
(bank1).Otherwise,itisconfiguredasoutput.
inputmacroarg1,arg2MacroInput
bank1BankcontainingTRISregisters
bsfarg1,arg2Setthespecifiedbit(1=Input)
bank0Macroforbank0selection
endmEndofmacro

outputmacroarg1,arg2MacroOutput
bank1BankcontainingTRISregisters
bcfarg1,arg2Clearthespecifiedbit(0=Output)
bank0Macroforbank0selection
endmEndofmacro
Macrowithargumentsmaybecalledinthefollowingway:
...
outputTRISB,7PinRB7isconfiguredasoutput
...
Whencallingthismacro,thefirstspecifiedargumentTRISBisreplacedbythefirstargumentarg1inmacrodefinition.Similarly,number7is
replacedbytheargumentarg2,andthefollowingcodeisgenerated:
...
bsfSTATUS,RP0SetRP0bit=BANK1
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 7/17
bcfSTATUS,RP1ResetRP0bit=BANK1
bcfTRISB,7ConfigureRB7asoutput
bcfSTATUS,RP0ClearRP0bit=BANK0
bcfSTATUS,RP1ClearRP1bit=BANK0
...
Itisclearatfirstsightthattheprogrambecomesmorelegibleandflexiblebyusingmacros.Themaindisadvantageofmacroisthatit
occupiesalotofmemoryspacebecauseeverymacronameinaprogramisreplacedbyitspredefinedcode.Owingtothefactthatprograms
oftenusemacro,everythingismorecomplicatedifitislong.
callcmacrolabelMacrocallc
localExitDefinelocalLabelwithinmacro
bncExitIfC=0jumptoExit
calllabelIfC=1callsubroutineataddressLabel(outofmacro)
ExitLocalLabelwithinmacro
endmEndofmacro
Intheeventthatamacrohaslabels,theymustbedefinedaslocalonesbyusingdirectivelocal.Thegivenexamplecontainsmacrowhich
callsasubroutine(calllabelinthiscase)iftheCarrybitoftheSTATUSregisterisset.Otherwise,thefirstfollowinginstructionis
executed.
SUBROUTINES
Asubroutinecontainsasequenceofinstructions,beginswithalabel(subroutine_name)andendswithcommandreturnorretlw.Themain
differencecomparingtomacroisthatsubroutineisnotreplacedbyitscodeintheprogram,butprogramjumpstosubroutinetoexecuteit.It
happenseverytimetheassemblerencounterscommandcallSubroutine_nameintheprogram.Onthecommandreturn,itleavesa
subroutineandcontinuesexecutionfromwhereitleftoffthemainprogram.Subroutinemaybedefinedbothpriortooruponthecall.
Asseen,concerningmacros,theinputandoutputargumentsareofgreatimportance.Concerningsubroutines,itisnotpossibletodefine
argumentswithinthesubroutineitself.However,variablespredefinedinthemainprogrammaybeusedassubroutinearguments.
Alogicalsequenceofeventsisasfollows:definingvariables,callingsubroutinewhichusesthemandattheendreadingvariableschanged
upontheexecutionofsubroutine.
Theprograminthefollowingexampleperformsadditionoftwo2bytevariablesARG1andARG2andmovesresulttothevariableRES.When
2bytevariablesareused,itisnecessarytodefinehigherandlowerbyteforeachofthem.Theprogramitselfisverysimple.Itfirstaddslower
bytesofvariablesARG1andARG2andhigherafterwards.Ifthesumofadditionoftwolowerbytesisgreaterthan255(maximalbytevalue)
theremainderisaddedtotheRESHvariable.
Programtoaddtwo16bitnumbers
Version:1.0Date:April25,2007MCU:PIC16F887
PROCESSOR16f887Definingprocessor
#include"p16f887.inc"MicrochipINCdatabase
__CONFIG_CP_OFF&_WDT_OFF&_PWRTE_ON&_XT_OSC

Cblock0x20BeginningofRAM
ARG1HArgument1higherbyte
ARG1LArgument1lowerbyte
ARG2HArgument2higherbyte
ARG2LArgument2lowerbyte
RESHResulthigherbyte
RESLResultlowerbyte
endcEndofvariables
ORG0x00Resetvector
gotoStart
StartWritevaluestovariables
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 8/17
movlw0x01ARG1=0x0104
movwfARG1H
movlw0x04
movwfARG1L
movlw0x07ARG2=0x0705
movwfARG2H
movlw0x05
movwfARG2L
MainMainprogram
callAdd16CallsubroutineAdd16
LoopgotoLoopRemainhere
Add16Subroutinetoaddtwo16bitnumbers
clrfRESHRESH=0
movfARG1L,ww=ARG1L
addwfARG2L,ww=w+ARG2L
movwfRESLRESL=w
btfscSTATUS,CIstheresultgreaterthan255?
incfRESH,fIfgreater,incrementRESHbyone

movfARG1H,ww=ARG1H
addwfARG2H,ww=w+ARG2
addwfRESH,fRESH=w
returnReturnfromsubroutine
endEndofprogram
InShort
Themaindifferencebetweenmacrosandsubroutinesisthatmacroisaftercompilingreplacedbyitscode(enablestheprogrammertotype
less).Itmayalsohaveargumentswhilesubroutineuseslessmemory,butdoesnothavearguments.
MPLAB
MPLABisaWindowsprogrampackagewhichenableseasyprogramwritingaswellaseasyprogramdevelopment.Itisbesttodescribeitas
developmentenvironmentforastandardprogramlanguagedesignedforPCprogramming.MPLABtechnicallysimplifiessomeoperations
consistingofalotofparameters,which,untiltheIDEenvironment*appeared,wereexecutedfromthecommandline.However,tastesare
differentandtherearesomeprogrammerswhopreferstandardeditorsandcommandlinecompilers.EveryprogramwritteninMPLABis
clear,buttherearealsohelpdocumentationjustincase.
INSTALLINGMPLAB
MPLABconsistsofseveralparts:
Theprogramwhichsortsdatafilesofthesameprojectintoonegroup(ProjectManager)
programfortextgeneratingandprocessing(TextEditor)and
simulatorusedtosimulatetheoperationofaprogramloadedintothemicrocontroller.
Besides,therearealsobuiltinprogrammerssuchasPICStartPlusandICD(InCircuitDebugger)thatcanbeusedtoprogramsoftwareinto
PICmicrocontrollerdevice.Sincenotbeingthesubjectofthisbook,theyarementionedasoptionsonly.
InordertostartMPLAB,yourPCshouldcontain:
PCcompatiblecomputerbelongingtoclass486orbetter
AnyWindowsoperatingsystem
VGAgraphiccard
8MBmemory(32MBrecommended)
200MBavailableharddiscand
Amouse.
MPLABinstallationcomesfirst.DatafilesfromMPLABCDshouldbecopiedtoaharddisc.Theprocessofinstallationissimilartoalmostall
otherWindowsprograminstallations.Firstofallawelcomewindowappears,thenoptionstoselectandatlastinstallationitself.Amessage
notifyingthattheprogramissuccessfullyinstalledandreadyforuseappears.Areyouready?
Stepstofollowpriortheinstallation:
Everythingisreadynowtostartinstallation.Thefollowingpicturesdescribetheinstallationsteps.
1. StartMicrosoftWindows
2. InserttheCDintoCDROM
3. ClickSTARTandselectoptionRUN
4. ClickBROWSEandselectCDROMdriveand
5. FindfolderMPLABonCDROM.
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 9/17
Nextwindowcontainstheword"Welcome".Need
explanation?
Actually,theprogramremindsyoutocloseallactive
programsinordertonotinterferewiththeinstallation
process.Nextofcourse!
Priortocontinue,youhavetoaccepttheMPLAB
softwarelicenseconditions.Selecttheoption"I
accept"andclickNEXT.
Doyouwanttoinstalltheentiresoftware?Yes.Next...
Similartootherprograms,MPLABshouldbealso
installedintoafolder.Itmaybeanyfolderonanyhard
disc.Ifitisnotnecessarytomakechanges,selectthe
specifiedaddressandclickNext.
Clickonthisicontostartuptheprocess...
Somethingisgoingon...Thepicturecomingupindicatesthattheprocessofinstallationhasjuststarted!
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 10/17
Anotherlicense,anotheracceptanceofoptions
specifiedbythecomputer...Next,Next...
Bepatient!
Finally!Thisiswhatyouhavebeenwaitingfor.Click
Finish.Thecomputerwillberestartedalongwiththe
programsavedonharddisc.EverythingisOK!
ClicktheMPLABdesktopiconinordertostarttheprogramandlearnaboutit.
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 11/17
KeeponprojectmakingbyclickingNEXT.Thenselect
themicrocontrolleryouwillbeusing.
Asseen,MPLABissimilartomostWindowsprograms.Apartfromtheworkingarea,therearemenus(containsoptions:File,Editetc.),
toolbars(containsdifferenticons)andastatusbaratthebottomofthewindow.SimilartoWindows,thereisaruletohaveshortcutsforthe
mostcommonlyusedprogramoptionscreatedinordertoeasilyaccessthemandspeedupoperationtherefore.Theseshortcutsareactually
iconsbelowthemenubar.Inotherwords,alloptionscontainedinthetoolbararecontainedinthemenutoo.
PROJECTMAKING
Followthesestepstoprepareprogramforloadingintothemicrocontroller:
Inordertomakeaproject,itisnecessarytoclicktheoption"PROJECT"andthen"PROJECTWIZARD".Awelcomewindowappears.
1. Makeaproject
2. Writeaprogramand
3. Compileit.
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 12/17
Inourcase,itisPIC16F887microcontroller.
Attheend,theprojectisassignedanamewhichusuallyindicatesthepurposeandthecontentoftheprogrambeingwritten.Theproject
shouldbemovedtothedesiredfolder.ItisbestthatthefolderassociateswithPICmicrocontrollers(Seefigure).
DocumentscontainedintheprojectdonotalwaysneedtobewritteninMPLAB.Documentswrittenbysomeotherprogrammayalsobe
includedintheproject.Inthisexample,therearenosuchdocuments.JustclickNext.
ClickFINISHtocompletetheproject.Thewindowitselfcontainsprojectparameters.
WRITINGANEWPROGRAM
Whentheprojectiscreated,awindowshowninfigurebelowappears.
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 13/17
Afterthe"Blink.asm"iscreatedandsaved,itshould
beincludedintheprojectbyrightclickonthe"Source
Files"optioninthe"Proba.mcw"window.Afterthat,a
smallwindowwithtwooptionsappears.Selectthefirst
one"AddFiles".
Thenextstepistowriteaprogram.OpenanewdocumentbyclickingFile>New.TextEditorinMPLABenvironmentappears.
SavethedocumentinthefolderD:\PICprojectsbyusingtheFile>SaveAscommandandnameit"Blink.asm"indicatingthatthisprogramis
tobeanexampleofportdiodeblinking.Obviouslyyoucanlocateyoufileswhereveryouwish,inwhicheverharddriveyouwish.Usinga
commondirectorytostoreallyourdifferentprojectsandsubdirectoriesinmakesgoodsense.
Example:
D:\PicProjects
LEDFlashProject
Allassociatedfiles
EventCountProject
Allassociatedfiles
LEDScanningProject
Allassociatedfiles
ClickonthatoptionopensanotherwindowcontainingthefolderPICalongwiththedocumentBlink.asm.Seefigurebelow.
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 14/17
Click"Blink"toincludethedocumentBlink.asmintotheproject.
Programwritingexample
Theprogramwritingprocedurecannotstartuntilallpreviousoperationshavebeenperformed.Programwrittenbelowisasimpleillustrationof
projectmaking.
ProgramtosetportBpinstologicone(1).
Version:1.0Date:April25,2007MCU:PIC16F887Programmer:JohnSmith
*****Declarationandconfigurationofthemicrocontroller*****
PROCESSOR16f887
#include"p16f887.inc"
__CONFIG_CP_OFF&_WDT_OFF&_PWRTE_ON&_XT_OSC

*****Variabledeclaration*****
Cblock0x20FirstfreeRAMlocation
endcNovariables

*****Programmemorystructure*****
ORG0x00Resetvector
gotoMainAfterresetjumptothislocation

ORG0x04Interruptvector
gotoMainNointerruptroutine
MainStarttheprogram
bankselTRISBSelectbankcontainingTRISB
clrfTRISBPortBisconfiguredasoutput
bankselPORTBSelectbankcontainingPORTB
movlw0xffW=FF
movwfPORTBMoveWtoportB
LoopgotoLoopJumptolabelLoop
End
TheprogramshouldbewrittentotheBlink.asmwindoworcopiedfromdiscbymeansofoptionscopy/paste.Whencopied,theprogram
shouldbecompiledintoexecutableHEXformatbyusingoptionPROJECT>BUILDALL.Anewwindowappears.Thelastsentenceisthe
mostimportantbecauseittellsuswhethercompilinghassucceededornot.Clearly,BUILDSUCCEEDEDmessagemeansthatnoerror
occurredandcompilinghasbeensuccessfullydone.
Incaseanerroroccurs,itisnecessarytoclicktwiceonthemessagereferringtoitintheOutputwindow,whichautomaticallyswitchyouover
toassemblyprogram,directlytothelinewheretheerrorhasoccurred.
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 15/17
Startsprogramexecutionatfullspeed.Inthisexample,thesimulatorexecutestheprogram
atfull(normal)speeduntilitishaltedbyclickingtheiconbelow.
Pausesprogramexecution.Programcancontinueexecutingstepbysteporatfullspeed
again.
Startsprogramexecutionatoptionalspeed.Thespeedofexecutionissetindialog
Debugger/Settings/Animation/RealtimeUpdates.
Startsstepbystepprogramexecution.Instructionsareexecutedoneafteranother.
Furthermore,clickingonthisiconenablesyoutostepintosubroutinesandmacros.
Thisiconhasthesamefunctionasthepreviousoneexceptithastheabilitytostepinto
subroutines.
Resetsmicrocontroller.Byclickingthisicon,theprogramcounterispositionedatthe
beginningoftheprogramandsimulationcanstart.
SIMULATOR
AsimulatorisapartofMPLABenvironmentwhichprovidesbetterinsightintotheoperationofthemicrocontroller.Generallyspeaking,a
simulationisanattempttomodelareallifeorhypotheticalsituationsothatitcanbestudiedtoseehowthesystemworks.Bymeansofthe
simulator,itisalsopossibletomonitorcurrentvaluesofvariables,registersandportpinsstatesaswell.Tobehonest,asimulatorisnotofthe
sameimportanceforallprograms.Ifaprogramissimpler(asinourexample),thesimulationisnotofgreatimportancebecausesettingportB
pinstologicone(1)isnotcomplicatedatall.However,inmorecomplexprogramscontainingtimers,differentconditionsandrequests
(especiallymathematicaloperations),thesimulatormaybeofgreatuse.Asthenameitselfindicates,asimulationmeanstosimulatethe
operationofmicrocontroller.Likethemicrocontroller,asimulatorexecutesinstructionsoneafteranother(linebyline)andconstantlyupdates
thestateofallregisters.Inthisway,theusersimplymonitorsprogramexecution.Attheendofprogramwriting,theusershouldfirsttestitin
thesimulatorpriortoexecutingitinarealenvironment.Unfortunately,thisisoneofmanygoodthingsbeingoverlookedbytheprogrammer
becauseofitscharacterassuchandthelackofhighqualitysimulatorsaswell.
SimulatorisactivatedbyclickingonDEBUGGER>SELECTTOOL>MPLABSIM,asshowninfigure.Asaresult,severaliconsrelatedto
thesimulatoronlyappear.Theirmeaningsareasfollows:
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 16/17
previouschapter|tableofcontents|nextchapter
Similartorealenvironment,thefirstthingthatshouldbedoneistoresetthemicrocontrollerusingtheoptionDEBUGGER>RESETorby
clickingreseticon.Astheconsequenceofthis,agreenlineispositionedatthebeginningoftheprogramandprogramcounterPCLiscleared
tozero.RefertothewindowSpecialFunctionRegistersshownbelow.
ApartfromSFRs,itisgoodtohaveaninsightinFileRegisters.AwindowcontainingthemappearsbyclickingtheVIEW>FILEREGISTERS
option.
Iftheprogramcontainsvariables,itisgoodtomonitortheirvaluesaswell.Eachvariableisassignedawindow(WatchWindows)byclicking
VIEW>WATCHoption.
Iftheprogramcontainsvariables,itisgoodtomonitortheirvaluesaswell.Eachvariableisassignedawindow(WatchWindows)byclicking
VIEW>WATCHoption.
Afterallvariablesandregistersofinterestbecomeavailableonthesimulatorworkingarea,theprocessofsimulationcanstart.Thenext
instructionmaybeeitherStepintoorStepoverdependingonwhetheryouwanttostepintosubroutineornot.Thesameinstructionsmaybe
setbyusingkeyboardpushbuttons<F7>or<F8>(generally,allimportantinstructionshavethecorrespondingpushbuttonsonthe
keyboard).
MikroElektronika Embedded Solutions
Follow us on
8/27/2014 Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/ 17/17
Copyright 1998 - 2014. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.
PIC Solution
PIC Development Boards
PIC Compilers
PIC Programmers/Debuggers
PIC Kits
PIC Books
PIC32 Solution
PIC32 Development Boards
PIC32 Compilers
PIC32 Programmers/Debuggers
PIC32 Kits
dsPIC Solution
dsPIC Development Boards
dsPIC Compilers
dsPIC Programmers/Debuggers
dsPIC Kits
dsPIC Books
AVR Solution
AVR Development Boards
AVR Compilers
AVR Programmers/Debuggers
AVR Kits
STM32 Solution
STM32 Development Boards
STM32 Compilers
STM32 Programmers/Debuggers
STM32 Kits
Tiva C Series Solution
Tiva C Development Boards
Tiva C Compilers
Tiva C Programmers/Debuggers
Tiva C Kits
8051 Solution
8051 Dev. Boards
8051 Compilers
8051 Programmers
8051 Books
8051 Kits
Additional Software
Visual TFT
Visual GLCD
Package Manager
GLCD Font Creator
Timer Calculator
Add-on boards
Click Boards
mikromedia shields
Communication
Storage
Real Time Clock
Display
Measurement
Audio & Voice
Power Supply
GPS
GSM/GPRS
Support Forum mikroBUS Lets make Press Legal Archive About Us Customization

You might also like