Top Banner

of 17

Appendix A_ Programming a Microcontroller - Book_ PIC Microcontrollers

Oct 09, 2015

Download

Documents

anon_448550364
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 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.ThewordAssembleritselfdoesnothaveanydeepermeaning,itcorrespondstothenamesofotherlanguagessuchasEnglishorFrench.Moreprecisely,assemblylanguageisonlyapassingsolution.Inorderthatthemicrocontrollercanunderstandaprogramwritteninassemblylanguage,itmustbecompiledintoalanguageofzerosandones.AssemblylanguageandAssemblerdonothavethesamemeaning.Thefirstonereferstothesetofrulesusedforwritingprogramforthemicrocontroller,whilethelaterreferstoaprogramonapersonalcomputerusedtotranslateassemblylanguagestatementsintothelanguageofzerosandones.AcompiledprogramisalsocalledMachineCode.A"Program"isadatafilestoredonacomputerharddisc(orinmemoryofthemicrocontroller,ifloaded)andwrittenaccordingtotherulesofassemblyorsomeotherprogramminglanguage.Assemblylanguageisunderstandableforhumansbecauseitconsistsofmeaningfulwordsandsymbolsofthealphabet.Letustake,forexamplethecommand"RETURN"whichis,asitsnameindicates,usedtoreturnthemicrocontrollerfromasubroutine.Inmachinecode,thesamecommandisrepresentedbya14bitarrayofzerosandonesunderstandablebythemicrocontroller.Allassemblylanguagecommandsaresimilarlycompiledintothecorrespondingarrayofzerosandones.Adatafileusedforstoringcompiledprogramiscalledan"executivefile",i.e."HEXdatafile".Thenamecomesfromthehexadecimalpresentationofadatafileandhasasuffixof"hex"aswell,forexample"probe.hex".Afterhasbeengenerated,thedatafileisloadedintothemicrocontrollerusingaprogrammer.Assemblylanguageprogramsmaybewritteninanyprogramfortextprocessing(editor)abletocreateASCIIdatafilesonaharddiscorinaspecializedworkenvironmentsuchasMPLABdescribedlater.

    ELEMENTSOFASSEMBLYLANGUAGE

    Aprogramwritteninassemblylanguageconsistsofseveralelementsbeingdifferentlyinterpretedwhilecompilingtheprogramintoanexecutabledatafile.Theuseoftheseelementsrequiresstrictrulesanditisnecessarytopayspecialattentiontothemduringprogramwritinginordertoavoiderrors.

    ASSEMBLYLANGUAGESYNTAX

    Asmentioned,itisnecessarytoobservesomespecificrulesinordertoenabletheprocessofcompilingintoexecutiveHEXcodetorunwithouterrors.Compulsoryrulesexplaininghowsequencesofexpressionsareputtogethertoformthestatementsthatmakeupanassemblylanguageprogramarecalledsyntax.Thereareonlyseveralofthem:

    Everyprogramlinemayconsistofamaximumof255charactersEveryprogramlinethatistobecompiledmuststartwithasymbol,label,mnemonicsordirectiveTextfollowingthemark""inaprogramlinerepresentsacommentwhichisignoredbytheassembler(notcompiled)andAlltheelementsofoneprogramline(labels,instructionsetc.)mustbeseparatedbyatleastonespacecharacter.Forthesakeofbetterclearness,apushbuttonTABiscommonlyusedinsteadofit,sothatitiseasytodelimitcolumnswithlabels,directivesetc.inaprogram.

    LABELS

    AlabelrepresentsatextualversionofsomeaddressinROMorRAMmemory.Eachlabelhastostartinthefirstcolumnwithaletterofalphabetor"_"andmayconsistofmaximumof32characters.Besides,itiseasilyused:

    Itissufficienttoenterthenameofalabelinsteadofa16bitaddressininstructionwhichcallssomesubroutineorajump.Thelabelwiththesamenameshouldalsobewrittenatthebeginningofaprogramlineinwhichasubroutinestartsorwhereajumpshouldbeexecuted.Asageneralrule,labelshaveeasilyrecognizablenames.

    Duringprogramcompiling,theassemblerwillautomaticallyreplacethelabelsbythecorrespondingaddresses.

    FeaturedDevelopmentTools

    FreeOnlineBooks

    EasyPICv7DevelopmentSystem

    EasyPICv7istopsellingPICDevelopmentBoardfor250MicrochipPICMCUsinDIPpackaging.ItfeaturesUSB2.0programmer/debuggerandover17essentialmodulesnecessaryindevelopment.BoardcomeswithPIC18F45K22.[moreinfo]

    Book:PICMicrocontrollersProgramminginC

    Whataremicrocontrollers,anyway?Electroniccomponentsbuiltintoonesinglechipcapableofcontrollingasmallsubmarine,acraneoranelevatoranything.Itsuptoyoutodecidewhatyouwantthemtodo.Youjusthavetowriteaprogramanddumpitintothemicrocontroller.[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.Itisnotnecessarytocommenteveryline.Whenthreeorfourlinesofcodeworktogethertoaccomplishsomehigherleveltask,itisbettertohaveasinglehigherlevelcommentforthegroupoflines.Therefore,itisaddedifneededandhastostartwith"".Commentsaddedtoassemblysourcecodearenotcompiledintomachinecode.

    INSTRUCTIONS

    Instructionsaredefinedforeachmicrocontrollerfamilybythemanufacturer.Therefore,itisuptotheusertofollowtherulesoftheirusage.Thewayofwritinginstructionsisalsocalledinstructionsyntax.Theinstructions"movlp"and"gotto",inthefollowingexample,arerecognizedbythePIC16F887microcontrollerasanerrorsincetheyarenotcorrectlywritten.

    OPERANDS

    Anoperandisavalue(anargument)uponwhichtheinstruction,namedbymnemonic,operates.Theoperandsmaybearegister,avariable,aliteralconstant,alabeloramemoryaddress.

    DIRECTIVES

    Unlikeinstructionsbeingwrittentoonchipprogrammemoryaftercompilation,directivesarecommandsofassemblylanguageitselfanddonotdirectlyaffecttheoperationofthemicrocontroller.Someofthemmustbeusedineveryprogramwhileothersareonlyusedtofacilitateorenhancetheoperation.Directivesarewrittentothecolumnreservedforinstructions.Therulewhichmustbeobservedallowsonlyonedirectiveperprogramline.

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

    PROCESSORDirective

    Thisdirectivemustbewrittenatthebeginningofeachprogram.Itdefinesthetypeofthemicrocontrollerwhichtheprogramiswrittenfor.Forexample:

    Processor16f887

    EQUdirective

    Thisdirectiveisusedtoreplaceanumericvaluebyasymbol.Inthisway,someaspecificlocationinmemoryisassignedaname.Forexample:

    MAXIMUMEQUH25

    Thismeansthatamemorylocationataddress25(hex.)isassignedthename"MAXIMUM".Everyappearanceofthelabel"MAXIMUM"intheprogramwillbeinterpretedbytheassemblerastheaddress25(MAXIMUM=H25).Symbolsmaybedefinedthiswayonlyonceinaprogram.Thatthisdirectiveismostlyusedatthebeginningoftheprogram.

    ORGdirective

    Thisdirectivespecifiesalocationinprogrammemorywheretheprogramfollowingdirectiveistobeplaced.Forexample:

    ORG0x100

    START......

    ...

    ORG0x1000

    TABLE...

    ...

    Thisprogramstartsatlocation0x100.Thetablecontainingdataistobestoredatlocation1024(1000h).

    ENDdirective

    Eachprogrammustbeendedbyusingthisdirective.Onceaprogramencountersthisdirective,theassemblerimmediatelystopscompiling.Forexample:

    ...

    ENDEndofprogram

    \$INCLUDEdirective

    Thenameofthisdirectivefullyindicatesitspurpose.Duringcompiling,itenablestheassemblertousedatacontainedinanotherfileonacomputerharddisc.Forexample:

    ...

    #include

    CBLOCKandENDCdirectives

    Allvariables(theirnamesandaddresses)thatwillbeusedinaprogrammustbedefinedatthebeginningoftheprogram.Becauseofthisitisnotnecessarytospecifytheaddressofeachspecifiedvariablelaterintheprogram.Instead,itisenoughtospecifytheaddressofthefirstonebyusingdirectiveCBLOCKandlistallothersafterwards.Thecompilerautomaticallyassignsthesevariablesthecorrespondingaddressesaspertheordertheyarelisted.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.EachoftheseblocksstartswiththedirectiveIFandendswiththedirectiveENDIForELSE.Astatementorasymbol(inparentheses)followingthedirectiveIFrepresentsaconditionwhichdetermineswhichpartoftheprogramistobecompiled:

    Ifthestatementiscorrectorthevalueofasymbolisequaltoone,programcompilesallinstructionswrittenbeforedirectiveELSEorENDIFandIfthestatementisnotcorrectorthevalueofasymbolisequaltozero,onlyinstructionswrittenafterdirectivesELSEorENDIFaretobecompiled.

    Example1:

    IF(VERSION>3)

    CALLTable_2

    CALL

    ENDIF

    ...

    Iftheprogramisreleasedaftertheversion3(statementisright)thensubroutines"Table2"and"Extension"areexecuted.Ifthestatementinparenthesesiswrong(VERSION

  • 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.Oneofthemistowriteinafewwordsatthebeginningofaprogramwhattheprogramsnameis,whatitisusedfor,version,releasedate,typeofthemicrocontrolleritiswrittenforandthenameoftheprogrammer.Sincethisinformationisnotofimportancefortheassembler,itiswrittenasacommentwhichalwaysstartswithsemicolonandcanbewritteninanewlineorimmediatelyafteracommand.

    Afterwritingthisgeneralcomment,itistimetoselectthemicrocontrollerbyusingdirectivePROCESSOR.ThisdirectiveisfollowedbyanotheroneusedtoincludeallthedefinitionsofthePIC16F887microcontrollersinternalregistersintheprogram.ThesedefinitionsarenothingbuttheabilitytoaddressportBandotherregistersasPORTBinsteadof06h,whichmakestheprogramclearerandmorelegible.

    Inorderthatthemicrocontrollerwilloperateproperly,aseveralparameterssuchasthetypeofoscillator,stateofthewatchdogandinternalresetcircuitmustbedefined.Itisdonebyutilizingthefollowingdirective:

    _CONFIG_CP_OFF&_WDT_OFF&PWRTE_ON&XT_OSC

    Whenallnecessaryelementsaredefined,theprocessofprogramwritingcanstart.Firstandforemost,itisnecessarytospecifytheaddressfromwhichthemicrocontrollerstartswhenthepowergoeson(org0x00)aswellastheaddressfromwhichtheprogramproceedswithexecutionifaninterruptoccurs(org0x04).Sincethisprogramisverysimple,itisenoughtousecommand"gotoMain"inordertodirectthemicrocontrollertothebeginningoftheprogram.Thenextcommandselectsmemorybank1inordertoenableaccesstotheTRISBregistertoconfigureportBasoutput(bankselTRISB).Themainprogramendsbyselectingmemorybank0andsettingallportBpinstologicone(1)(movlw0xFF,movwfPORTB).

    Itisnecessarytocreatealooptokeepprogramfrom"gettinglost"incaseanerroroccurs.Forthispurpose,thereisanendlessloopexecutedallthetimewhilethemicrocontrollerisswitchedon.

    "end"isrequiredattheendofeveryprogramtoinformtheassemblerthattherearenomorecommandstobecompiled.

    DATAFILESRESULTINGFROMPROGRAMCOMPILING

    Theresultofcompilingaprogramwritteninassemblylanguagearedatafiles.Themostimportantandmostcommonlyuseddatafilesare:

    Executivedatafile(Program_Name.HEX)Errordatafile(Program_Name.ERR)andListdatafile(Program_Name.LST).

    Thefirstfilecontainscompiledprogramwhichisloadedintothemicrocontroller.Itscontentsgivenoinformationofimportancetotheprogrammersoitwillnotbediscussedhere.Thesecondfilecontainserrorsmadeinwritingprocessanddetectedbythecompilerduringcompilingprocess.Errorscanbedetectedinlistdatafile,whichtakesmoretime,sotheerrordatafileismoresuitableforlongprograms.

    Thethirdfileisthemostusefulfortheprogrammer.Itcontainslotsofinformationoncommandsandvariableslocationsinonchipmemoryaswellaserrorsignalization.Thereisasymboltableattheendofeachdatafilelistcontainingallthesymbolsusedinaprogram.Otherusefulelementsoflistdatafilearememoryusagemapsanderrorstatisticsprovidedattheveryendofthefilelist.

    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,becauseonlyonewrongcommandorlabelnamemaycausetheprogramtonotworkproperlyoritmaynotworkatall.Therefore,itislesstediousandlesserrorpronetouseasequenceofinstructionsasasingleprogramstatementwhichworksproperlyforsure.Toimplementthisidea,macrosandsubroutinesareused.

    MACROS

    Amacrocontainsprogrammerdefinedsymbolsthatstandforasequenceoftextlines.Itisdefinedbyusingdirectivemacrowhichnamesmacroandargumentsifneeded.Macromustbedefinedprioritisused.Onceamacrohasbeendefined,itsnamemaybeusedintheprogram.Whentheassemblerencountersmacrosname,itreplacesitbytheappropriatesequenceofinstructionsandprocessesthemjustasthoughtheyhaveappearedintheprogram.Manydifferentmacroinstructionsareavailableforvariouspurposes,eliminatingsomeoftherepetitivenessoftheprogramming,aswellassimplifyingthewriting,readingandunderstandingoftheprogram.Thesimplestuseofmacrosmaybegivinganametoaninstructionsequencebeingrepeated.Letustake,forexample,globalinterruptenableprocedure,SFRs'bankselection.

    macro_namemacroarg1,arg2...

    ...

    sequenceofinstructions

    ...

    endm

    Thefollowingexampleshowsfourmacros.Thefirsttwomacrosselectbanks,thethirdoneenablesinterrupt,whereasthefourthonedisablesinterrupt.

    bank0macroMacrobank0

    bcfSTATUS,RP0ResetRP0bit

    bcfSTATUS,RP1ResetRP1bit

    endmEndofmacro

    bank1macroMacrobank1

    bsfSTATUS,RP0SetRP0bit

    bcfSTATUS,RP1ResetRP1bit

    endmEndofmacro

    enableintmacroGlobalinterruptenable

    bsfINTCON,7Setbit

    endmEndofmacro

    disableintmacroGlobalinterruptdisable

    bcfINTCON,7ResetbitendmEndofmacro

    MacrosdefinedinthiswayaresavedinaparticulardatafilewithextensionINCwhichstandsforINCLUDEdatafile.Asseen,thesefourmacrosdonothavearguments.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,number7isreplacedbytheargumentarg2,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.Themaindisadvantageofmacroisthatitoccupiesalotofmemoryspacebecauseeverymacronameinaprogramisreplacedbyitspredefinedcode.Owingtothefactthatprogramsoftenusemacro,everythingismorecomplicatedifitislong.

    callcmacrolabelMacrocallc

    localExitDefinelocalLabelwithinmacro

    bncExitIfC=0jumptoExit

    calllabelIfC=1callsubroutineataddressLabel(outofmacro)

    ExitLocalLabelwithinmacro

    endmEndofmacro

    Intheeventthatamacrohaslabels,theymustbedefinedaslocalonesbyusingdirectivelocal.Thegivenexamplecontainsmacrowhichcallsasubroutine(calllabelinthiscase)iftheCarrybitoftheSTATUSregisterisset.Otherwise,thefirstfollowinginstructionisexecuted.

    SUBROUTINES

    Asubroutinecontainsasequenceofinstructions,beginswithalabel(subroutine_name)andendswithcommandreturnorretlw.Themaindifferencecomparingtomacroisthatsubroutineisnotreplacedbyitscodeintheprogram,butprogramjumpstosubroutinetoexecuteit.IthappenseverytimetheassemblerencounterscommandcallSubroutine_nameintheprogram.Onthecommandreturn,itleavesasubroutineandcontinuesexecutionfromwhereitleftoffthemainprogram.Subroutinemaybedefinedbothpriortooruponthecall.

    Asseen,concerningmacros,theinputandoutputargumentsareofgreatimportance.Concerningsubroutines,itisnotpossibletodefineargumentswithinthesubroutineitself.However,variablespredefinedinthemainprogrammaybeusedassubroutinearguments.

    Alogicalsequenceofeventsisasfollows:definingvariables,callingsubroutinewhichusesthemandattheendreadingvariableschangedupontheexecutionofsubroutine.

    Theprograminthefollowingexampleperformsadditionoftwo2bytevariablesARG1andARG2andmovesresulttothevariableRES.When2bytevariablesareused,itisnecessarytodefinehigherandlowerbyteforeachofthem.Theprogramitselfisverysimple.ItfirstaddslowerbytesofvariablesARG1andARG2andhigherafterwards.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(enablestheprogrammertotypeless).Itmayalsohaveargumentswhilesubroutineuseslessmemory,butdoesnothavearguments.

    MPLAB

    MPLABisaWindowsprogrampackagewhichenableseasyprogramwritingaswellaseasyprogramdevelopment.ItisbesttodescribeitasdevelopmentenvironmentforastandardprogramlanguagedesignedforPCprogramming.MPLABtechnicallysimplifiessomeoperationsconsistingofalotofparameters,which,untiltheIDEenvironment*appeared,wereexecutedfromthecommandline.However,tastesaredifferentandtherearesomeprogrammerswhopreferstandardeditorsandcommandlinecompilers.EveryprogramwritteninMPLABisclear,buttherearealsohelpdocumentationjustincase.

    INSTALLINGMPLAB

    MPLABconsistsofseveralparts:

    Theprogramwhichsortsdatafilesofthesameprojectintoonegroup(ProjectManager)programfortextgeneratingandprocessing(TextEditor)andsimulatorusedtosimulatetheoperationofaprogramloadedintothemicrocontroller.

    Besides,therearealsobuiltinprogrammerssuchasPICStartPlusandICD(InCircuitDebugger)thatcanbeusedtoprogramsoftwareintoPICmicrocontrollerdevice.Sincenotbeingthesubjectofthisbook,theyarementionedasoptionsonly.

    InordertostartMPLAB,yourPCshouldcontain:

    PCcompatiblecomputerbelongingtoclass486orbetterAnyWindowsoperatingsystemVGAgraphiccard8MBmemory(32MBrecommended)200MBavailableharddiscandAmouse.

    MPLABinstallationcomesfirst.DatafilesfromMPLABCDshouldbecopiedtoaharddisc.TheprocessofinstallationissimilartoalmostallotherWindowsprograminstallations.Firstofallawelcomewindowappears,thenoptionstoselectandatlastinstallationitself.Amessagenotifyingthattheprogramissuccessfullyinstalledandreadyforuseappears.Areyouready?

    Stepstofollowpriortheinstallation:

    Everythingisreadynowtostartinstallation.Thefollowingpicturesdescribetheinstallationsteps.

    1. StartMicrosoftWindows2. InserttheCDintoCDROM3. ClickSTARTandselectoptionRUN4. ClickBROWSEandselectCDROMdriveand5. 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".Needexplanation?

    Actually,theprogramremindsyoutocloseallactiveprogramsinordertonotinterferewiththeinstallationprocess.Nextofcourse!

    Priortocontinue,youhavetoaccepttheMPLABsoftwarelicenseconditions.Selecttheoption"Iaccept"andclickNEXT.

    Doyouwanttoinstalltheentiresoftware?Yes.Next...

    Similartootherprograms,MPLABshouldbealsoinstalledintoafolder.Itmaybeanyfolderonanyharddisc.Ifitisnotnecessarytomakechanges,selectthespecifiedaddressandclickNext.

    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,anotheracceptanceofoptionsspecifiedbythecomputer...Next,Next...

    Bepatient!

    Finally!Thisiswhatyouhavebeenwaitingfor.ClickFinish.Thecomputerwillberestartedalongwiththeprogramsavedonharddisc.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.Thenselectthemicrocontrolleryouwillbeusing.

    Asseen,MPLABissimilartomostWindowsprograms.Apartfromtheworkingarea,therearemenus(containsoptions:File,Editetc.),toolbars(containsdifferenticons)andastatusbaratthebottomofthewindow.SimilartoWindows,thereisaruletohaveshortcutsforthemostcommonlyusedprogramoptionscreatedinordertoeasilyaccessthemandspeedupoperationtherefore.Theseshortcutsareactuallyiconsbelowthemenubar.Inotherwords,alloptionscontainedinthetoolbararecontainedinthemenutoo.

    PROJECTMAKING

    Followthesestepstoprepareprogramforloadingintothemicrocontroller:

    Inordertomakeaproject,itisnecessarytoclicktheoption"PROJECT"andthen"PROJECTWIZARD".Awelcomewindowappears.

    1. Makeaproject2. Writeaprogramand3. 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.Theprojectshouldbemovedtothedesiredfolder.ItisbestthatthefolderassociateswithPICmicrocontrollers(Seefigure).

    DocumentscontainedintheprojectdonotalwaysneedtobewritteninMPLAB.Documentswrittenbysomeotherprogrammayalsobeincludedintheproject.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,itshouldbeincludedintheprojectbyrightclickonthe"SourceFiles"optioninthe"Proba.mcw"window.Afterthat,asmallwindowwithtwooptionsappears.Selectthefirstone"AddFiles".

    Thenextstepistowriteaprogram.OpenanewdocumentbyclickingFile>New.TextEditorinMPLABenvironmentappears.

    SavethedocumentinthefolderD:\PICprojectsbyusingtheFile>SaveAscommandandnameit"Blink.asm"indicatingthatthisprogramistobeanexampleofportdiodeblinking.Obviouslyyoucanlocateyoufileswhereveryouwish,inwhicheverharddriveyouwish.Usingacommondirectorytostoreallyourdifferentprojectsandsubdirectoriesinmakesgoodsense.

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

    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,theprogramshouldbecompiledintoexecutableHEXformatbyusingoptionPROJECT>BUILDALL.Anewwindowappears.Thelastsentenceisthemostimportantbecauseittellsuswhethercompilinghassucceededornot.Clearly,BUILDSUCCEEDEDmessagemeansthatnoerroroccurredandcompilinghasbeensuccessfullydone.

    Incaseanerroroccurs,itisnecessarytoclicktwiceonthemessagereferringtoitintheOutputwindow,whichautomaticallyswitchyouovertoassemblyprogram,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,thesimulatorexecutestheprogramatfull(normal)speeduntilitishaltedbyclickingtheiconbelow.

    Pausesprogramexecution.Programcancontinueexecutingstepbysteporatfullspeedagain.

    Startsprogramexecutionatoptionalspeed.ThespeedofexecutionissetindialogDebugger/Settings/Animation/RealtimeUpdates.

    Startsstepbystepprogramexecution.Instructionsareexecutedoneafteranother.Furthermore,clickingonthisiconenablesyoutostepintosubroutinesandmacros.

    Thisiconhasthesamefunctionasthepreviousoneexceptithastheabilitytostepintosubroutines.

    Resetsmicrocontroller.Byclickingthisicon,theprogramcounterispositionedatthebeginningoftheprogramandsimulationcanstart.

    SIMULATOR

    AsimulatorisapartofMPLABenvironmentwhichprovidesbetterinsightintotheoperationofthemicrocontroller.Generallyspeaking,asimulationisanattempttomodelareallifeorhypotheticalsituationsothatitcanbestudiedtoseehowthesystemworks.Bymeansofthesimulator,itisalsopossibletomonitorcurrentvaluesofvariables,registersandportpinsstatesaswell.Tobehonest,asimulatorisnotofthesameimportanceforallprograms.Ifaprogramissimpler(asinourexample),thesimulationisnotofgreatimportancebecausesettingportBpinstologicone(1)isnotcomplicatedatall.However,inmorecomplexprogramscontainingtimers,differentconditionsandrequests(especiallymathematicaloperations),thesimulatormaybeofgreatuse.Asthenameitselfindicates,asimulationmeanstosimulatetheoperationofmicrocontroller.Likethemicrocontroller,asimulatorexecutesinstructionsoneafteranother(linebyline)andconstantlyupdatesthestateofallregisters.Inthisway,theusersimplymonitorsprogramexecution.Attheendofprogramwriting,theusershouldfirsttestitinthesimulatorpriortoexecutingitinarealenvironment.Unfortunately,thisisoneofmanygoodthingsbeingoverlookedbytheprogrammerbecauseofitscharacterassuchandthelackofhighqualitysimulatorsaswell.

    SimulatorisactivatedbyclickingonDEBUGGER>SELECTTOOL>MPLABSIM,asshowninfigure.Asaresult,severaliconsrelatedtothesimulatoronlyappear.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>RESETorbyclickingreseticon.Astheconsequenceofthis,agreenlineispositionedatthebeginningoftheprogramandprogramcounterPCLisclearedtozero.RefertothewindowSpecialFunctionRegistersshownbelow.

    ApartfromSFRs,itisgoodtohaveaninsightinFileRegisters.AwindowcontainingthemappearsbyclickingtheVIEW>FILEREGISTERSoption.

    Iftheprogramcontainsvariables,itisgoodtomonitortheirvaluesaswell.Eachvariableisassignedawindow(WatchWindows)byclickingVIEW>WATCHoption.

    Iftheprogramcontainsvariables,itisgoodtomonitortheirvaluesaswell.Eachvariableisassignedawindow(WatchWindows)byclickingVIEW>WATCHoption.

    Afterallvariablesandregistersofinterestbecomeavailableonthesimulatorworkingarea,theprocessofsimulationcanstart.ThenextinstructionmaybeeitherStepintoorStepoverdependingonwhetheryouwanttostepintosubroutineornot.Thesameinstructionsmaybesetbyusingkeyboardpushbuttonsor(generally,allimportantinstructionshavethecorrespondingpushbuttonsonthekeyboard).

    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 SolutionPIC Development BoardsPIC CompilersPIC Programmers/DebuggersPIC KitsPIC Books

    PIC32 SolutionPIC32 Development BoardsPIC32 CompilersPIC32 Programmers/DebuggersPIC32 Kits

    dsPIC SolutiondsPIC Development BoardsdsPIC CompilersdsPIC Programmers/DebuggersdsPIC KitsdsPIC Books

    AVR SolutionAVR Development BoardsAVR CompilersAVR Programmers/DebuggersAVR Kits

    STM32 SolutionSTM32 Development BoardsSTM32 CompilersSTM32 Programmers/DebuggersSTM32 Kits

    Tiva C Series SolutionTiva C Development BoardsTiva C CompilersTiva C Programmers/DebuggersTiva C Kits

    8051 Solution8051 Dev. Boards8051 Compilers8051 Programmers8051 Books8051 Kits

    Additional SoftwareVisual TFTVisual GLCDPackage ManagerGLCD Font CreatorTimer Calculator

    Add-on boardsClick Boardsmikromedia shieldsCommunicationStorageReal Time ClockDisplayMeasurementAudio & VoicePower SupplyGPSGSM/GPRS

    Support Forum mikroBUS Lets make Press Legal Archive About Us Customization