You are on page 1of 173

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers


Products Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Introduction:Worldofmicrocontrollers
Thesituationwefindourselvestodayinthefieldofmicrocontrollershaditsbeginningsinthedevelopmentoftechnologyofintegrated circuits.Thisdevelopmenthasenabledustostorehundredsofthousandsoftransistorsintoonechip.Thatwasapreconditionforthe manufactureofmicroprocessors.Thefirstcomputersweremadebyaddingexternalperipheralssuchasmemory,input/outputlines,timers andotherstoit.Furtherincreasingofpackagedensityresultedincreatinganintegratedcircuitwhichcontainedbothprocessorand peripherals.Thatishowthefirstchipcontainingamicrocomputerlaterknownasamicrocontrollerhasdeveloped.

Thisishowitallgotstarted...
Intheyear1969,ateamofJapaneseengineersfromBUSICOMcametotheUSAwitharequestthatafewintegratedcircuitsforcalculators weretobedesignedaccordingtotheirprojects.TherequestwassenttoINTELandMarcianHoffwasinchargeoftheprojectthere.Having experienceworkingwithacomputer,thePDP8,hecameupwithanideatosuggestfundamentallydifferentsolutionsinsteadofthe suggesteddesign.Thissolutionpresumedthattheoperationofintegratedcircuitwastobedeterminedbytheprogramstoredinthecircuit itself.Itmeantthatconfigurationwouldbesimpler,butitwouldrequirefarmorememorythantheprojectproposedbyJapaneseengineers. Afterawhile,eventhoughtheJapaneseengineersweretryingtofindaneasiersolution,Marciansideawonandthefirstmicroprocessor wasborn.AmajorhelpwithturninganideaintoareadytouseproductwasFedericoFaggin.Ninemonthsafterhiringhim,Intelsucceeded indevelopingsuchaproductfromitsoriginalconcept.In1971Intelobtainedtherighttosellthisintegratedcircuit.BeforethatIntelbought thelicensefromBUSICOMwhichhadnoideawhatatreasureithad.Duringthatyear,amicroprocessorcalledthe4004appearedonthe market.Thatwasthefirst4bitmicroprocessorwiththespeedof6000operationspersecond.Notlongafterthat,anAmericancompany CTCrequestedfromIntelandTexasInstrumentstomanufacturean8bitmicroprocessortobeappliedinterminals.EventhoughCTCgave upthisproject,IntelandTexasInstrumentskeptworkingonthemicroprocessorandinApril1972thefirst8bitmicroprocessorcalledthe 8008appearedonthemarket.Itwasabletoaddress16Kbofmemory,had45instructionsandthespeedof300000operationsper second.Thatmicroprocessorwasthepredecessorofalltodaysmicroprocessors.IntelkeptondevelopingitandinApril1974itlaunched an8bitprocessorcalledthe8080.Itwasabletoaddress64Kbofmemory,had75instructionsandinitialpricewas$360. AnotherAmericancompanycalledMotorola,quicklyrealizedwhatwasgoingon,sotheylaunched8bitmicroprocessor6800.Theirchief constructorwasChuckPeddle.Apartfromtheprocessoritself,Motorolawasthefirstcompanythatalsomanufacturedotherperipherals suchasthe6820and6850.Atthattimemanycompaniesrecognizedthegreaterimportanceofmicroprocessorsandbegantheirown development.ChuckPeddleleftMotorolatojoinMOSTechnologyandkeptworkingintensivelyondevelopingmicroprocessors. AttheWESCONexhibitionintheUSAin1975,acrucialeventinthehistoryofthemicroprocessorstookplace.MOSTechnology announcedthatitwassellingprocessors6501and6502at$25each,thatinterestedcustomerscouldpurchaseimmediately.Itwassucha sensationthatmanythoughtitwasakindoffraud,consideringthatcompetingcompaniesweresellingthe8080and6800at$179each.On thefirstdayoftheexhibit,inresponsetothecompetitor,bothMotorolaandIntelcutthepricesoftheirmicroprocessorsto$69.95.Motorola accusedMOSTechnologyandChuckPeddleofplagiarizingtheprotected6800.Becauseofthat,MOSTechnologygaveupfurther manufactureofthe6501,butkeptmanufacturingthe6502.Itwasthe8bitmicroprocessorwith56instructionsandabilitytodirectlyaddress 64Kbofmemory.Duetolowprice,6502becameverypopularsoitwasinstalledintocomputerssuchasKIM1,AppleI,AppleII,Atari, Commodore,Acorn,Oric,Galeb,Orao,Ultraandmanyothers.Soonseveralcompaniesbeganmanufacturingthe6502(Rockwell, Sznertek,GTE,NCR,Ricoh,CommodoretookoverMOSTechnology).Intheyearofitsprosperity1982,thisprocessorwasbeingsoldata rateof15millionprocessorsperyear! Othercompaniesdidnotwanttogiveupeither.FredericoFagginleftIntelandstartedhisowncompanyZilogInc.In1976Zilogannounced theZ80.WhendesigningthismicroprocessorFagginmadeacrucialdecision.The8080hadalreadybeendevelopedandherealizedthat manywouldremainloyaltothatprocessorbecauseofthegreatexpenditureswhichrewritingofalltheprogramswouldresultin. Accordinglyhedecidedthatanewprocessorhadtobecompatiblewiththe8080,i.e.ithadtobeabletoperformalltheprogramswrittenfor the8080.Apartfromthat,manyotherfeatureshavebeenaddedsothattheZ80wasthemostpowerfulmicroprocessoratthattime.Itwas abletodirectlyaddress64Kbofmemory,had176instructions,alargenumberofregisters,abuiltinoptionforrefreshingdynamicRAM memory,asinglepowersupply,greateroperatingspeedetc.TheZ80wasagreatsuccessandeverybodyreplacedthe8080bytheZ80. CertainlytheZ80wascommerciallythemostsuccessful8bitmicroprocessoratthattime.BesidesZilog,othernewmanufacturerssuchas Mostek,NEC,SHARPandSGSappearedsoon.TheZ80wastheheartofmanycomputerssuchas:Spectrum,Partner,TRS703,Z3and Galaxy. In1976Intelcameupwithanupgradedversionofthe8bitmicroprocessorcalledthe8085.However,theZ80wassomuchbetterthatIntel lostthebattle.Eventhoughafewmoremicroprocessorsappearedlateronthemarket(6809,2650,SC/MPetc.),thediehadalreadybeen cast.Therewerenosuchgreatimprovementswhichcouldmakemanufacturerstochangetheirmind,sothe6502andZ80alongwiththe 6800remainedchiefrepresentativesofthe8bitmicroprocessorsofthattime.

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

MicrocontrollerversusMicroprocessor
Amicrocontrollerdiffersfromamicroprocessorinmanyways.Thefirstandmostimportantdifferenceisitsfunctionality.Inorderthatthe microprocessormaybeused,othercomponentssuchasmemorymustbeaddedtoit.Eventhoughthemicroprocessorsareconsideredto bepowerfulcomputingmachines,theirweakpointisthattheyarenotadjustedtocommunicatingtoperipheralequipment. Simply,Inordertocommunicatewithperipheralenvironment,themicroprocessormustusespecializedcircuitsaddedasexternalchips.In shortmicroprocessorsarethepureheartofthecomputers.Thisishowitwasinthebeginningandremainsthesametoday.

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

1/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Fig.01MicrocontrollerversusMicroprocessor

Ontheotherhand,themicrocontrollerisdesignedtobeallofthatinone.Nootherspecializedexternalcomponentsareneededforits applicationbecauseallnecessarycircuitswhichotherwisebelongtoperipheralsarealreadybuiltintoit.Itsavesthetimeandspace neededtodesignadevice.

BASICCONCEPT
Didyouknowthatallpeoplecanbeclassifiedintooneof10groupsthosewhoarefamiliarwithbinarynumbersystemandthosewhoare notfamiliarwithit.Youdontunderstand?Thatmeansthatyoustillbelongtothelatergroup.Ifyouwanttochangeyourstatusreadthe followingtextdescribingbrieflysomeofthebasicconceptsusedfurtherinthisbook(justtobesureweareonthesamepage).

WorldofNumbers
Mathematicsissuchagoodscience!Everythingissologicalandsimpleasthat.Thewholeuniversecanbedescribedwithtendigitsonly. But,doesitreallyhavetobelikethat?Doweneedexactlytendigits?Ofcoursenot,itisonlyamatterofhabit.Rememberthelessonsfrom theschool.Forexample,whatdoesthenumber764mean:fourunits,sixtensandsevenhundreds.Simple!Coulditbedescribedinabit morecomplicatedway?Ofcourseitcould:4+60+700.Evenmorecomplicated?Naturally:4*1+6*10+7*100.Couldthisnumberlooka bitmorescientific?Theanswerisyes:4*10^0+6*10^1+7*10^2.Whatdoesitactuallymean?Whydoweuseexactlythesenumbers:100, 101and102?Whyisitalwaysaboutthenumber10?Thatisbecauseweusetendifferentdigits(0,1,2,...8,9).Inotherwords,because weusebase10numbersystem,i.e.decimalnumbersystem.

Fig.02Thenumber764representedinthreedifferentways

BinaryNumberSystem
Whatwouldhappenifonlytwodigitswouldbeused0and1?Orifwewouldnotknowtodeterminewhethersomethingis3or5times greaterthansomethingelse?Orifwewouldberestrictedwhencomparingtwosizes,i.e.ifwecouldonlystatethatsomethingexists(1)or

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

2/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

doesnotexist(0)?Nothingspecialwouldhappen,wewouldkeeponusingnumbersinthesameway,buttheywouldlookabitdifferent. Forexample:11011010.Howmanypagesofabookdoesthenumber11011010include?Inordertolearnthat,followthesamelogiclikein thepreviousexample,butinreverseorder.Bearinmindthatallthisisaboutmathematicswithonlytwodigits0and1,i.e.base2number system(binarynumbersystem).

Fig.03Thenumber218representedinbinaryanddecimalsystem

Clearly,itisthesamenumberrepresentedintwodifferentways.Theonlydifferenceisinthenumberofdigitsnecessaryforwritingsome number.Onedigit(2)isusedtowritethenumber2indecimalsystem,whereastwodigits(1and0)areusedtowritethatnumberinbinary system.Doyounowagreethatthereare10groupsofpeople?Welcometotheworldofbinaryarithmetic!Doyouhaveanyideawhereitis used? Exceptingstrictlycontrolledlaboratoryconditions,themostcomplicatedelectroniccircuitscannotaccuratelydeterminethedifference betweentwosizes(twovoltagevalues,forexample)iftheyaretoosmall(lowerthanseveralvolts).Thereasonsareelectricalnoisesand somethingcalledtherealworkingenvironment(unpredictablechangesofpowersupplyvoltage,temperaturechanges,toleranceto valuesofbuiltincomponentsetc.).Imagineacomputerwhichwouldoperateupondecimalnumbersbyrecognizing10digitsinthe followingway:0=0V,1=5V,2=10V,3=15V,4=20V...9=45V!?Didanybodysaybatteries?Afarsimplersolutionistheuseofbinarylogic where0indicatesthatthereisnovoltageand1indicatesthatthereisvoltage.Itiseasiertowrite0or1insteadofthereisnovoltageor thereisvoltage.Itiscalledlogiczero(0)andlogicone(1)whichelectronicsperfectlyconformswithandeasilyperformsallthose endlesslycomplexmathematicaloperations.Itiselectronicswhichinrealityappliesmathematicsinwhichallnumbersarerepresentedby twodigitsonlyandinwhichitisonlyimportanttoknowwhetherthereisvoltageornot.Ofcourse,wearetalkingaboutdigitalelectronics.

HexadecimalNumberSystem
Attheverybeginningofcomputerdevelopmentitwasrealizedthatpeoplehadmanydifficultiesinhandlingbinarynumbers.Becauseof this,anewnumberingsystemhadtobeestablished.Thistime,anumbersystemusing16differentdigits.Thefirsttendigitsarethesameas digitsweareusedto(0,1,2,3,...9)buttherearesixdigitsmore.Inordertokeepfrommakingupnewsymbols,thesixlettersofalphabetA, B,C,D,EandFareused.Ahexadecimalnumbersystemconsistingofdigits:0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,Fhasbeenestablished. Whatisthepurposeofthisseeminglybizarrecombination?Justlookhowperfectlyeverythingfitsthestoryaboutbinarynumbers.

Fig.04BinaryandHexadecimalnumber

Thelargestnumberthatcanberepresentedby4binarydigitsisthenumber1111.Itcorrespondstothenumber15indecimalsystem.That numberisinhexadecimalsystemrepresentedbyonlyonedigitF.Itisthelargestonedigitnumberinhexadecimalsystem.Doyouseehow skillfullyitisused?Thelargestnumberwrittenwitheightdigitsisatthesametimethelargesttwodigithexadecimalnumber.Bearinmind thatthecomputeruses8digitbinarynumbers.

BCDCode
BCDcodeisactuallyabinarycodefordecimalnumbersonly.Itisusedtoenableelectroniccircuitstocommunicateinadecimalnumber systemwithperipheralsandinabinarysystemwithintheirownworld.Itconsistsoffourdigitbinarynumberswhichrepresentthefirstten digits(0,1,2,3...8,9).Eventhoughfourdigitscangiveatotalof16possiblecombinations,onlythefirsttenareused.

NumberSystemConversion
Thebinarynumberingsystemisthemostcommonlyused,thedecimalsystemisthemostunderstandablewhilethehexadecimalsystemis somewherebetweenthem.Therefore,itisveryimportanttolearnhowtoconvertnumbersfromonenumberingsystemtoanother,i.e.how toturnaseriesofzerosandunitsintovaluesunderstandabletous.

BinarytoDecimalNumberConversion
Digitsinabinarynumberhavedifferentvaluesdependingontheirpositioninthatnumber.Additionally,eachpositioncancontaineither1 or0anditsvaluemaybeeasilydeterminedbyitspositionfromtheright.Tomaketheconversionofabinarynumbertodecimalitis necessarytomultiplyvalueswiththecorrespondingdigits(0or1)andaddalltheresults.Themagicofbinarytodecimalnumber conversionworks...Youdoubt?Lookattheexample: 110=1*2^2+1*2^1+0*2^0=6 Itshouldbenotedthatfordecimalnumbersfrom0to3youonlyneedtwobinarydigits.Forgreatervalues,extrabinarydigitsmustbe added.Thus,fornumbersfrom0to7youneedthreedigits,fornumbersfrom0to15fourdigitsetc.Simplyspeaking,thelargestbinary

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

3/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

numberconsistingofndigitsisobtainedwhenthebase2israisedbyn.Theresultshouldbethensubtractedby1.Forexample,ifn=4: 2^41=161=15 Accordingly,using4binarydigitsitispossibletorepresentdecimalnumbersfrom0to15,includingthesetwodigits,whichamountsto16 differentvaluesintotal.

HexadecimaltoDecimalNumberConversion
Inordertomakeconversionofahexadecimalnumbertodecimal,eachhexadecimaldigitshouldbemultipliedwiththenumber16raised byitspositionvalue.Forexample:

Fig.05Hexadecimaltodecimalnumberconversion

HexadecimaltoBinaryNumberConversion
Itisnotnecessarytoperformanycalculationinordertoconverthexadecimalnumberstobinarynumbers.Hexadecimaldigitsaresimply replacedbytheappropriatefourbinarydigits.Sincethemaximumhexadecimaldigitisequivalenttodecimalnumber15,weneedtouse fourbinarydigitstorepresentonehexadecimaldigit.Forexample:

Fig.06Hexadecimaltobinarynumberconversion

MarkingNumbers
Thehexadecimalnumberingsystemisalongwithbinaryanddecimal numbersystemsconsideredtobethemostimportantforus.Itiseasyto makeconversionofanyhexadecimalnumbertobinaryanditisalso easytorememberit.However,theseconversionsmaycauseconfusion. Forexample,whatdoesthestatementItisnecessarytocountup110 productsonassemblylineactuallymean?Dependingonwhetheritis aboutbinary,decimalorhexadecimal,theresultcouldbe6,110or272 products,respectively!Accordingly,inordertoavoidmisunderstanding, differentprefixesandsuffixesaredirectlyaddedtothenumbers.The prefix$or0xaswellasthesuffixhmarksthenumbersinhexadecimal system.Forexample,hexadecimalnumber10AFmaylookasfollows $10AF,0x10AFor10AFh.Similarly,binarynumbersusuallygetthe suffix%or0b,whereasdecimalnumbersgetthesuffixD.

Comparativetablebelowcontainsthevalues ofnumbers0255inthreedifferentnumbering systems.

Bit
Theorysaysabitisthebasicunitofinformation...Letsforgetthisdryexplanationforamomentandtakealookatwhatitisinpractice.The answerisnothingspecialabitisabinarydigit.Similartodecimalnumbersysteminwhichdigitsinanumberdonothavethesamevalue( forexampledigitsinthenumber444arethesame,buthavedifferentvalues),thesignificanceofthebitdependsonthepositionithasin thebinarynumber.Therefore,thereisnopointtalkingaboutunits,tensetc.Instead,hereitisaboutthezerobit(rightmostbit),firstbit (secondfromtheright)etc.Inaddition,sincethebinarysystemusestwodigitsonly(0and1),thevalueofonebitcanbe0or1. Dontbeconfusedifyoufindsomebithasvalue4,16or64.Itmeansthatbitsvaluesarerepresentedindecimalsystem.Simply,wehave gotsomuchaccustomedtotheusageofdecimalnumbersthattheseexpressionsbecamecommon.Itwouldbecorrecttosayforexample, thevalueofsixthbitinbinarynumberisequivalenttodecimalnumber64.Butwearehumanandhabitsdiehard...Besides,howwouldit soundnumber:oneonezeroonezero...

Byte
Abyteoraprogramwordconsistsofeightbitsgroupedtogether.Ifabitisadigit,itislogicalthatbytesrepresentnumbers.Allmathematical operationscanbeperformeduponthem,likeuponcommondecimalnumbers.Asisthecasewithdigitsofanyothernumber,bytedigitsdo

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

4/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

nothavethesamesignificance.Thelargestvaluehastheleftmostbitcalledthemostsignificantbit(MSB).Therightmostbithastheleast valueandisthereforecalledtheleastsignificantbit(LSB).Sinceeightzerosandunitsofonebytecanbecombinedin256differentways, thelargestdecimalnumberwhichcanberepresentedbyonebyteis255(onecombinationrepresentszero). Anibbleisreferredtoashalfabyte.Dependingonwhichhalfofthebytewearetalkingabout(leftorright),therearehighandlow nibbles.

Fig.08HighandLownibbles

LogicCircuits
Haveyoueverwonderedwhatelectronicswithinsomedigitalintegratedcircuits,microcontrollersorprocessorslooklike?Whatdothe circuitsperformingcomplicatedmathematicaloperationsandmakingdecisionslooklike?Doyouknowthattheirseeminglycomplicated schematicscompriseonlyafewdifferentelementscalledlogiccircuitsorlogicgates? TheoperationoftheseelementsisbasedontheprinciplesestablishedbyBritishmathematicianGeorgeBooleinthemiddleofthe19th centuryevenbeforethefirstbulbwasinvented!Inbrief,themainideawastoexpresslogicalformsthroughalgebraicfunctions.Such thinkingwassoontransformedintoapracticalproductwhichfarlaterevaluatedinwhattodayisknownasAND,ORandNOTlogiccircuits. TheprincipleoftheiroperationisknownasBooleanalgebra.Assomeprograminstructionsusedbythemicrocontrollerperformthesame wayaslogicgatesexceptintheformofcommands,theprincipleoftheiroperationwillbediscussedhere.

ANDGate
AlogicgateANDhastwoormoreinputsandoneoutput.Letuspresumethatthegateusedinthiscasehasonlytwoinputs.Alogicone (1)willappearonitsoutputonlyincasebothinputs(AANDB)aredriventologicone(1). Thetableshowsmutualdependencebetweeninputsandoutput. Whenthegatehasmorethantwoinputs,theprincipleofoperationisthe same:alogicone(1)willappearonitsoutputonlyifcaseallinputsare driventologicone(1).Anyothercombinationofinputvoltageswillresultin alogiczero(0)atitsoutput.

Whenusedinaprogram,alogicANDoperationisperformedbytheprogram instruction,whichwillbediscussedlater.Forthetimebeing,itisenoughto rememberthatlogicANDinaprogramreferstothecorrespondingbitsoftwo registers.

ORGate
Similarlytothepreviouscase,ORgatesalsohavetwoormoreinputsand oneoutput.Alogicone(1)willappearonitsoutputifeitherinput(AORB) isdriventologicone(1).Ifallinputsareatlogiczero(0),theoutputwillbe driventologiczero(0).

Inaprogram,logicORoperationisperformedbetweenthecorrespondingregisters bitsthesameasinlogicANDoperation.

NOTGate
Thislogicgatehasonlyoneinputandonlyoneoutput.Itoperatesinan extremelysimpleway.Whenlogiczero(0)appearsonitsinput,alogicone (1)appearsonitsoutputandviceversa.Thismeansthatthisgateinverts thesignalbyitself.Itissometimescalledinverter.

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

5/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers


Ifaprogram,logicNOToperationisperformedononebyte.Theresultisabytewith invertedbits.Ifbyteisconsideredtobeanumber,theinvertedvalueisactuallya complementofthatnumber,i.e.thecomplementofanumberiswhatisneededto addtoittomakeitreachthemaximal8bitvalue(255).

EXCLUSIVEORGate
TheEXCLUSIVEOR(XOR)gateisabitcomplicatedcomparingtoothergates.Itrepresentsacombination ofallthepreviouslydescribedgates.Alogicone(1)appearsonitsoutputonlywhentheinputshave differentlogicstates.

Inaprogram,thisoperationiscommonlyusedtocomparetwobytes.Subtraction maybeusedforthesamepurpose(iftheresultis0,bytesareequal).Theadvantage ofthislogicoperationisthatthereisnodangertosubtractlargernumberfrom smallerone.

Register
Aregisteroramemorycellisanelectroniccircuitwhichcanmemorizethestateofonebyte.

Fig.017Register

SpecialFunctionRegister
Inadditiontotheregisterswhichdonothaveanyspecialandpredeterminedfunction,everymicrocontrollerhasanumberofregisters whosefunctionispredeterminedbythemanufacturer.Theirbitsareconnected(literally)tointernalcircuitssuchastimers,A/Dconverter, oscillatorsandothers,whichmeansthattheyaredirectlyincommandoftheoperationofthemicrocontroller.Imagineeightswitcheswhich areincommandofsomesmallercircuitswithinthemicrocontrolleryouareright!SpecialFunctionRegisters(SFRs)doexactlythat!

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

6/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Fig.018SpecialFunctionRegister

Input/OutputPorts
Inordertomakethemicrocontrolleruseful,ithastobeconnectedtoadditionalelectronics,i.e.peripherals.Eachmicrocontrollerhasoneor moreregisters(calledaport)connectedtothemicrocontrollerpins.Whyinput/output?Becauseyoucanchangethepinsfunctionasyou wish.Forexample,supposeyouwantyourdevicetoturnthreesignalLEDsandsimultaneouslymonitorthelogicstateoffivesensorsor pushbuttons.Someofportsneedtobeconfiguredsothattherearethreeoutputs(connectedtotheLEDs)andfiveinputs(connectedto sensors).Itissimplyperformedbysoftware,whichmeansthatthepinsfunctioncanbechangedduringoperation.

Fig.019Input/Outputports

Oneofthemoreimportantspecificationsofinput/output(I/O)pinsisthemaximumcurrenttheycanhandle.Formostmicrocontrollers, currentobtainedfromonepinissufficienttoactivateanLEDorothersimilarlowcurrentdevice(1020mA).Ifthemicrocontrollerhasmany I/Opins,thenthemaximumcurrentofonepinislower.Simplyput,youcannotexpectallpinstogivemaximumcurrentiftherearemorethan 80ofthemononemicrocontroller.Anotherwayofputtingitisthatthemaximumcurrentstatedinthedataspecificationssheetforthe microprocessorissharedacrossallI/Oports. Anotherimportantpinfunctionisthatitcanhavepullupresistors.Theseresistorsconnectpinstothepositivepowersupplyvoltageand theireffectisvisiblewhenthepinisconfiguredasaninputconnectedtomechanicalswitchorpushbutton.Newerversionsof microcontrollershavepullupresistorsconfigurablebysoftware. Usually,eachI/OportisundercontrolofanotherSFR,whichmeansthateachbitofthatregisterdeterminesthestateofthecorresponding microcontrollerpin.Forexample,bywritinglogicone(1)toonebitofthatcontrolregisterSFR,theappropriateportpinisautomatically configuredasinput.Itmeansthatvoltagebroughttothatpincanbereadaslogic0or1.Otherwise,bywritingzerototheSFR,the appropriateportpinisconfiguredasanoutput.Itsvoltage(0Vor5V)correspondstothestateoftheappropriatebitoftheportregister.

MemoryUnit
Memoryispartofthemicrocontrollerusedfordatastorage.Theeasiestwaytoexplainitistocompareitwithafilingcabinetwithmany drawers.Suppose,thedrawersareclearlymarkedsothatitiseasytoaccessanyofthem.Itiseasyenoughtofindoutthecontentsofthe drawerbyreadingthelabelonthefrontofthedrawer. Eachmemoryaddresscorrespondstoonememorylocation.Thecontentofanylocationbecomesknownbyitsaddressing.Memorycan

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

7/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers


eitherbewrittentoorreadfrom.Thereareseveraltypesofmemorywithin themicrocontroller.

ReadOnlyMemory(ROM)
ROM(ReadOnlyMemory)isusedtopermanentlysavetheprogrambeingexecuted.Thesizeofaprogramthatcanbewrittendependson thesizeofthismemory.Todaysmicrocontrollerscommonlyuse16bitaddressing,whichmeansthattheyareabletoaddressupto64Kb ofmemory,i.e.65535locations.Asanovice,yourprogramwillrarelyexceedthelimitofseveralhundredinstructions.Thereareseveral typesofROM. MaskedROM.MicrocontrollerscontainingthisROMarereservedforthegreatmanufacturers.Programisloadedintothechipbythe manufacturer.Incaseoflargescalemanufacture,thepriceisverylow.Forgetit... OneTimeProgrammableROM(OTPROM).Ifthemicrocontrollercontainsthismemory,youcandownloadaprogramintothismemory,but theprocessofprogramdownloadingisaonewayticket,meaningthatitcanbedoneonlyonce.Ifanerrorisdetectedafterdownloading, theonlythingyoucandoistodownloadthecorrectedprogramtoanotherchip. UVErasableProgrammableROM(UVEPROM).Boththemanufacturingprocessandcharacteristics ofthismemoryarecompletelyidenticaltoOTPROM.However,thepackageofthismicrocontrollerhas arecognizablewindowontheupperside.Itenablesthesurfaceofthesiliconchipinsidetobelitby anUVlamp,whicheffectivelyerasesandprogramfromtheROM. Installationofthiswindowisverycomplicated,whichnormallyaffectstheprice.Fromourpointofview, unfortunatelynegative...

Flashmemory.Thistypeofmemorywasinventedinthe80sinthelaboratoriesofINTELandwererepresentedasthesuccessortotheUV EPROM.Sincethecontentsofthismemorycanbewrittenandclearedpracticallyanunlimitednumberoftimes,themicrocontrollerswith FlashROMareidealforlearning,experimentationandsmallscalemanufacture.Becauseofitspopularity,themostmicrocontrollersare manufacturedinflashversionstoday.So,ifyouaregoingtobuyamicrocontroller,thetypetolookforisdefinitelyFlash! RandomAccessMemory(RAM) OncethepowersupplyisoffthecontentsofRAM(RandomAccessMemory)iscleared.Itisusedfortemporarystoringdataand intermediateresultscreatedandusedduringtheoperationofthemicrocontroller.Forexample,iftheprogramperformsanaddition(of whatever),itisnecessarytohavearegisterrepresentingwhatineverydaylifeiscalledthesum.Forthatpurpose,oneoftheregistersin RAMiscalledthesumandusedforstoringresultsofaddition. ElectricallyErasableProgrammableROM(EEPROM) ThecontentsoftheEEPROMmaybechangedduringoperation(similartoRAM),butremainspermanentlysavedevenuponthepower supplygoesoff(similartoROM).Accordingly,anEEPROMisoftenusedtostorevalues,createdduringoperation,whichmustbe permanentlysaved.Forexample,ifyoudesignanelectroniclockoranalarm,itwouldbegreattoenabletheusertocreateandentera password,butuselessifitislosteverytimethepowersupplygoesoff.TheidealsolutionisthemicrocontrollerwithanembeddedEEPROM.

Interrupt
Themostprogramsuseinterruptsinregularprogramexecution.Thepurposeofthemicrocontrollerismainlytoreactonchangesinits surrounding.Inotherwords,whensomeeventtakesplace,themicrocontrollerdoessomething...Forexample,whenyoupushabuttonon aremotecontroller,themicrocontrollerwillregisteritandrespondtotheorderbychangingachannel,turnthevolumeupordownetc.Ifthe microcontrollerspentmostofitstimeendlesslyafewbuttonsforhoursordays...Itwouldnotbepractical. Themicrocontrollerhaslearntduringitsevolutionatrick.Insteadofcheckingeachpinorbitconstantly,themicrocontrollerdelegatesthe waitissuetothespecialistwhichwillreactonlywhensomethingattentionworthyhappens. ThesignalwhichinformsthecentralprocessoraboutsuchaneventiscalledanINTERRUPT.

CentralProcessorUnit(CPU)
Asitsnamesuggests,thisisaunitwhichmonitorsandcontrolsallprocessesinsidethemicrocontroller.Itconsistsofseveralsmaller subunits,ofwhichthemostimportantare:

InstructionDecoderisapartoftheelectronicswhichrecognizesprograminstructionsandrunsothercircuitsonthe basisofthat.Theinstructionsetwhichisdifferentforeachmicrocontrollerfamilyexpressestheabilitiesofthis circuit.

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

8/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

ArithmeticalLogicalUnit(ALU)performsallmathematicalandlogicaloperationsupondata. AccumulatorisaSFRcloselyrelatedtotheoperationoftheALU.Itisakindofworkingdeskusedforstoringall datauponwhichsomeoperationshouldbeperformed(addition,shift/moveetc.).Italsostorestheresultsreadyfor useinfurtherprocessing.OneoftheSFRs,calledaStatusRegister(PSW),iscloselyrelatedtotheaccumulator.It showsatanygivenmomentthestatusofanumberstoredintheaccumulator(numberisgreaterorlessthanzero etc.).

Fig.022CentralProcessorUnitCPU

Bus
Physically,thebusconsistsof8,16ormorewires.Therearetwotypesofbuses:theaddressbusandthedatabus.Theaddressbus consistsofasmanylinesasnecessaryformemoryaddressing.ItisusedtotransmittheaddressfromtheCPUtothememory.Thedatabus isaswideasthedata,inourcaseitis8bitsorwireswide.Itisusedtoconnectallcircuitsinsidethemicrocontroller.

SerialCommunication
Parallelconnectionsbetweenthemicrocontrollerandperipheralsviainput/outputportsistheidealsolutionforshorterdistancesupto severalmeters.However,inothercaseswhenitisnecessarytoestablishcommunicationbetweentwodevicesonlongerdistancesitis notpossibletouseaparallelconnectionsuchasimplesolutionisoutofquestion.Inthesesituations,serialcommunicationisthebest solution. Today,mostmicrocontrollershavebuiltinseveraldifferentsystemsforserialcommunicationasastandardequipment.Whichofthese systemswillbeuseddependsonmanyfactorsofwhichthemostimportantare:

Howmanydevicesthemicrocontrollerhastoexchangedatawith? Howfastthedataexchangehastobe? Whatisthedistancebetweendevices? Isitnecessarytosendandreceivedatasimultaneously?


OneofthemostimportantthingsconcerningserialcommunicationistheProtocolwhich

Fig.023Serialcommunication

shouldbestrictlyobserved.Itisasetofruleswhichmustbeappliedinorderthatthedevicescancorrectlyinterpretdatatheymutually exchange.Fortunately,themicrocontrollersautomaticallytakecareofthis,sotheworkoftheprogrammer/userisreducedtosimplewrite (datatobesent)andread(receiveddata).

BaudRate
ThetermBaudrateiscommonlyusedtodenotethenumberofbitstransferredpersecond[bps]. Itshouldbenotedthatitreferstobits,notbytes!Itisusuallyrequiredbytheprotocolthateachbyteistransferredalongwithseveralcontrol bits.Itmeansthatonebyteinserialdatastreammayconsistof11bits.Forexample,ifthebaudrateis300bpsthenmaximum37and minimum27bytesmaybetransferredpersecond,whichdependsontypeofconnectionandprotocolinuse. Themostcommonlyusedserialcommunicationsystemsare:

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

9/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

I2C(InterIntegratedCircuit)isasystemusedwhenthedistance betweenthemicrocontrollersisshortandspecializedintegrated circuitsofofanewgeneration(receiverandtransmitterareusually onthesameprintedcircuitboard).Connectionisestablishedvia twoconductorsoneisusedfordatatransferwhereasanotheris usedforsynchronization(clocksignal).Asseeninfigure,one deviceisalwaysthemaster.Itperformsaddressingofoneslave chip(subordinated)beforecommunicationstarts.Inthiswayone microcontrollercancommunicatewith112differentdevices.Baud rateisusually100Kb/sec(standardmode)or10Kb/sec(slowbaudratemode).Systemswiththebaudrateof3.4Mb/sechaverecently appeared.Thedistancebetweendeviceswhichcommunicateviaaninterintegratedcircuitbusislimitedtoseveralmeters. SPI(SerialPeripheralInterfaceBus)isasystemforserial communicationwhichusesuptofourconductors(usuallythree) onefordatareceiving,onefordatasending,onefor synchronizationandone(alternatively)forselectingthedeviceto communicatewith.Itisfullduplexconnection,whichmeansthat dataissentandreceivedsimultaneously.Themaximumbaudrate ishigherthaninI2Cconnection.

UART(UniversalAsynchronousReceiver/Transmitter) Thisconnectionisasynchronous,whichmeansthataspeciallineforclocksignaltransmissionisnotused.Insomesituationsthisfeatureis crucial(forexample,radioconnectionorinfraredwavesremotecontrol).Sinceonlyonecommunicationlineisused,bothreceiverand transmitteroperateatthesamepredefinedrateinordertomaintainnecessarysynchronization.Thisisaverysimplewayoftransferring datasinceitbasicallyrepresentsconversionof8bitdatafromparalleltoserialformat.Baudrateisnothighupto1Mbit/sec.

Oscillator
Evenpulsescomingfromtheoscillatorenableharmonicand synchronousoperationofallcircuitsofthemicrocontroller.The oscillatormoduleisusuallyconfiguredtousequartzcrystalor ceramicresonatorforfrequencystabilization.Furthermore,itcan alsooperatewithoutelementsforfrequencystabilization(likeRC oscillator).Itisimportanttosaythatinstructionsarenotexecuted attherateimposedbytheoscillatoritself,butseveraltimesslower. Ithappensbecauseeachinstructionisexecutedinseveralsteps. Insomemicrocontrollers,thesamenumberofcyclesisneededto executeanyinstruction,whileinothers,theexecutiontimeisnot thesameforallinstructions.Accordingly,ifthesystemusesquartz crystalwithafrequencyof20Mhz,executiontimeofaninstruction isnot50nS,but200,400or800nS,dependingonthetypeof MicrocontrollerUnit(MCU)!

Powersupplycircuit
Therearetwothingsworthattentionconcerningthemicrocontrollerpowersupplycircuit: Brownoutisapotentiallydangerousstatewhichoccursatthemomentthemicrocontrollerisbeingturnedofforinsituationswhenpower supplyvoltagedropstothelimitduetoelectricnoise.Asthemicrocontrollerconsistsofseveralcircuitswhichhavedifferentoperating voltagelevels,thisstatecancauseitsoutofcontrolperformance.Inordertopreventit,themicrocontrollerusuallyhasbuiltincircuitfor brownoutreset.Thiscircuitimmediatelyresetsthewholeelectronicswhenthevoltageleveldropsbelowthelimit. ResetpinisusuallymarkedasMCLR(MasterClearReset)andservesforexternalresetofthemicrocontrollerbyapplyinglogiczero(0)or one(1),dependingontypeofthemicrocontroller.Incasethebrownoutcircuitisnotbuiltin,asimpleexternalcircuitforbrownoutresetcan beconnectedtothispin.

Timers/Counters
Themicrocontrolleroscillatorusesquartzcrystalforitsoperation.Eventhoughitisnotthesimplestsolution,therearemanyreasonstouse it.Namely,thefrequencyofsuchoscillatorispreciselydefinedandverystable,thepulsesitgeneratesarealwaysofthe

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

10/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Fig.027Timers/Counters

samewidth,whichmakesthemidealfortimemeasurement.Suchoscillatorsareusedinquartzwatches.Ifitisnecessarytomeasuretime betweentwoevents,itissufficienttocountpulsescomingfromthisoscillator.Thatisexactlywhatthetimerdoes. Mostprogramsusetheseminiatureelectronicstopwatches.Thesearecommonly8or16bitSFRsandtheircontentisautomatically incrementedbyeachcomingpulse.Oncearegisteriscompletelyloadedaninterruptisgenerated! Ifthetimerregistersuseaninternalquartzoscillatorfortheiroperationthenitispossibletomeasuretimebetweentwoevents(iftheregister valueisT1atthemomentmeasurementhasstarted,andT2atthemomentithasfinished,thentheelapsedtimeisequaltotheresultof subtractionT2T1).Iftheregistersusepulsescomingfromexternalsourcethensuchatimeristurnedintoacounter. Thisisonlyasimpleexplanationoftheoperationitself.

Howdoesatimeroperate?
Inpracticepulsescomingfromthequartzoscillatorareoncepereachmachinecycledirectlyorviaaprescalerbroughttothecircuitwhich incrementsthenumberinthetimerregister.Ifoneinstruction(onemachinecycle)lastsforfourquartzoscillatorperiodsthen,byembedding quartzwiththefrequencyof4MHz,thisnumberwillbechangedamilliontimespersecond(eachmicrosecond).

Fig.028TimerOperation

Itiseasytomeasureshorttimeintervals(upto256microseconds)inthewaydescribedabovebecauseitisthelargestnumberthatone registercancontain.Thisobviousdisadvantagemaybeeasilyovercomeinseveralwaysbyusingasloweroscillator,registerswithmore bits,aprescalerorinterrupts.Thefirsttwosolutionshavesomeweaknessessoitispreferabletouseprescalersorinterupts.

Usingprescalerintimeroperating
Aprescalerisanelectronicdeviceusedtoreduceafrequencybyapredeterminedfactor.Meaningthatinordertogenerateonepulseon itsoutput,itisnecessarytobring1,2,4ormorepulsestoitsinput.Onesuchcircuitisbuiltinthemicrocontrolleranditsdivisionratecanbe changedfromwithintheprogram.Itisusedwhenitisnecessarytomeasurelongerperiodsoftime. Oneprescalerisusuallysharedbytimerandwatchdogtimer,whichmeansthatitcannotbeusedbybothofthemsimultaneously.

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

11/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Fig.029Usingprescalerintimeroperating

Usingtheinterruptintimeroperation
Ifthetimerregisterconsistsof8bits,thelargestnumberthatcanbewrittentoitis255(for16bitregistersitisthenumber65.535).Ifthis numberisexceeded,thetimerwillbeautomaticallyresetandcountingwillstartfromzeroagain.Thisconditioniscalledoverflow.Ifenabled fromwithintheprogram,suchoverflowcancauseaninterrupt,whichgivescompletelynewpossibilities.Forexample,thestateofregisters usedforcountingseconds,minutesordayscanbechangedinaninterruptroutine.Thewholeprocess(exceptinterruptroutine)is automaticallyperformedinthebackground,whichenablesthemaincircuitsofthemicrocontrollertoperformotheroperations.

Fig.030Usingtheinterruptintimeroperation

Thisfigureillustratestheuseoftheinterruptintimeroperation.Delaysofarbitrarydurationwithminimalinterferencebythemainprogram executioncanbeeasilyobtainedbyassigningaprescalertothetimer.

Counters
Ifatimerissupplyingpulsesintothemicrocontrollerinputpinthenitturnsintoacounter.Clearly,Itisthesameelectroniccircuit.Theonly differenceisthatinthiscasepulsestobecountedcomethroughtheportsandtheirduration(width)ismostlynotdefined.Thisiswhythey cannotbeusedfortimemeasurement,butcanbeusedtomeasureanythingelse:productsonanassemblyline,numberofaxisrotation, passengersetc.(dependingonsensorinuse).

WatchdogTimer
TheWatchdogTimerisatimerconnectedtoacompletelyseparateRCoscillatorwithinthemicrocontroller. Ifthewatchdogtimerisenabled,everytimeitcountsuptotheprogramend,themicrocontrollerresetoccursandprogramexecutionstarts fromthefirstinstruction.Thepointistopreventthisfromhappeningbyusingaspecificcommand.Thewholeideaisbasedonthefactthat everyprogramisexecutedinseverallongerorshorterloops. Ifinstructionswhichresetthewatchdogtimeraresetattheappropriateprogramlocations,besidescommandsbeingregularlyexecuted, thentheoperationofthewatchdogtimerwillnotaffectprogramexecution.Ifforanyreason(usuallyelectricalnoisesinindustry),the programcountergetsstuckonsomememorylocationfromwhichthereisnoreturn,thewatchdogwillnotbeclearedandtheregisters valuebeingconstantlyincrementedwillreachthemaximumetvoila!Resetoccurs!

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

12/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Fig.031WatchdogTimer

A/DConverter
Externalsignalsareusuallyfundamentallydifferentfromthosethemicrocontrollerunderstands(OnesandZeros),sothattheyhavetobe convertedinorderforthemicrocontrollertounderstandthem.Ananaloguetodigitalconverterisanelectroniccircuitwhichconverts continuoussignalstodiscretedigitalnumbers.Thismoduleisthereforeusedtoconvertsomeanaloguevalueintobinarynumberand forwardsittotheCPUforfurtherprocessing.Inotherwords,thismoduleisusedforinputpinvoltagemeasurement(analoguevalue).The resultofmeasurementisanumber(digitalvalue)usedandprocessedlaterintheprogram.

Fig.032A/DConverter

InternalArchitecture
AllupgradedmicrocontrollersuseoneoftwobasicdesignmodelscalledHarvardandvonNeumannarchitecture. Briefly,theyaretwodifferentwaysofdataexchangebetweenCPUandmemory. vonNeumannArchitecture Microcontrollersusingthisarchitecturehaveonlyonememoryblockandone8bitdatabus.Asalldata areexchangedbyusingthese8lines,thisbusisoverloadedandcommunicationitselfisveryslowand inefficient.TheCPUcaneitherreadaninstructionorread/writedatafrom/tothememory.Bothcannot occuratthesametimesincetheinstructionsanddatausethesamebussystem.Forexample,ifsome programlinesaysthatRAMmemoryregistercalledSUMshouldbeincrementedbyone(instruction: incfSUM),themicrocontrollerwilldothefollowing:

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

13/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

1. ReadthepartoftheprograminstructionspecifyingWHATshouldbedone(inthisverycaseitistheincf instructionforincrement). 2. ReadfurtherthesameinstructionspecifyinguponWHICHdataitshouldbeperformed(inthisverycaseitisthe SUMregister). 3. Afterbeingincremented,thecontentsofthisregistershouldbewrittentotheregisterfromwhichitwasread (SUMregisteraddress).


Thesamedatabusisusedforalltheseintermediateoperations. HarvardArchitecture Microcontrollersusingthisarchitecturehavetwodifferentdata buses.Oneis8bitswideandconnectsCPUtoRAM.Another consistsofseverallines(12,14or16)andconnectsCPUtoROM. Accordingly,theCPUcanreadaninstructionandperformadata memoryaccessatthesametime.SinceallRAMmemoryregisters are8bitswide,alldatawithinthemicrocontrollerareexchanged inthesamesuchformat.Additionally,duringprogramwriting,only 8bitsdataareconsidered.Inotherwords,allyoucaneverchange fromwithintheprogramandallyoucanaffectwillbe8bitswide.A programwrittenforsomeofthesemicrocontrollerswillbestoredin themicrocontrollerinternalROMuponhavingbeingcompiledinto machinelanguage.However,thesememorylocationsdonothave 8,but12,14or16bits.Therestofbits4,6or8representsthe instructionitselfspecifyingtotheCPUwhattodowiththe8bit data. Theadvantagesofsuchdesignarethefollowing:

Alldatainaprogramisonebyte(8bit)wide.Asthedatabususedforprogramreadinghasseverallines(12,14or 16),bothinstructionsanddatacanbereadsimultaneouslybyusingthesesparebits.Therefore,allinstructionsare executedinonlyoneinstructioncycle.Theonlyexceptionisjumpinstructionwhichisexecutedintwocycles. Owingtothefactthataprogram(ROM)andtemporarydata(RAM)areseparate,theCPUcanexecutetwo instructionssimultaneously.Simply,whileRAMreadorwriteisinprogress(theendofoneinstruction),thenext programinstructionisbeingreadviaanotherbus. WhenusingmicrocontrollerswithvonNeumannarchitectureoneneverknowshowmuchmemoryistobeoccupied bysomeprogram.Basically,eachprograminstructionoccupiestwomemorylocations(onecontainsinformationon WHATshouldbedone,whereasanothercontainsinformationuponWHICHdataitshouldbedone).However,itisnot ahardandfastrule,butthemostcommoncase.InmicrocontrollerswithHarvardarchitecture,theprogrambusis widerthanonebyte,whichallowseachprogramwordtoconsistofinstructionanddata.Inotherwords:oneprogram wordoneinstruction.
INSTRUCTIONSET
Instructionsthatcanbeunderstoodbythemicrocontrollerareknownasaninstructionset.Whenyouwritea programinassemblylanguage,youactuallytellastorybyspecifyinginstructionsintheordertheyshouldbe executed.Themainrestrictioninthisprocessisthenumberofavailableinstructions.Themanufacturersstickto oneofthetwofollowingstrategies:

RISC(ReducedInstructionSetComputer) Inthiscase,themicrocontrollerrecognizesandexecutesonlybasicoperations(addition,subtraction,copyingetc.).Allothermore complicatedoperationsareperformedbycombiningthese(forexample,multiplicationisperformedbyperformingsuccessiveaddition).The constrainsareobvious(trybyusingonlyafewwords,toexplaintosomeonehowtoreachtheairportinsomeothercity).However,thereare alsosomegreatadvantages.Firstofall,thislanguageiseasytolearn.Besides,themicrocontrollerisveryfastsothatitisnotpossibleto seeallthearithmeticacrobaticsitperforms.Theusercanonlyseethefinalresultofallthoseoperations.Atlast,itisnotsodifficultto explainwheretheairportisifyouusetherightwords.Forexample:left,right,kilometersetc. CISC(ComplexInstructionSetComputer) CISCistheoppositeofRISC!Microcontrollersdesignedtorecognizemorethan200differentinstructionscandomuchandareveryfast. However,oneneedstounderstandhowtotakeallthatsucharichlanguageoffers,whichisnotatalleasy...

Howtomaketherightchoice
Ok,youarethebeginnerandyouhavemadeadecisiontogoonanadventureofworkingwiththemicrocontrollers.Congratulationson yourchoice!However,itisnotaseasytochoosetherightmicrocontrollerasitmayseem.Theproblemisnotalimitedrangeofdevices,but theopposite! Beforeyoustartdesigningsomedevicebasedonthemicrocontroller,thinkofthefollowing:howmanyinput/outputlineswillIneedfor operation?Shoulditperformsomeotheroperationsthantosimplyturnrelayson/off?Doesitneedsomespecializedmodulesuchasserial communication,A/Dconverteretc.Whenyoucreateaclearpictureofwhatyouneed,theselectionrangeisconsiderablyreduced,thenitis timetothinkofprice.Isyourplantohaveseveralsamedevices?Severalhundred?Amillion?Anyway,yougetthepoint... Ifyouthinkofallthesethingsfortheveryfirsttimetheneverythingseemsabitconfusing.Forthatreason,gostepbystep.Firstofall,select

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

14/16

19/05/13

Introduction: World of microcontrollers - Book: PIC Microcontrollers

themanufacturer,i.e.thefamilyofthemicrocontrollersyoucaneasilyobtain.Afterthat,studyoneparticularmodel.Learnasmuchasyou need,donotgointodetails.Solveaspecificproblemandsomethingincrediblewillhappenyouwillbeabletohandleanymodel belongingtothatfamily. Rememberlearningtorideabicycle:afterseveralunavoidablebruisesatthebeginning,youwillmanagetokeepbalanceandwillbeable toeasilyrideanyotherbicycle.Andofcourse,youwillneverforgettheskillinprogrammingjustasyouwillneverforgetridingbicycles!

PICmicrocontrollers
PICmicrocontrollersdesignedbyMicrochipTechnologyarelikelytherightchoiceforyouifyouarethebeginner.Hereiswhy... TherealnameofthismicrocontrollerisPICmicro(PeripheralInterfaceController),butitisbetterknownasPIC.Itsfirstancestorwas designedin1975byGeneralInstruments.ThischipcalledPIC1650wasmeantfortotallydifferentpurposes.Abouttenyearslater,by addingEEPROMmemory,thiscircuitwastransformedintoarealPICmicrocontroller.Nowadays,MicrochipTechnologyannouncesa manufacturingofthe5billionthsample... Inorderthatyoucanbetterunderstandthereasonsforitspopularity,wewillbrieflydescribeseveralimportantthings.
ROM [Kbytes] RAM [bytes] Clock Freq. [MHz] A/D Inputs Resolution of A/D Converter Comparators 8/16 bit Timers Serial Comm. PWM Outputs

Family

Pins

Others

Base-Line 8 - bit architecture, 12-bit Instruction Word Length PIC10FXXX PIC12FXXX PIC16FXXX PIC16HVXXX 0.375 0.75 0.75 1.5 0.75 - 3 1.5 16 - 24 25 - 38 25 134 25 6-8 8 14 44 18 20 4-8 4-8 20 20 0-2 0-3 0-3 8 8 8 0-1 0-1 0-2 1x 8 1x 8 1x 8 1x 8 EEPROM EEPROM Vdd = 15V

Mid-Range 8 - bit architecture, 14-bit Instruction World Length PIC12FXXX 1.75 3.5 64 128 8 20 0-4 10 1 1-2x 81x 16 1-2x 81x 16 1-2x 81x 16 2x 81 x 16 0-1 EEPROM

PIC12HVXXX

1.75

64

20

0-4

10

0-1

PIC16FXXX

1.75 - 14

64 368 64 128

14 64 14 20

20

0 - 13

8 or 10

0-2

USART I2C SPI USART I2C SPI

0-3

PIC16HVXXX

1.75 3.5

20

0 - 12

10

High-End 8 - bit architecture, 16-bit Instruction Word Length 256 3936 18 80 32 48 0-2x 82-3 x 16 0-2x 82-3 x 16 1x 83 x 16 USB2.0 CAN2.0 USART I2C SPI USB2.0 USART Ethernet I2C SPI USART I2C SPI

PIC18FXXX

4 - 128

4 - 16

10 or 12

0-3

0-5

PIC18FXXJXX

8 - 128

1024 3936 768 3936

28 100 28 44

40 48

10 - 16

10

2-5

PIC18FXXKXX

8 - 64

64

10 - 13

10

AllPICmicrocontrollersuseharvardarchitecture,whichmeansthattheirprogrammemoryisconnectedtoCPUviamorethan8lines. Dependingonthebuswidth,thereare12,14and16bitmicrocontrollers.Thetableaboveshowsthemainfeaturesofthesethree categories. Asseeninthetableonthepreviouspage,excepting16bitmonstersPIC24FXXXandPIC24HXXXallPICmicrocontrollershave8bit harvardarchitectureandbelongtooneoutofthreelargegroups.Therefore,dependingonthesizeofaprogramwordtherearefirst,second andthirdcategory,i.e.12,14or16bitmicrocontrollers.Havingsimilar8bitcore,allofthemusethesameinstructionsetandthebasic hardwareskeletonconnectedtomoreorlessperipheralunits. Inordertoavoidtediousexplanationsandendlessstoryabouttheusefulfeaturesofdifferentmicrocontrollers,thisbookdescribesthe operationofoneparticularmodelbelongingtohighmiddleclass.ItisaboutPIC16F887powerfulenoughtobeworthattentionandsimple enoughtobeeasilypresentedtoeverybody. tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers

AVR Solution
AVR Development Boards

ARM Solution
ARM Development Boards

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

15/16

19/05/13
AVR Compilers AVR Programmers/Debuggers AVR Kits

Introduction: World of microcontrollers - Book: PIC Microcontrollers


ARM Compilers ARM Programmers/Debuggers ARM Kits 8051 Programmers/Debuggers 8051 Books 8051 Kits Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/

16/16

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers


Products Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter1:PIC16F887MicrocontrollerDeviceOverview
ThePIC16F887isoneofthelatestproductsfromMicrochip.Itfeaturesallthecomponentswhichmodernmicrocontrollersnormallyhave. Foritslowprice,widerangeofapplication,highqualityandeasyavailability,itisanidealsolutioninapplicationssuchas:thecontrolof differentprocessesinindustry,machinecontroldevices,measurementofdifferentvaluesetc.Someofitsmainfeaturesarelistedbelow.

RISCarchitecture
Only35instructionstolearn Allsinglecycleinstructionsexceptbranches

256bytesEEPROMmemory
Datacanbewrittenmorethan1.000.000times

Operatingfrequency020MHz Precisioninternaloscillator
Factorycalibrated Softwareselectablefrequencyrangeof8MHzto31KHz

368bytesRAMmemory A/Dconverter:
14channels 10bitresolution

Powersupplyvoltage2.05.5V
Consumption:220uA(2.0V,4MHz),11uA(2.0V,32KHz) 50nA(standbymode)

3independenttimers/counters Watchdogtimer Analoguecomparatormodulewith


Twoanaloguecomparators Fixedvoltagereference(0.6V) Programmableonchipvoltagereference

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

PowerSavingSleepMode BrownoutReset(BOR)withsoftwarecontrol option 35input/outputpins


Highcurrentsource/sinkfordirectLEDdrive softwareandindividuallyprogrammablepullupresistor InterruptonChangepin

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

PWMoutputsteeringcontrol EnhancedUSARTmodule
SupportsRS485,RS232andLIN2.0 AutoBaudDetect

MasterSynchronousSerialPort(MSSP)
supportsSPIandI2Cmode

8KROMmemoryinFLASHtechnology
Chipcanbereprogrammedupto100.000times

InCircuitSerialProgrammingOption
Chipcanbeprogrammedevenembeddedinthetarget device Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

Fig.11PIC16F887PDIP40Microcontroller

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

1/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Fig.12PIC16F887QFN44Microcontroller

Fig.13PIC16F887BlockDiagram

PinDescription
AsseeninFig.11above,themostpinsaremultifunctional.Forexample,designatorRA3/AN3/Vref+/C1IN+forthefifthpinspecifiesthe followingfunctions:

RA3PortAthirddigitalinput/output AN3Thirdanaloginput Vref+Positivevoltagereference C1IN+ComparatorC1positiveinput


Thissmalltrickisoftenusedbecauseitmakesthemicrocontrollerpackagemorecompactwithoutaffectingitsfunctionality.Thesevarious pinfunctionscannotbeusedsimultaneously,butcanbechangedatanypointduringoperation. Thefollowingtables,refertothePDIP40microcontroller.

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

2/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Table11PinAssignment

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

3/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Table11cont.PinAssignment

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

4/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Table11cont.PinAssignment

CentralProcessorUnit(CPU)
ImnotgoingtoboreyouwiththeoperationoftheCPUatthisstage,howeveritisimportanttostatethattheCPUismanufacturedwithin RISCtechnologyanimportantfactorwhendecidingwhichmicroprocessortouse. RISCReducedInstructionSetComputer,givesthePIC16F887twogreatadvantages:

TheCPUcanrecognizesonly35simpleinstructions(Inordertoprogramsomeothermicrocontrollersitisnecessary toknowmorethan200instructionsbyheart). Theexecutiontimeisthesameforallinstructionsexcepttwoandlasts4clockcycles(oscillatorfrequencyis stabilizedbyaquartzcrystal).TheJumpandBranchinstructionsexecutiontimeis2clockcycles.Itmeansthatifthe microcontrollersoperatingspeedis20MHz,executiontimeofeachinstructionwillbe200nS,i.e.theprogramwillbe executedatthespeedof5millioninstructionspersecond!

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

5/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers


Fig.14CPUMemory

Memory
ThismicrocontrollerhasthreetypesofmemoryROM,RAMandEEPROM.Allofthemwillbeseparatelydiscussedsinceeachhasspecific functions,featuresandorganization.

ROMMemory
ROMmemoryisusedtopermanentlysavetheprogrambeingexecuted.Thisiswhyitisoftencalledprogrammemory.ThePIC16F887 has8KbofROM(intotalof8192locations).SincethisROMismadewithFLASHtechnology,itscontentscanbechangedbyprovidinga specialprogrammingvoltage(13V). Anyway,thereisnoneedtoexplainitindetailbecauseitisautomaticallyperformedbymeansofaspecialprogramonthePCandasimple electronicdevicecalledtheProgrammer.

Fig.15ROMMemoryConsept

EEPROMMemory
Similartoprogrammemory,thecontentsofEEPROMispermanentlysaved,eventhepowergoesoff.However,unlikeROM,thecontentsof theEEPROMcanbechangedduringoperationofthemicrocontroller.Thatiswhythismemory(256locations)isaperfectonefor permanentlysavingresultscreatedandusedduringtheoperation.

RAMMemory
Thisisthethirdandthemostcomplexpartofmicrocontrollermemory.Inthiscase,itconsistsoftwoparts:generalpurposeregistersand specialfunctionregisters(SFR). Eventhoughbothgroupsofregistersareclearedwhenpowergoesoffandeventhoughtheyaremanufacturedinthesamewayandactin thesimilarway,theirfunctionsdonothavemanythingsincommon.

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

6/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Fig.16SFRandGeneralPurposeRegisters

GeneralPurposeRegisters
GeneralPurposeregistersareusedforstoringtemporarydataandresultscreatedduringoperation.Forexample,iftheprogramperformsa counting(forexample,countingproductsontheassemblyline),itisnecessarytohavearegisterwhichstandsforwhatweineverydaylife callsum.Sincethemicrocontrollerisnotcreativeatall,itisnecessarytospecifytheaddressofsomegeneralpurposeregisterandassign itanewfunction.Asimpleprogramtoincrementthevalueofthisregisterby1,aftereachproductpassesthroughasensor,shouldbe created. Therefore,themicrocontrollercanexecutethatprogrambecauseitnowknowswhatandwherethesumwhichmustbeincrementedis. Similarlytothissimpleexample,eachprogramvariablemustbepreassignedsomeofgeneralpurposeregister.

SFRRegisters
SpecialFunctionregistersarealsoRAMmemorylocations,butunlikegeneralpurposeregisters,theirpurposeispredeterminedduring manufacturingprocessandcannotbechanged.Sincetheirbitsarephysicallyconnectedtoparticularcircuitsonthechip(A/Dconverter, serialcommunicationmodule,etc.),anychangeoftheircontentsdirectlyaffectstheoperationofthemicrocontrollerorsomeofitscircuits. Forexample,bychangingtheTRISAregister,thefunctionofeachportApincanbechangedinawayitactsasinputoroutput.Another featureofthesememorylocationsisthattheyhavetheirnames(registersandtheirbits),whichconsiderablyfacilitatesprogramwriting. Sincehighlevelprogramminglanguagecanusethelistofallregisterswiththeirexactaddresses,itisenoughtospecifytheregisters nameinordertoreadorchangeitscontents.

RAMMemoryBanks
Thedatamemoryispartitionedintofourbanks.Priortoaccessingsomeregisterduringprogramwriting(inordertoreadorchangeits contents),itisnecessarytoselectthebankwhichcontainsthatregister.TwobitsoftheSTATUSregisterareusedforbankselecting,which willbediscussedlater.Inordertofacilitateoperation,themostcommonlyusedSFRshavethesameaddressinallbankswhichenables themtobeeasilyaccessed.

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

7/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Table12AddressBanks

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

8/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Table13SFRBank0

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

9/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Table14SFRBank1

Table15SFRBank2

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

10/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

Table16SFRBank3

STACK
ApartoftheRAMusedforthestackconsistsofeight13bitregisters.Beforethemicrocontrollerstartstoexecuteasubroutine(C A L L instruction)orwhenaninterruptoccurs,theaddressoffirstnextinstructionbeingcurrentlyexecutedispushedontothestack,i.e.ontoone ofitsregisters.Inthatway,uponsubroutineorinterruptexecution,themicrocontrollerknowsfromwheretocontinueregularprogram execution.Thisaddressiscleareduponreturntothemainprogrambecausethereisnoneedtosaveitanylonger,andonelocationofthe stackisautomaticallyavailableforfurtheruse. Itisimportanttounderstandthatdataisalwayscircularlypushedontothestack.Itmeansthatafterthestackhasbeenpushedeighttimes, theninthpushoverwritesthevaluethatwasstoredwiththefirstpush.Thetenthpushoverwritesthesecondpushandsoon.Data overwritteninthiswayisnotrecoverable.Inaddition,theprogrammercannotaccesstheseregistersforwriteorreadandthereisnoStatus bittoindicatestackoverfloworstackunderflowconditions.Forthatreason,oneshouldtakespecialcareofitduringprogramwriting.

InterruptSystem
Thefirstthingthatthemicrocontrollerdoeswhenaninterruptrequestarrivesistoexecutethecurrentinstructionandthenstopregular programexecution.Immediatelyafterthat,thecurrentprogrammemoryaddressisautomaticallypushedontothestackandthedefault address(predefinedbythemanufacturer)iswrittentotheprogramcounter.Thatlocationfromwheretheprogramcontinuesexecutionis calledtheinterruptvector.ForthePIC16F887microcontroller,thisaddressis0004h.AsseeninFig.17below,thelocationcontaining interruptvectorispassedoverduringregularprogramexecution. Partoftheprogrambeingactivatedwhenaninterruptrequestarrivesiscalledtheinterruptroutine.Itsfirstinstructionislocatedatthe interruptvector.Howlongthissubroutinewillbeandwhatitwillbelikedependsontheskillsoftheprogrammeraswellastheinterrupt sourceitself.Somemicrocontrollershavemoreinterruptvectors(everyinterruptrequesthasitsvector),butinthiscasethereisonlyone. Consequently,thefirstpartoftheinterruptroutineconsistsininterruptsourcerecognition. Finally,whentheinterruptsourceisrecognizedandinterruptroutineisexecuted,themicrocontrollerreachestheR E T F I E instruction,pops theaddressfromthestackandcontinuesprogramexecutionfromwhereitleftoff.

Fig.17InterruptSystem

HowtouseSFRs
Youhaveboughtthemicrocontrollerandhaveagoodideahowtouseit...ThereisalonglistofSFRswithallbits.Eachofthemcontrols someprocess.Allinall,itlookslikeabigcontroltablewithalotofinstrumentsandswitches.Nowyouareconcernedaboutwhetheryou willmanagetolearnhowtousethemall?Youwillprobablynot,butdontworry,youdonthaveto!Suchpowerfulmicrocontrollersare similartoasupermarkets:theyoffersomanythingsatlowpricesanditisonlyuptoyoutochoose.Therefore,selectthefieldyouare interestedinandstudyonlywhatyouneedtoknow.Afterwards,whenyoucompletelyunderstandhardwareoperation,studySFRswhich areincontrolofit(thereareusuallyafewofthem).Toreiterate,duringprogramwritingandpriortochangingsomebitsoftheseregisters, donotforgettoselecttheappropriatebank.Thisiswhytheyarelistedinthetablesabove. previouschapter|tableofcontents|nextchapter

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

11/12

19/05/13

Chapter 1: PIC16F887 Microcontroller - Device Overview - Book: PIC Microcontrollers

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/

12/12

19/05/13
Products

Chapter 2: Core SFRs - Book: PIC Microcontrollers


Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter2:CoreSFRs
FeaturesandFunction
Thespecialfunctionregisterscanbeclassifiedintotwocategories:

Core(CPU)registerscontrolandmonitoroperationandprocessesinthecentralprocessor.Eventhoughthereare onlyafewofthem,theoperationofthewholemicrocontrollerdependsontheircontents. PeripheralSFRscontroltheoperationofperipheralunits(serialcommunicationmodule,A/Dconverteretc.).Eachof theseregistersismainlyspecializedforonecircuitandforthatreasontheywillbedescribedalongwiththecircuit theyareincontrolof.


Thecore(CPU)registersofthePIC16F887microcontrolleraredescribedinthischapter.Sincetheirbitscontrolseveraldifferentcircuits withinthechip,itisnotpossibletoclassifythemintosomespecialgroup.Thesebitsaredescribedalongwiththeprocessestheycontrol.

STATUSRegister

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

Fig.21STATUSRegister

TheSTATUSregistercontains:thearithmeticstatusoftheWregister,theRESETstatusandthebankselectbitsfordatamemory.One shouldbecarefulwhenwritingavaluetothisregisterbecauseifyoudoitwrong,theresultsmaybedifferentthanexpected.Forexample,if youtrytoclearallbitsusingtheC L R F S T A T U S instruction,theresultintheregisterwillbe000xx1xxinsteadoftheexpected00000000. Sucherrorsoccurbecausesomeofthebitsofthisregisteraresetorclearedaccordingtothehardwareaswellasbecausethebits3and4 arereadableonly.Forthesereasons,ifitisrequiredtochangeitscontent(forexample,tochangeactivebank),itisrecommendedtouse onlyinstructionswhichdonotaffectanyStatusbits(C,DCandZ).RefertoInstructionSetSummary.

IRP Bitselectsregisterbank.Itisusedforindirectaddressing.
1Banks0and1areactive(memorylocation00hFFh) 0Banks2and3areactive(memorylocation100h1FFh)

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoonesingle chipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhatyou wantthemtodo.Youjusthavetowritea programanddumpitintothe microcontroller.[moreinfo]

RP1,RP0Bitsselectregisterbank.Theyareusedfordirectaddressing.
RP1
0 0 1 1

RP0
0 1 0 1

ACT IVEBANK
Bank0 Bank1 Bank2 Bank3

Table21

TOTimeoutbit.
1AfterpoweronorafterexecutingC L R W D T instructionwhichresetswatchdogtimerorSLEEPinstructionwhichsetsthe microcontrollerintolowconsumptionmode. 0Afterwatchdogtimertimeouthasoccurred.

PDPowerdownbit.
1AfterpoweronorafterexecutingC L R W D T instructionwhichresetswatchdogtimer. 0AfterexecutingS L E E P instructionwhichsetsthemicrocontrollerintolowconsumptionmode.

ZZerobit
1Theresultofanarithmeticorlogicoperationiszero. 0Theresultofanarithmeticorlogicoperationisdifferentfromzero.

DCDigitcarry/borrowbitischangedduringadditionandsubtractionifanoverfloworaborrowoftheresult occurs.
1Acarryoutfromthe4thloworderbitoftheresulthasoccurred. 0Nocarryoutfromthe4thloworderbitoftheresulthasoccurred.

CCarry/Borrowbitischangedduringadditionandsubtractionifanoverfloworaborrowoftheresultoccurs,i.e. iftheresultisgreaterthan255orlessthan0.
1Acarryoutfromthemostsignificantbitoftheresulthasoccurred. 0Nocarryoutfromthemostsignificantbitoftheresulthasoccurred.

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

1/8

19/05/13
OPTION_REGRegister

Chapter 2: Core SFRs - Book: PIC Microcontrollers

Fig.22

TheOPTION_REGregistercontainsvariouscontrolbitstoconfigure:Timer0/WDTprescaler,timerTMR0,externalinterruptandpullupson PORTB.

RBPUPortBPullupEnablebit.
1PortBpullupsaredisabled. 0PortBpullupsareenabled. Fig.23

INTEDGInterruptEdgeSelectbit.
1InterruptonrisingedgeofRB0/INTpin. 0InterruptonfallingedgeofRB0/INTpin. Fig.24

T0CSTMR0ClockSourceSelectbit.
1TransitiononTOCKIpin. 0Internalinstructioncycleclock(Fosc/4). Fig.25

T0SETMR0SourceEdgeSelectbitselectspulseedge(risingorfalling)countedby thetimerTMR0throughtheRA4/T0CKIpin.
1IncrementonhightolowtransitiononTOCKIpin. 0IncrementonlowtohightransitiononTOCKIpin. Fig.26

PSAPrescalerAssignmentbitassignsprescaler(onlyoneexists)tothetimeror watchdogtimer.
1PrescalerisassignedtotheWDT. 0PrescalerisassignedtotheTMR0. Fig.27

PS2,PS1,PS0PrescalerRateSelectbits Prescalerrateisselectedbycombiningthesethreebits.Described,asshowninthetablebelow,prescalerratedependsonwhether prescalerisassigned(TMR0)orwatchdogtimer(WDT).


PS2
0 0 0 0 1 1 1

PS1
0 0 1 1 0 1 1

PS0
0 1 0 1 1 0 1

TMR0
1:2 1:4 1:8 1:16 1:64 1:128 1:256

WDT
1:1 1:2 1:4 1:8 1:32 1:64 1:128

Table22

Inordertoachieve1:1prescalerratewhenthetimerTMR0countsuppulses,theprescalershouldbeassignedtotheWDT.Asaresultof this,thetimerTMR0doesnotusetheprescaler,butdirectlycountspulsesgeneratedbytheoscillator,whichwastheobjective!

InterruptSystemRegisters
Whenaninterruptrequestarrivesitdoesnotmeanthatinterruptwillautomaticallyoccur,becauseitmustalsobeenabledbytheuser(from withintheprogram).Becauseofthat,therearespecialbitsusedtoenableordisableinterrupts.ItiseasytorecognizethesebitsbyIE containedintheirnames(standsforInterruptEnable).Besides,eachinterruptisassociatedwithanotherbitcalledtheflagwhichindicates thatinterruptrequesthasarrivedregardlessofwhetheritisenabledornot.Theyarealsoeasilyrecognizablebythelasttwoletters containedintheirnamesIF(InterruptFlag).

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

2/8

19/05/13

Chapter 2: Core SFRs - Book: PIC Microcontrollers

Asseen,everythingisbasedonasimpleandefficientidea.Whenaninterruptrequestarrives,theflagbitistobesetfirst.

Fig.28InterruptSystemRegisters

IftheappropriateIEbitisnotset(0),thiseventwillbecompletelyignored.Otherwise,aninterruptoccurs!Incaseseveralinterruptsources areenabled,itisnecessarytodetecttheactiveonebeforetheinterruptroutinestartsexecution.Sourcedetectionisperformedbychecking flagbits. Itisimportanttounderstandthattheflagbitsarenotautomaticallycleared,butbysoftwareduringinterruptroutineexecution.Ifthisdetailis neglected,anotherinterruptwilloccurimmediatelyuponreturntotheprogram,eventhoughtherearenomorerequestsforitsexecution! Simplyput,theflagaswellasIEbitremainedset. AllinterruptsourcestypicalofthePIC16F887microcontrollerareshownonthenextpage.Noteseveralthings:

GIEbitenablesallunmaskedinterruptsanddisablesallinterruptssimultaneously. PEIEbitenablesallunmaskedperipheralinterruptsanddisablesallperipheralinterrupts(Thisdoesnotconcern TimerTMR0andportBinterruptsources).


ToenableinterruptcausedbychanginglogicstateonportB,itisnecessarytoenableitforeachbitseparately.Inthiscase,bitsoftheIOCB registerhavethefunctiontocontrolIEbits.

Fig.29InterruptSFRs

INTCONRegister
TheINTCONregistercontainsvariousenableandflagbitsforTMR0registeroverflow,PORTBchangeandexternalINTpininterrupts.

Fig.210INTCONRegister

GIEGlobalInterruptEnablebitcontrolsallpossibleinterruptsourcessimultaneously.
1Enablesallunmaskedinterrupts. 0Disablesallinterrupts.

PEIEPeripheralInterruptEnablebitactssimilartoGIE,butcontrolsinterruptsenabledbyperipherals.Itmeans thatitdoesnotaffectinterruptstriggeredbythetimerTMR0orbychangingstateonportBorRB0/INTpin.
1Enablesallunmaskedperipheralinterrupts.

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

3/8

19/05/13
0Disablesallperipheralinterrupts.

Chapter 2: Core SFRs - Book: PIC Microcontrollers

T0IETMR0OverflowInterruptEnablebitcontrolsinterruptenabledbyTMR0overflow.
1EnablestheTMR0interrupt. 0DisablestheTMR0interrupt.

INTERB0/INTExternalInterruptEnablebitcontrolsinterruptcausedbychanginglogicstateonpinRB0/IN (externalinterrupt).
1EnablestheINTexternalinterrupt. 0DisablestheINTexternalinterrupt.

RBIERBPortChangeInterruptEnablebit.Whenconfiguredasinputs,portBpinsmaycauseinterruptby changingtheirlogicstate(nomatterwhetheritishightolowtransitionorviceversa,factthatsomethingischanged onlymatters).Thisbitdetermineswhetherinterruptistooccurornot.


1EnablestheportBchangeinterrupt. 0DisablestheportBchangeinterrupt.

T0IFTMR0OverflowInterruptFlagbitregistersthetimerTMR0registeroverflow,whencountingstartsfromzero.
1TMR0registerhasoverflowed(bitmustbeclearedinsoftware). 0TMR0registerhasnotoverflowed.

INTFRB0/INTExternalInterruptFlagbitregisterschangeoflogicstateontheRB0/INTpin.
1TheINTexternalinterrupthasoccurred(mustbeclearedinsoftware). 0TheINTexternalinterrupthasnotoccurred.

RBIFRBPortChangeInterruptFlagbitregisterschangeoflogicstateofsomeportBinputpins.
1AtleastoneoftheportBgeneralpurposeI/Opinshaschangedstate.UponreadingportB,RBIF(flagbit)mustbeclearedin software. 0NoneoftheportBgeneralpurposeI/Opinshaschangedstate.

PIE1Register
ThePIE1registercontainstheperipheralinterruptenablebits.

Fig.211PIE1register

ADIEA/DConverterInterruptEnablebit.
1EnablestheADCinterrupt. 0DisablestheADCinterrupt.

RCIEEUSARTReceiveInterruptEnablebit.
1EnablestheEUSARTreceiveinterrupt. 0DisablestheEUSARTreceiveinterrupt.

TXIEEUSARTTransmitInterruptEnablebit.
1EnablestheEUSARTtransmitinterrupt. 0DisablestheEUSARTtransmitinterrupt.

SSPIEMasterSynchronousSerialPort(MSSP)InterruptEnablebitenablesaninterruptrequesttobe generatedaftereachdatatransferviasynchronousserialcommunicationmodule(SPIorI2Cmode).
1EnablestheMSSPinterrupt. 0DisablestheMSSPinterrupt.

CCP1IECCP1InterruptEnablebitenablesaninterruptrequesttobegeneratedinCCP1moduleusedforPWM signalprocessing.
1EnablestheCCP1interrupt. 0DisablestheCCP1interrupt.

TMR2IETMR2toPR2MatchInterruptEnablebit
1EnablestheTMR2toPR2matchinterrupt. 0DisablestheTMR2toPR2matchinterrupt.

TMR1IETMR1OverflowInterruptEnablebitenablesaninterruptrequesttobegeneratedaftereachtimerTMR1 registeroverflow,i.e.whenthecountingstartsfromzero.
1EnablestheTMR1overflowinterrupt. 0DisablestheTMR1overflowinterrupt.

PIE2Register
ThePIE2Registeralsocontainsthevariousinterruptenablebits.

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

4/8

19/05/13

Chapter 2: Core SFRs - Book: PIC Microcontrollers

Fig.212PIE2Register

OSFIEOscillatorFailInterruptEnablebit.
1Enablesoscillatorfailinterrupt. 0Disablesoscillatorfailinterrupt.

C2IEComparatorC2InterruptEnablebit.
1EnablesComparatorC2interrupt. 0DisablesComparatorC2interrupt.

C1IEComparatorC1InterruptEnablebit.
1EnablesComparatorC1interrupt. 0DisablesComparatorC1interrupt.

EEIEEEPROMWriteOperationInterruptEnablebit.
1EnablesEEPROMwriteoperationinterrupt. 0DisablesEEPROMwriteoperationinterrupt.

BCLIEBusCollisionInterruptEnablebit.
1Enablesbuscollisioninterrupt. 0Disablesbuscollisioninterrupt.

ULPWUIEUltraLowPowerWakeupInterruptEnablebit.
1EnablesUltraLowPowerWakeupinterrupt. 0DisablesUltraLowPowerWakeupinterrupt.

CCP2IECCP2InterruptEnablebit.
1EnablesCCP2interrupt. 0DisablesCCP2interrupt.

PIR1Register
ThePIR1registercontainstheinterruptflagbits.

Fig.213PIR1Register

ADIFA/DConverterInterruptFlagbit.
1A/Dconversioniscompleted(bitmustbeclearedinsoftware). 0A/Dconversionisnotcompletedorhasnotstarted.

RCIFEUSARTReceiveInterruptFlagbit.
1TheEUSARTreceivebufferisfull.BitisclearedbyreadingtheRCREGregister. 0TheEUSARTreceivebufferisnotfull.

TXIFEUSARTTransmitInterruptFlagbit.
1TheEUSARTtransmitbufferisempty.BitisclearedbywritingtotheTXREGregister. 0TheEUSARTtransmitbufferisfull.

SSPIFMasterSynchronousSerialPort(MSSP)InterruptFlagbit.
1TheMSSPinterruptconditionduringdatatransmit/receivehasoccurred.TheseconditionsdifferdependingonMSSPoperatingmode (SPIorI2C)Thisbitmustbeclearedinsoftwarebeforereturningfromtheinterruptserviceroutine. 0NoMSSPinterruptconditionhasoccurred.

CCP1IFCCP1InterruptFlagbit.
1CCP1interruptconditionhasoccurred(CCP1isunitforcapturing,comparingandgeneratingPWMsignal).Dependingonoperating mode,captureorcomparematchhasoccurred.Inbothcases,bitmustbeclearedinsoftware.ThisbitisnotusedinPWMmode. 0NoCCP1interruptconditionhasoccurred.

TMR2IFTimer2toPR2InterruptFlagbit
1TMR2(8bitregister)toPR2matchhasoccurred.Thisbitmustbeclearedinsoftwarebeforereturningfromtheinterruptservice routine. 0NoTMR2toPR2matchhasoccurred.

TMR1IFTimer1OverflowInterruptFlagbit
1TheTMR1registerhasoverflowed.Thisbitmustbeclearedinsoftware. 0TheTMR1registerhasnotoverflowed.

PIR2Register
ThePIR2registercontainstheinterruptflagbits.

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

5/8

19/05/13

Chapter 2: Core SFRs - Book: PIC Microcontrollers

Fig.214PIR2register

OSFIFOscillatorFailInterruptFlagbit.
1SystemoscillatorfailedandclockinputhaschangedtointernaloscillatorINTOSC.Thisbitmustbeclearedinsoftware. 0Systemoscillatoroperatesnormally.

C2IFComparatorC2InterruptFlagbit.
1ComparatorC2outputhaschanged(bitC2OUT).Thisbitmustbeclearedinsoftware. 0ComparatorC2outputhasnotchanged.

C1IFComparatorC1InterruptFlagbit.
1ComparatorC1outputhaschanged(bitC1OUT).Thisbitmustbeclearedinsoftware. 0ComparatorC1outputhasnotchanged.

EEIFEEWriteOperationInterruptFlagbit.
1EEPROMwritecompleted.Thisbitmustbeclearedinsoftware. 0EEPROMwriteisnotcompletedorhasnotstarted.

BCLIFBusCollisionInterruptFlagbit.
1AbuscollisionhasoccurredintheMSSPwhenconfiguredforI2CMastermode.Thisbitmustbeclearedinsoftware. 0Nobuscollisionhasoccurred.

ULPWUIFUltraLowpowerWakeupInterruptFlagbit.
1Wakeupconditionhasoccurred.Thisbitmustbeclearedinsoftware. 0NoWakeupconditionhasoccurred.

CCP2IFCCP2InterruptFlagbit.
1CCP2interruptconditionhasoccurred(unitforcapturing,comparingandgeneratingPWMsignal).Dependingonoperatingmode, captureorcomparematchhasoccurred.Inbothcases,thebitmustbeclearedinsoftware.ThisbitisnotusedinPWMmode. 0NoCCP2interruptconditionhasoccurred.

PCONregister
ThePCONregistercontainsonlytwoflagbitsusedtodifferentiatebetweena:poweronreset,brownoutreset,WatchdogTimerResetand externalreset(throughMCLRpin).

Fig.215PCONregister

ULPWUEUltraLowPowerWakeupEnablebit
1UltraLowPowerWakeupenabled. 0UltraLowPowerWakeupdisabled.

SBORENSoftwareBOREnablebit
1BrownoutResetenabled. 0BrownoutResetdisabled.

PORPoweronResetStatusbit
1NoPoweronresethasoccurred. 0Poweronresethasoccurred.ThisbitmustbesetinsoftwareafteraPoweronResetoccurs.

BORBrownoutResetStatusbit
1NoBrownoutresethasoccurred. 0Brownoutresethasoccurred.ThisbitmustbesetinsoftwareafteraBrownoutResetoccurs.

PCLandPCLATHRegisters
ThesizeoftheprogrammemoryofthePIC16F887is8K.Therefore,ithas8192locationsforprogramstoring.Forthisreasontheprogram countermustbe13bitswide(2^13=8192).Inorderthatthecontentsofsomelocationmaybechangedinsoftwareduringoperation,its addressmustbeaccessiblethroughsomeSFR.SinceallSFRsare8bitswide,thisregisterisartificiallycreatedbydividingits13bitsinto twoindependentregisters:PCLATHandPCL. Iftheprogramexecutiondoesnotaffecttheprogramcounter,thevalueofthisregisterisautomaticallyandconstantlyincremented+1,+1, +1,+1...Inthatway,theprogramisexecutedjustasitiswritteninstructionbyinstruction,followedbyaconstantaddressincrement.

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

6/8

19/05/13

Chapter 2: Core SFRs - Book: PIC Microcontrollers

Fig.216PCLandPCLATHRegisters

Iftheprogramcounterischangedinsoftware,thenthereareseveralthingsthatshouldbekeptinmindinordertoavoidproblems:

Eightlowerbits(thelowbyte)comefromthePCLregisterwhichisreadableandwritable,whereasfiveupperbits comingfromthePCLATHregisterarewritableonly. ThePCLATHregisterisclearedonanyreset. Inassemblylanguage,thevalueoftheprogramcounterismarkedwithPCL,butitobviouslyrefersto8lowerbits only.OneshouldtakecarewhenusingtheA D D W F P C L instruction.Thisisajumpinstructionwhichspecifiesthe targetlocationbyaddingsomenumbertothecurrentaddress.Itisoftenusedwhenjumpingintoalookuptableor programbranchtabletoreadthem.Aproblemarisesifthecurrentaddressissuchthatadditioncauseschangeon somebitbelongingtothehigherbyteofthePCLATHregister.Doyouseewhatisgoingon? ExecutinganyinstructionuponthePCLregistersimultaneouslycausestheProgramCounterbitstobereplacedby thecontentsofthePCLATHregister.However,thePCLregisterhasaccesstoonly8lowerbitsoftheinstruction resultandthefollowingjumpwillbecompletelyincorrect.Theproblemissolvedbysettingsuchinstructionsat addressesendingbyxx00h.Thisenablestheprogramtojumpupto255locations.Iflongerjumpsareexecutedby thisinstruction,thePCLATHregistermustbeincrementedby1foreachPCLregisteroverflow. Onsubroutinecallorjumpexecution(instructionsC A L L andG O T O ),themicrocontrollerisabletoprovideonly11bit addressing.Forthisreason,similartoRAMwhichisdividedinbanks,ROMisdividedinfourpagesinsizeof2K each.Suchinstructionsareexecutedwithinthesepageswithoutanyproblems.Simply,sincetheprocessoris providedwith11bitaddressfromtheprogram,itisabletoaddressanylocationwithin2KB.Figure217below illustratesthissituationasajumptothesubroutinePP1address. However,ifasubroutineorjumpaddressarenotwithinthesamepageasthelocationfromwherethejumpis,two missinghigherbitsshouldbeprovidedbywritingtothePCLATHregister.Itisillustratedinfigure217belowasa jumptothesubroutinePP2address.

Fig.217PCLATHRegisters

Inbothcases,whenthesubroutinereachesinstructionsR E T U R N ,R E T L W orR E T F I E (toreturntothemainprogram),themicrocontrollerwill simplycontinueprogramexecutionfromwhereitleftoffbecausethereturnaddressispushedandsavedontothestackwhich,as mentioned,consistsof13bitregisters.

Indirectaddressing
Inadditiontodirectaddressingwhichislogicalandclearbyitself(itissufficienttospecifyaddressofsomeregistertoreaditscontents),this microcontrollerisabletoperformindirectaddressingbymeansoftheINDFandFSRregisters.Itsometimesconsiderablysimplifies programwriting.ThewholeprocedureisenabledbecausetheINDFregisterisnottrueone(physicallydoesnotexist),butonlyspecifiesthe registerwhoseaddressislocatedintheFSRregister.Becauseofthis,writeorreadfromtheINDFregisteractuallymeanswriteorreadfrom theregisterwhoseaddressislocatedintheFSRregister.Inotherwords,registersaddressesarespecifiedintheFSRregister,andtheir contentsarestoredintheINDFregister.Thedifferencebetweendirectandindirectaddressingisillustratedinthefigure218below: Asseen,theproblemwiththemissingaddressingbitsissolvedbyborrowingfromanotherregister.Thistime,itistheseventhbitcalled IRPfromtheSTATUSregister.

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

7/8

19/05/13

Chapter 2: Core SFRs - Book: PIC Microcontrollers

Fig.218DirectandIndirectaddressing

previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/3/chapter-2-core-sfrs/

8/8

19/05/13
Products

Chapter 4: Timers - Book: PIC Microcontrollers


Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter4:Timers
ThetimersofthePIC16F887microcontrollercanbebrieflydescribedinonlyonesentence.Therearethreecompletelyindependent timers/countersmarkedasTMR0,TMR1andTMR2.Butitsnotassimpleasthat.

TimerTMR0
ThetimerTMR0hasawiderangeofapplicationsinpractice.Veryfewprogramsdon'tuseitinsomeway.Itisveryconvenientandeasyto useforwritingprogramsorsubroutinesforgeneratingpulsesofarbitraryduration,timemeasurementorcountingexternalpulses(events) withalmostnolimitations. ThetimerTMR0moduleisan8bittimer/counterwiththefollowingfeatures:

8bittimer/counter 8bitprescaler(sharedwithWatchdogtimer) Programmableinternalorexternalclocksource Interruptonoverflowand Programmableexternalclockedgeselection.


Figure41belowrepresentsthetimerTMR0schematicwithallbitswhichdetermineitsoperation.Thesebitsarestoredinthe OPTION_REGRegister.

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoonesingle chipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhatyou wantthemtodo.Youjusthavetowritea programanddumpitintothe microcontroller.[moreinfo]

Fig.41TimerTMR0

OPTION_REGRegister

Fig.42OPTION_REGRegister

RBPUPORTBPullupenablebit
1PORTBpullupresistorsaredisabledand 0PORTBpinscanbeconnectedtopullupresistors.

INTEDGInterruptEdgeSelectbit
1InterruptonrisingedgeofINTpin(01)and 0InterruptonfallingedgeofINTpin(10).

www.mikroe.com/chapters/view/5/chapter-4-timers/

1/8

19/05/13
T0CSTMR0ClockSelectbit

Chapter 4: Timers - Book: PIC Microcontrollers

1PulsesarebroughttoTMR0timer/counterinputthroughtheRA4pinand 0Internalcycleclock(Fosc/4).

T0SETMR0SourceEdgeSelectbit
1IncrementonhightolowtransitiononTMR0pinand 0IncrementonlowtohightransitiononTMR0pin.

PSAPrescalerAssignmentbit
1PrescalerisassignedtotheWDTand 0PrescalerisassignedtotheTMR0timer/counter.

PS2,PS1,PS0PrescalerRateSelectbit
Prescalerrateisadjustedbycombiningthesebits Asseeninthetable41,thesamecombinationofbitsgivesdifferentprescalerratefor thetimer/counterandwatchdogtimerrespectively.

PS2
0 0 0 0 1 1 1 1

PS1
0 0 1 1 0 0 1 1

PS0
0 1 0 1 0 1 0 1

TMR0
1:2 1:4 1:8 1:16 1:32 1:64 1:128 1:256

WDT
1:1 1:2 1:4 1:8 1:16 1:32 1:64 1:128

Table41PrescalerRate

ThefunctionofthePSAbitisshowninthetwofiguresbelow:

Fig.43ThefunctionofthePSAbit0

Fig.44ThefunctionofthePSAbit1

www.mikroe.com/chapters/view/5/chapter-4-timers/

2/8

19/05/13

Chapter 4: Timers - Book: PIC Microcontrollers

Asseen,thelogicstateofthePSAbitdetermineswhethertheprescaleristobeassignedtothetimer/counterorwatchdogtimer. Additionallyitisalsoworthmentioning:

Whentheprescalerisassignedtothetimer/counter,anywritetotheTMR0registerwillcleartheprescaler Whentheprescalerisassignedtowatchdogtimer,aCLRWDTinstructionwillclearboththeprescalerandWDT WritingtotheTMR0registerusedasatimer,willnotcausethepulsecountingtostartimmediately,butwithtwo instructioncyclesdelay.Accordingly,itisnecessarytoadjustthevaluewrittentotheTMR0register Whenthemicrocontrollerissetupinsleepmode,theoscillatoristurnedoff.Overflowcannotoccursincethereareno pulsestocount.ThisiswhytheTMR0overflowinterruptcannotwakeuptheprocessorfromSleepmode Whenusedasanexternalclockcounterwithoutprescaler,aminimalpulselengthorapausebetweentwopulses mustbe2Tosc+20nS.Toscistheoscillatorsignalperiod Whenusedasanexternalclockcounterwithprescaler,aminimalpulselengthorapausebetweentwopulsesis 10nS The8bitprescalerregisterisnotavailabletotheuser,whichmeansthatitcannotbedirectlyreadorwrittento WhenchangingtheprescalerassignmentfromTMR0tothewatchdogtimer,thefollowinginstructionsequencemust beexecutedinordertoavoidreset:

B A N K S E L T M R 0 C L R W D T C L E A R W D T C L R F T M R 0 C L E A R T M R 0 A N D P R E S C A L E R B A N K S E L O P T I O N _ R E G B S F O P T I O N _ R E G , P S A P R E S C A L E R I S A S S I G N E D T O T H E W D T C L R W D T C L E A R W D T M O V L W b 1 1 1 1 1 0 0 0 S E L E C T B I T S P S 2 , P S 1 , P S 0 A N D C L E A R A N D W F O P T I O N _ R E G , W T H E M B Y I N S T R U C T I O N L O G I C A L A N D I O R L W b 0 0 0 0 0 1 0 1 B I T S P S 2 , P S 1 , A N D P S 0 S E T M O V W F O P T I O N _ R E G P R E S C A L E R R A T E T O 1 : 3 2

Likewise,whenchangingtheprescalerassignmentfromtheWDTtotheTMR0,thefollowinginstructionsequence mustbeexecuted:

B A N K S E L T M R 0 C L R W D T C L E A R W D T A N D P R E S C A L E R B A N K S E L O P T I O N _ R E G M O V L W b 1 1 1 1 0 0 0 0 S E L E C T O N L Y B I T S P S A , P S 2 , P S 1 , P S 0 A N D W F O P T I O N _ R E G , W C L E A R T H E M A F T E R W A R D S B Y I N S T R U C T I O N L O G I C A L A N D I O R L W b 0 0 0 0 0 0 1 1 P R E S C A L E R R A T E I S 1 : 1 6 M O V W F O P T I O N _ R E G

InordertouseTMR0properly,itisnecessary: Toselectmode:

TimermodeisselectedbytheT0CSbitoftheOPTION_REGregister,(T0CS:0=timer,1=counter) Whenused,theprescalershouldbeassignedtothetimer/counterbyclearingthePSAbitoftheOPTION_REG register.TheprescalerrateissetbyusingthePS2PS0bitsofthesameregisterand Whenusinginterrupt,theGIEandTMR0IEbitsoftheINTCONregistershouldbeset.


Tomeasuretime:

ResettheTMR0registerorwritesomewellknownvaluetoit Elapsedtime(inmicrosecondswhenusingquartz4MHz)ismeasuredbyreadingtheTMR0registerand TheflagbitTMR0IFoftheINTCONregisterisautomaticallyseteverytimetheTMR0registeroverflows.Ifenabled, aninterruptoccurs.


Tocountpulses:

ThepolarityofpulsesaretobecountedisselectedontheRA4pinareselectedbytheTOSEbitoftheOPTION register(T0SE:0=positive,1=negativepulses)and NumberofpulsesmaybereadfromtheTMR0register.Theprescalerandinterruptareusedinthesamemannerasin timermode.

TimerTMR1
TimerTMR1moduleisa16bittimer/counter,whichmeansthatitconsistsoftworegisters(TMR1LandTMR1H).Itcancountup65.535 pulsesinasinglecycle,i.e.beforethecountingstartsfromzero.

Fig.45TimerTMR1

www.mikroe.com/chapters/view/5/chapter-4-timers/

3/8

19/05/13

Chapter 4: Timers - Book: PIC Microcontrollers

SimilartothetimerTMR0,theseregisterscanbereadorwrittentoatanymoment.Incaseanoverflowoccurs,aninterruptisgenerated. ThetimerTMR1modulemayoperateinoneoftwobasicmodesasatimeroracounter.However,unlikethetimerTMR0,eachofthese moduleshasadditionalfunctions. PartsoftheT1CONregisterareincontroloftheoperationofthetimerTMR1.

Fig.46TimerTMR1Overview

TimerTMR1Prescaler
TimerTMR1hasacompletelyseparateprescalerwhichallows1,2,4or8divisionsoftheclockinput.Theprescalerisnotdirectlyreadable orwritable.However,theprescalercounterisautomaticallycleareduponwritetotheTMR1HorTMR1Lregister.

TimerTMR1Oscillator
RC0/T1OSOandRC1/T1OSIpinsareusedtoregisterpulsescomingfromperipheralelectronics,buttheyalsohaveanadditionalfunction. Asseeninfigure47,theyaresimultaneouslyconfiguredasbothinput(pinRC1)andoutput(pinRC0)oftheadditionalLPquartzoscillator (lowpower). Thisadditionalcircuitisprimarilydesignedforoperatingatlowfrequencies(upto200KHz),moreprecisely,forusingthe32,768KHz quartzcrystal.Suchcrystalsareusedinquartzwatchesbecauseitiseasytoobtainonesecondlongpulsesbysimplydividingthis frequency. Sincethisoscillatordoesnotdependoninternalclocking,itcanoperateeveninsleepmode.ItisenabledbysettingtheT1OSCENcontrol bitoftheT1CONregister.Theusermustprovideasoftwaretimedelay(afewmilliseconds)toensureproperoscillatorstartup. Tablebelowshowstherecommendedvaluesofcapacitorstosuitthequartzoscillator.Thesevaluesdo nothavetobeexact.However,thegeneralruleis:thehigherthecapacitor'scapacitythehigherthe stability,which,atthesametime,prolongsthetimeneededfortheoscillatorstability.
O SCIL L AT O R F REQ UENCY
32 kHz LP 100 kHz 200 kHz

C1
33 pF 15 pF 15 pF

C2
33 pF 15 pF 15 pF

Fig.47TimerTMR1Oscillator

TimerTMR1Gate
Timer1gatesourceissoftwareconfigurabletobetheT1GpinortheoutputofcomparatorC2.Thisgateallowsthetimertodirectlytime externaleventsusingthelogicstateontheT1GpinoranalogeventsusingthecomparatorC2output.Refertofigure47above.Inorderto timeasignalsdurationitissufficienttoenablesuchgateandcountpulseshavingpassedthroughit.

TMR1intimermode
Inordertoselectthismode,itisnecessarytocleartheTMR1CSbit.Afterthis,the16bitregisterwillbeincrementedoneverypulsecoming fromtheinternaloscillator.Ifthe4MHzquartzcrystalisinuse,itwillbeincrementedeverymicrosecond. Inthismode,theT1SYNCbitdoesnotaffectthetimerbecauseitcountsinternalclockpulses.Sincethewholeelectronicsusesthese pulses,thereisnoneedforsynchronization.

www.mikroe.com/chapters/view/5/chapter-4-timers/

4/8

19/05/13

Chapter 4: Timers - Book: PIC Microcontrollers

Fig.48TMR1intimermode

Themicrocontrollersclockoscillatordoesnotrunduringsleepmodesothetimerregisteroverflowcannotcauseanyinterrupt.

TimerTMR1Oscillator
ThepowerconsumptionofthemicrocontrollerisreducedtothelowestlevelinSleepmode.Thepointistostoptheoscillator.Anyway,itis easytosetthetimerinthismodebywritingaSLEEPinstructiontotheprogram.Aproblemoccurswhenitisnecessarytowakeupthe microcontrollerbecauseonlyaninterruptcandothat.Sincethemicrocontrollersleeps,aninterruptmustbetriggeredbyexternal electronics.Itcanallgetincrediblycomplicatedifitisnecessarythewakeupoccursatregulartimeintervals...

Fig.49TimerTMR1Oscillator

Inordertosolvethisproblem,acompletelyindependentLowPowerquartzoscillator,abletooperateinsleepmode,isbuiltintothe PIC16F887microcontroller.Simply,whatpreviouslyhasbeenaseparatecircuit,itisnowbuiltintothemicrocontrollerandassignedtothe timerTMR1.TheoscillatorisenabledbysettingtheT1OSCENbitoftheT1CONregister.Afterthat,theTMR1CSbitofthesameregister thenisusedtodeterminethatthetimerTMR1usespulsesequencesfromthatoscillator.

ThesignalfromthisquartzoscillatorissynchronizedwiththemicrocontrollerclockbyclearingtheT1SYNCbit.In thatcase,thetimercannotoperateinsleepmode.Youwonderwhy?Becausethecircuitforsynchronizationusesthe clockofmicrocontroller!and TheTMR1registeroverflowinterruptmaybeenabled.Suchinterruptswilloccurinsleepmodeaswell.


TMR1incountermode
TimerTMR1startstooperateasacounterbysettingtheTMR1CSbit.ItmeansthatthetimerTMR1isincrementedontherisingedgeofthe externalclockinputT1CKI.IfcontrolbitT1SYNCoftheT1CONregisteriscleared,theexternalclockinputswillbesynchronizedontheir waytotheTMR1register.Inotherwords,thetimerTMR1issynchronizedtothemicrocontrollersystemclockandcalledasynchronous counter. Whenthemicrocontroller,operatinginthisway,issetinsleepmode,theTMR1HandTMR1Ltimerregistersarenotincrementedeven thoughclockpulsesappearontheinputpins.Simply,sincethemicrocontrollersystemclockdoesnotruninthismode,therearenoclock inputstouseforsynchronization.However,theprescalerwillcontinuetorunifthereareclockpulsesonthepinssinceitisjustasimple frequencydivider.

www.mikroe.com/chapters/view/5/chapter-4-timers/

5/8

19/05/13

Chapter 4: Timers - Book: PIC Microcontrollers

Fig.411CounterMode

Thiscounterregistersalogicone(1)oninputpins.Itisimportantto understandthatatleastonefallingedgemustberegisteredpriortothe firstincrementonrisingedge.Refertofigureontheleft.Thearrowsin figure411denotecounterincrements.

T1CONRegister

Fig.412T1CONRegister

T1GINVTimer1GateInvertbitactsaslogicstateinverterontheT1GpingateorthecomparatorC2output(C2OUT)gate.Itenablesthe timertomeasuretimewhilstthegateishighorlow.

1Timer1countswhenthepinT1GorbitC2OUTgateishigh(1)and 0Timer1countswhenthepinT1GorbitC2OUTgateislow(0).
TMR1GETimer1GateEnablebitdetermineswhetherthepinT1GorcomparatorC2output(C2OUT)gatewillbeactiveornot.Thisbitis functionalonlyintheeventthatthetimerTMR1ison(bitTMR1ON=1).Otherwise,thisbitisignored.

1TimerTMR1isononlyiftimer1gateisnotactiveand 0GatedoesnotaffectthetimerTMR1.
T1CKPS1,T1CKPS0Timer1InputClockPrescaleSelectbitsdeterminetherateoftheprescalerassignedtothetimerTMR1.
T 1CKPS1
0 0 1 1

T 1CKPS0
0 1 0 1

PRESCAL ERRAT E
1:1 1:2 1:4 1:8

Table42PrescalerRate

T1OSCENLPOscillatorEnableControlbit

1LPoscillatorisenabledfortimerTMR1clock(oscillatorwithlowpowerconsumptionandfrequency32.768kHz) and 0LPoscillatorisoff.


T1SYNCTimer1ExternalClockInputSynchronizationControlbitenablessynchronizationoftheLPoscillatorinputorT1CKIpininputwith themicrocontrollerinternalclock.Whencountingpulsesfromthelocalclocksource(bitTMR1CS=0),thisbitisignored.

1Donotsynchronizeexternalclockinputand 0Synchronizeexternalclockinput.
TMR1CSTimerTMR1ClockSourceSelectbit

1CountspulsesontheT1CKIpin(ontherisingedge01)and 0Countspulsesoftheinternalclockofmicrocontroller.
TMR1ONTimer1Onbit

1EnablesTimerTMR1and

www.mikroe.com/chapters/view/5/chapter-4-timers/

6/8

19/05/13
0StopsTimerTMR1.

Chapter 4: Timers - Book: PIC Microcontrollers

InordertousethetimerTMR1properly,itisnecessarytoperformthefollowing:

Sinceitisnotpossibletoturnofftheprescaler,itsrateshouldbeadjustedbyusingbitsT1CKPS1andT1CKPS0of theregisterT1CON(Refertotable42) ThemodeshouldbeselectedbytheTMR1CSbitofthesameregister(TMR1CS:0=theclocksourceisquartz oscillator,1=theclocksourceissuppliedexternally) BysettingtheT1OSCENbitofthesameregister,thetimerTMR1isturnedonandtheTMR1HandTMR1Lregisters areincrementedoneveryclockinput.Countingstopsbyclearingthisbit Theprescalerisclearedbyclearingorwritingthecounterregistersand Byfillingbothtimerregisters,theflagTMR1IFissetandcountingstartsfromzero.

TimerTMR2
TimerTMR2moduleisan8bittimerwhichoperatesinaveryspecificway.

Fig.413TimerTMR2

ThepulsesfromthequartzoscillatorfirstpassthroughtheprescalerwhoseratemaybechangedbycombiningtheT2CKPS1and T2CKPS0bits.TheoutputoftheprescaleristhenusedtoincrementtheTMR2registerstartingfrom00h.ThevaluesofTMR2andPR2are constantlycomparedandtheTMR2registerkeepsonbeingincrementeduntilitmatchesthevalueinPR2.Whenamatchoccurs,theTMR2 registerisautomaticallyclearedto00h.ThetimerTMR2Postscalerisincrementedanditsoutputisusedtogenerateaninterruptifitis enabled. TheTMR2andPR2registersarebothfullyreadableandwritable.CountingmaybestoppedbyclearingtheTMR2ONbit,whichcontributes topowersaving. Asaspecialoption,themomentofTMR2resetmaybealsousedtodeterminesynchronousserialcommunicationbaudrate. ThetimerTMR2iscontrolledbyseveralbitsoftheT2CONregister.

T2CONRegister

Fig.414T2CONRegister

TOUTPS3TOUTPS0Timer2OutputPostcalerSelectbitsareusedtodeterminethepostscalerrateaccordingtothefollowingtable:
T O UT PS3
0 0 0 0 0 0 0 0

T O UT PS2
0 0 0 0 1 1 1 1

T O UT PS1
0 0 1 1 0 0 1 1

T O UT PS0
0 1 0 1 0 1 0 1

PO ST SCAL ERRAT E
1:1 1:2 1:3 1:4 1:5 1:6 1:7 1:8

www.mikroe.com/chapters/view/5/chapter-4-timers/

7/8

19/05/13
1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1

Chapter 4: Timers - Book: PIC Microcontrollers


0 1 0 1 0 1 0 1 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16

Table43PostscalerRate

TMR2ONTimer2OnbitturnsthetimerTMR2on.

1TimerT2isonand 0TimerT2isoff.
T2CKPS1,T2CKPS0Timer2ClockPrescalebitsdetermineprescalerrate:
T 2CKPS1
0 0 1

T 2CKPS0
0 1 x

PRESCAL ERRAT E
1:1 1:4 1:16

Table44PrescalerRate

WhenusingtheTMR2timer,oneshouldknowseveralspecificdetailsthathavetodowithitsregisters:

Uponpoweron,thePR2registercontainsthevalueFFh BothprescalerandpostscalerareclearedbywritingtotheTMR2register BothprescalerandpostscalerareclearedbywritingtotheT2CONregisterand Onanyreset,bothprescalerandpostscalerarecleared.


previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/5/chapter-4-timers/

8/8

19/05/13
Products

Chapter 5: CCP Modules - Book: PIC Microcontrollers


Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter5:CCPModules
TheabbreviationCCPstandsforCapture/Compare/PWM. TheCCPmoduleisaperipheralwhichallowstheusertotimeandcontroldifferentevents. CaptureMode,allowstimingforthedurationofanevent.Thiscircuitgivesinsightintothecurrentstateofaregisterwhichconstantly changesitsvalue.Inthiscase,itisthetimerTMR1register. CompareModecomparesvaluescontainedintworegistersatsomepoint.OneofthemisthetimerTMR1register.Thiscircuitalsoallows theusertotriggeranexternaleventwhenapredeterminedamountoftimehasexpired. PWMPulseWidthModulationcangeneratesignalsofvaryingfrequencyanddutycycle. ThePIC16F887microcontrollerhastwosuchmodulesCCP1andCCP2. Bothofthemareidenticalinnormalmode,withtheexceptionoftheEnhancedPWMfeaturesavailableonCCP1only.Thisiswhythis chapterdescribestheCCP1moduleindetail.ConcerningCCP2,onlythefeaturesdistinguishingitfromCCP1willbecovered. Complicated?Allthisisonlyasimplifiedexplanationontheiroperation.Everythingismuchmorecomplicatedinpracticebecausethese modulescanoperateinmanydifferentmodes.Trytoanalyzetheiroperationonthebasisofthetablesdescribingbitfunctions.Ifyouuse anyCCPmodule,firstselectthemodeyouneed,analyzetheappropriatefigureandthenstartchangingbitsoftheregistersorelse...
EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

CCP1Module
Acentralpartofthiscircuitisa16bitregisterCCPR1,whichconsistsoftheCCPR1LandCCPR1Hregisters.Itisusedforcapturingor comparingwithbinarynumberstoredinthetimerregisterTMR1(TMR1HandTMR1L).

Fig.51CCP1Module

InComparemode,ifenabledbysoftware,thetimerTMR1resetmayoccuronmatch.Besides,theCCP1modulecangeneratePWM signalsofvaryingfrequencyanddutycycle. BitsoftheCCP1CONregistercontrolstheCCP1module.

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoonesingle chipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhatyou wantthemtodo.Youjusthavetowritea programanddumpitintothe microcontroller.[moreinfo]

CCP1inCapturemode
Inthismode,thetimerregisterTMR1(consistingofTMR1HandTMR1L)iscopiedtotheCCP1register(consistingofCCPR1Hand CCPR1L)inthefollowingsituations:

Everyfallingedge(10)ontheRC2/CCP1pin Everyrisingedge(01)ontheRC2/CCP1pin Every4thrisingedge(01)ontheRC2/CCP1pinand Every16thrisingedge(01)ontheRC2/CCP1pin.


Thecombinationofthefourbits(CCP1M3CCP1M0)ofthecontrolregisterdetermineswhichoftheseeventswilltrigger16bitdata transfer.Inaddition,thefollowingconditionsmustbemet:

RC2/CCP1pinmustbeconfiguredasinputand TMR1modulemustoperateastimerorsynchronouscounter.

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

1/11

19/05/13

Chapter 5: CCP Modules - Book: PIC Microcontrollers

Fig.52CCP1inCapturemode

TheflagbitCCP1IFissetwhenacaptureismade.IfithappensandiftheCCP1IEbitofthePIEregisterisset,thenaninterruptoccurs. WhentheCapturemodeischanged,anundesirablecaptureinterruptsmaybegenerated.Inordertoavoidthat,bothabitenablingCCP1IE interruptandflagbitCCP1IFshouldbeclearedpriortoanychangeoccuringinthecontrolregister. Undesirableinterruptmaybealsogeneratedbyswitchingfromonecaptureprescalertoanother.Toavoidthis,theCCP1moduleshouldbe temporarilyswitchedoffbeforechangingtheprescaler. Thefollowingprogramsequenceisrecommended:

B A N K E S E L C C P 1 C O N C L R F C C P 1 C O N C O N T R O L R E G I S T E R I S C L E A R E D C C P 1 M O D U L E I S O F F M O V L W X X N E W P R E S C A L E R M O D E I S S E L E C T E D M O V W F C C P 1 C O N N E W V A L U E I S L O A D E D T O T H E C O N T R O L R E G I S T E R C C P 1 M O D U L E I S S I M U L T A N E O U S L Y S W I T C H E D O N

CCP1inComparemode
Inthismode,thevalueintheCCP1registerisconstantlycomparedtothevalueinthetimerregisterTMR1.Whenamatchoccurs,theoutput pinRC2/CCP1logicstatemaybechanged,whichdependsonthestateofbitsinthecontrolregister(CCP1M3CCP1M0).Theflagbit CCP1IFwillbesimultaneouslyset.

Fig.53CCP1inComparemode

TosetupCCP1moduletooperateinthismode,twoconditionsmustbemet:

PinRC2/CCP1mustbeconfiguredasoutputand TimerTMR1mustbesynchronizedwithinternalclock.
CCP1inPWMmode
Signalsofvaryingfrequencyanddutycyclehaveawideapplicationinautomation.Atypicalexampleisapowercontrolcircuitwhose simpleoperationisshowninfigure54below.Ifalogiczero(0)representsswitchoffandlogicone(1)representsswitchon,thepowerthat theloadconsumeswillbedirectlyproportionaltothepulseduration.ThisratioisoftencalledDutyCycle.

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

2/11

19/05/13

Chapter 5: CCP Modules - Book: PIC Microcontrollers

Fig.54CCP1inPWMmode

Anotherexample,commoninpractice,istheusageofPWMsignalsinthecircuitforgeneratingsignalsofarbitrarywaveforms,forexample, sinusoidalwaveform.Seefigure55below:

Fig.55CCP1inPWMmodewithfiltration

Deviceswhichoperateinthiswayareoftenusedinpracticeasswitchingregulatorswhichcontroltheoperationofmotors(speed, acceleration,decelerationetc.).

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

3/11

19/05/13

Chapter 5: CCP Modules - Book: PIC Microcontrollers

Fig.56PWMmodule

ThefigureaboveshowstheblockdiagramoftheCCP1modulesetupinPWMmode.Inordertogenerateapulseofarbitraryformonits outputpin,itisnecessarytodetermineonlytwovaluespulsefrequencyandduration.

Fig.57PWMMode

PWMPeriod
Theoutputpulseperiod(T)isspecifiedbythePR2registerofthetimerTMR2.ThePWMperiodcanbecalculatedusingthefollowing equation: PWMPeriod(T)=(PR2+1)*4Tosc*TMR2PrescaleValue IfthePWMPeriod(T)isknownthen,itiseasytodeterminethesignalfrequencyFbecausethesetwovaluesarerelatedbyequationF=1/T.

PWMDutyCycle
ThePWMdutycycleisspecifiedbyusingintotalof10bits:eightMSbsfoundintheCCPR1LregisterandtwoadditionalLSbsfoundinthe CCP1CONregister(DC1B1andDC1B0).Theresultis10bitnumbercontainedintheformula: PulseWidth=(CCPR1L,DC1B1,DC1B0)*Tosc*TMR2PrescaleValue ThefollowingtableshowshowtogeneratePWMsignalsofvaryingfrequencyifthemicrocontrolleruses20MHzquartzcrystal (Tosc=50nS).
F REQ UENCY[ KHZ ]
TMR2 Prescaler PR2 Register

1.22
16 FFh

4.88
4 FFh

19.53
1 FFh

78.12
1 3Fh

156.3
1 1Fh

208.3
1 17h

Table51PWMDutyCycle

Atlast,twonotes:

OutputpinwillbeconstantlysetincasethepulsewidthisbynegligencedeterminedtobelargerthanPWMperiod and Inthisapplication,thetimerTMR2PostscalercannotbeusedforgeneratinglongerPWMperiods.


PWMResolution
PWMsignalisnothingmorethanthepulsesequencewithvaryingdutycycle.Foronespecifiedfrequency(numberofpulsespersecond), thereisalimitednumberofdutycyclecombinations.Thisnumberiscalledresolutionmeasuredbybits.Forexample,a10bitresolutionwill resultin1024discretedutycycles,whereasan8bitresolutionwillresultin256discretedutycyclesetc.Inrelationtothismicrocontroller, theresolutionisspecifiedbythePR2register.ThemaximalvalueisobtainedbywritingnumberFFh.

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

4/11

19/05/13
PWMfrequenciesandresolutions(Fosc=20MHz):
PWMF REQ UENCY
Timer Prescale PR2 Value Maximum Resolution

Chapter 5: CCP Modules - Book: PIC Microcontrollers

1.22KHZ
16 FFh 10

4.88KHZ
4 FFh 10

19.53KHZ
1 FFh 10

78.12KHZ
1 3Fh 8

156.3KHZ
1 1Fh 7

208.3KHZ
1 17h 6

Table52PWMFrequenciesandResolutions

PWMfrequenciesandresolutions(Fosc=8MHz):
PWMF REQ UENCY
Timer Prescale PR2 Value Maximum Resolution

1.22KHZ
16 65h 8

4.90KHZ
4 65h 8

19.61KHZ
1 65h 8

76.92KHZ
1 19h 6

153.85KHZ
1 0Ch 5

200.0KHZ
1 09h 5

Table53PWMFrequenciesandResolutions

CCP1CONRegister

Fig.58CCP1CONRegister

P1M1,P1M0PWMOutputConfigurationbitsInallmodes,exceptingPWM,theP1ApinisCapture/Comparemoduleinput.P1B,P1Cand P1Dpinsactasinput/outputportDpins.InPWMmode,thesebitsaffecttheCCP1moduleasshowninthetable54below:
P1M1 P1M0 MO DE
PWM with single output 0 0 Pin P1A outputs modulated signal. Pins P1B, P1C and P1D are port D input/output Full Bridge - Forward configuration 0 1 Pin P1D outputs modulated signal Pin P1A is active Pins P1B and P1C are inactive Half Bridge configuration 1 0 Pins P1A and P1B output modulated signal PinsP1C and P1D are port D input/output Full Bridge - Reverse configuration 1 1 Pin P1B outputs modulated signal Pin P1C is active Pins P1A and P1D are inactive

Table54CCP1CONRegister

DC1B1,DC1B0PWMDutyCycleLeastSignificantbitsareonlyusedinPWMmodeinwhichtheyrepresenttwoleastsignificantbitsofa 10bitnumber.ThisnumberdeterminesPWMsignalsdutycycle.Therestofbits(8intotal)arestoredintheCCPR1Lregister. CCP1M3CCP1M0CCP1ModeSelectbitsdeterminethemodeoftheCCP1module.


CCP1M3
0 0 0 0 0

CCP1M2
0 0 0 0 1

CCP1M1
0 0 1 1 0

CCP1M0
0 1 0 1 0

MO DE
Module is disabled (reset) Unused Compare mode CCP1IF bit is set on match Unused Capture mode Every falling edge on the CCP1 pin Capture mode Every rising edge on the CCP1 pin

Capture mode Every 4th rising edge on the CCP1 pin

Capture mode Every 16th rising edge on the CCP1 pin Compare mode

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

5/11

19/05/13

Chapter 5: CCP Modules - Book: PIC Microcontrollers


Output and CCP1IF bit are set on match

Compare mode Output is cleared and CCP1IF bit is set on match Compare mode Interrupt request arrives and bit CCP1IF is set on match Compare mode Bit CCP1IF is set and timers 1 or 2 registers are cleared PWM mode

Pins P1A and P1C are active-high Pins P1B and P1D are active-high PWM mode

Pins P1A and P1C are active-high Pins P1B and P1D are active-low PWM mode

Pins P1A and P1C are active-low Pins P1B and P1D are active-high PWM mode

Pins P1A and P1C are active-low Pins P1B and P1D are active-low

Table55ModesofOperations

CCP2Module
Excludingthedifferentnamesofregistersandbits,thismoduleisaverygoodcopyoftheCCP1modulesetupinnormalmode(previously discussed).ThereisonlyonetruedifferencebetweentheirmodeswhenCCP2operatesinComparemode. ThatdifferencereferstothetimerT1resetsignal.Namely,ifA/DconverterisenabledatthemomentthevaluesoftheTMR1andCCPR2 registersmatch,thetimerT1resetsignalwillautomaticallystartA/Dconversion.

Fig.59CCP2Module

Similartotheperviousmodule,thiscircuitisundercontrolofthebitsofthecontrolregister.Thistime,itistheCCP2CONregister.

CCP2CONRegister

Fig.510CCP2CONRegister

DC2B1,DC2B0PWMDutyCycleLeastSignificantbitsareonlyusedinPWMmoderepresentingtwoleastsignificantbitsofa10bit number.ThisnumberdeterminesPWMsignalsdutycycle.Therestofbits(8intotal)arestoredintheCCPR2Lregister. CCP2M3CCP2M0CCP2ModeSelectbitsselectCCP2mode.


CCP2M3
0 0 0

CCP2M2
0 0 0

CCP2M1
0 0 1

CCP2M0
0 1 0

MO DE
Module is disabled (reset) Unused Unused

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

6/11

19/05/13
0 0 0 1 1 0 1 0

Chapter 5: CCP Modules - Book: PIC Microcontrollers


Unused Capture mode Every falling edge on the CCP2 pin Capture mode Every raising edge on the CCP2 pin Capture mode Every 4th rising edge on the CCP2 pin Capture mode Every 16th rising edge on the CCP2 pin Compare mode Output and CCP2IF bit are set on match Compare mode Output is cleared and CCP2IF bit is set on match Compare mode

Interrupt is generated, CCP2IF bit is set and CCP2 pin is unaffected on match Compare mode

CCP2IF bit is set, Timer 1 registers are cleared, A/D conversion is started if the A/D converter is on on match PWM mode

Table56CCP2CONRegister

Inshort:SetupCCP1moduleforPWMoperation
InordertosetuptheCCPmoduleforPWMoperation,thefollowingstepsshouldbetaken:

DisabletheCCP1outputpin.Itshouldbeconfiguredasinput SetthePWMperiodbyloadingthePR2register ConfiguretheCCPmoduleforthePWMmodebycombiningbitsoftheCCP1CONregister SetthePWMsignalsdutycyclebyloadingtheCCPR1LregisterandusingbitsDC1B1andDC1B0ofthe CCP1CONregister ConfigureandstarttimerTMR2:


CleartheTMR2IFinterruptflagbitofthePIR1register SetthetimerTMR2prescalevaluebyloadingbitsT2CKPS1andT2CKPS0oftheT2CONregister StartthetimerTMR2bysettingtheTMR2ONbitoftheT2CONregister

EnablePWMoutputpinsafteronePWMcyclehasbeenfinished:
WaitforthetimerTMR2overflow(TMR2IFbitofthePIR1registerisset)and ConfiguretheappropriatepinasoutputbyclearingbitoftheTRISregister.

CCP1inEnhancedMode
TheenhancedmodeisavailableonCCP1only.Basically,thismoduledoesnotdifferfromtheonepreviouslydescribedandenhancement referstotransmissionofPWMsignaltotheoutputpins.Whyisitsoimportant?Becausethemicrocontrollersaremorefrequentlyusedin controlsystemsforelectricmotors.Thesedevicesarenotdescribedhere,butifyoueverhavehadachancetoworkondevelopmentof similardevices,youwillrecognizeelementswhich,untilquiterecently,havebeenusedasexternalones.Normally,alltheseelementsare nowintegratedintothemicrocontrollerandcanoperateinseveraldifferentmodes.

SingleOutputPWMMode
ThismodeisenabledonlyintheeventthattheP1M1andP1M0bitsoftheCCP1CONregisterarecleared.Inthiscase,thereisonlyone PWMsignalwhichcanbesimultaneouslyavailableonamaximumoffourdifferentoutputpins.Besides,thePWMsignalmayappearin basicorinvertedwaveform.SignaldistributionisdeterminedbythebitsofthePSTRCONregister,whileit'spolarityisdeterminedbythe CCP1M1andCCP1M0bitsoftheCCP1CONregister. Whenaninvertedoutputisinuse,thepinsarelowactiveandpulseshavingthesamewaveformarealwaysgeneratedinpairs:ontheP1A andP1CpinsandP1BandP1Dpins,respectively.

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

7/11

19/05/13

Chapter 5: CCP Modules - Book: PIC Microcontrollers

Fig.511SingleOutputPWMMode

HalfBridgeMode
Inthismode,thePWMsignalisoutputontheP1Apin,whileatthesametimethecomplementaryPWMsignalisoutputontheP1Bpin. SuchpulsesactivateMOSFETdriversinHalfBridgemodewhichenable/disablecurrentflowthroughdevice.

Fig.512HalfBridgeMode

Inrelationtothiscircuit,itisverydangeroustoswitchonbothMOSFETdriverssimultaneously.Theshortcircuitcausedinthatmomentwill befatal.Inordertoavoidthat,itisnecessarytoprovideashortdelaybetweenswitchingdriversonandoff.Thisdelayismarkedas"td"in figure513below.TheproblemissolvedbyusingthePDC0PDC6bitsofthePWM1CONregister.

Fig.513HalfBridgeMode

Asshowninfigure514,thesamemodecanbeusedtoactivateMOSFETdriversinFullBridge:

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

8/11

19/05/13

Chapter 5: CCP Modules - Book: PIC Microcontrollers

Fig.514ActivateMOSFETdrivers

FullBridgeMode
InFullBridgemode,allfourpinsareusedasoutputs.Inpractice,thismodeiscommonlyusedtorunmotors,whichprovidessimpleand completecontrolofspeedandrotationdirection.Therearetwosuchconfigurations:FullBridgeForwardandFullBridgeReverse.

Fig.515FullBridgeMode

FullBridgeForwardConfiguration
InForwardmodethefollowingoccurs:

Logicone(1)appearsontheP1Apin(pinishighactive) PulsesequenceappearsontheP1Dpinand Logiczero(0)appearsontheP1BandP1Cpins(pinsarelowactive).


FigurebelowshowsthestateoftheP1AP1DpinsduringonefullPWMcycle.

Fig.516ForwardMode

FullBridgeReverseConfiguration
ThesameoccursinReversemode,exceptofthepinsfunctions:

Logicone(1)appearsontheP1Cpin(pinisactivehigh) PulsesequenceappearsontheP1Bpinand Logiczero(0)appearsontheP1AandP1Dpins(pinsareactivelow).

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

9/11

19/05/13

Chapter 5: CCP Modules - Book: PIC Microcontrollers

Fig.517ReverseMode

PWM1CONRegisterSTRCPWMRestartEnablebit

1Uponautoshutdown,thePWMmoduleisautomaticallyreset,whiletheECCPASEbitoftheECCPASregisteris cleared. 0InordertorestartPWMmoduleuponautoshutdown,theECCPASEbitmustbeclearedinsoftware.


PDC6PDC0PWMDelayCountbits.7digitbinarynumberdeterminesthenumberofinstructioncycles(4*Tosc)addedastimedelay duringtheactivationofPWMoutputpins.

Fig.518PWM1CONRegister

PSTRCONRegister
STRSYNCSteeringSyncbitdeterminesthemomentofPWMpulsesteering:

1SteeringoccursuponthePSTRCONhasbeenchanged,butonlyifaPWMwaveformiscompletedand 0SteeringoccursuponthePSTRCONregisterhasbeenchanged.ThePWMsignalonoutputpinisimmediately changedwithnoregardtowhetherthepreviouscycleiscompletedornot.Thisoperationisusefulwhenitisneeded toimmediatelyremoveaPWMsignalfromthepin.


STRDSteeringEnablebitDdeterminestheP1Dpinfunction.

1P1DpinhasthePWMwaveformwithpolaritycontrolledbytheCCP1M0andCCP1M1bitsand 0PinisconfiguredasgeneralPortDinput/output.
STRCSteeringEnablebitCdeterminestheP1Cpinfunction.

1P1CpinhasthePWMwaveformwithpolaritycontrolledbytheCCP1M0andCCP1M1bitsand 0PinisconfiguredasgeneralportDinput/output.
STRBSteeringEnablebitBdeterminestheP1Bpinfunction.

1P1BpinhasthePWMwaveformwithpolaritycontrolledbytheCCP1M0andCCP1M1bitsand 0PinisconfiguredasgeneralportDinput/output.
STRASteeringEnablebitAdeterminestheP1Apinfunction.

1P1DpinhasthePWMwaveformwithpolaritycontrolledbytheCCP1M0andCCP1M1bitsand 0PinisconfiguredasgeneralportAinput/output.
ECCPASRegister

Fig.519ECCPASRegister

ECCPASEECCPAutoShutdownEventStatusbitindicateswhethershutdownofCCPmodulehasoccurred(Shutdownstate):

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

10/11

19/05/13
1CCPmoduleisinShutdownstateand 0CCPmoduleoperatesnormally.

Chapter 5: CCP Modules - Book: PIC Microcontrollers

ECCPAS2ECCPAS0ECCPAutoShutdownSourceSelectbitsselectautoshutdownsource:
ECCPAS2
0 0 0 0 1 1 1 1

ECCPAS1
0 0 1 1 0 0 1 1

ECCPAS0
0 1 0 1 0 1 0 1

SHUT HO WNST AT ESO URCE


Shutdown state disabled Comparator C1 output change Comparator C2 output change Comparator C1 or C2 output change Logic zero (0) on INT pin Logic zero (0) on INT pin or comparator C1 output change Logic zero (0) on INT pin or comparator C2 output change Logic zero (0) on INT pin or comparator C1 or C2 output change

Table57ECCPASRegister

PSSAC1,PSSAC0PinsP1A,P1CShutdownStateControlbitsdefinelogicstateonoutputpinsP1AandP1CwhenCCPmoduleisin shutdownstate.
PSSAC1
0 0 1

PSSAC0
0 1 X

PINSL O G ICST AT E
0 1 High impedance (Tri-state)

Table58A&CLogicStates

PSSBD1,PSSBD0PinsP1B,P1DShutdownStateControlbitsdefinelogicstateonoutputpinsP1BandP1DwhenCCPmoduleisin shutdownstate.
PSSBD1
0 0 1

PSSBD0
0 1 X

PINSL O G ICST AT E
0 1 High impedance (Tri-state)

Table59B&DLogicStates

previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/

11/11

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers


Products Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter6:SerialCommunicationModules
EUSART
TheEnhancedUniversalSynchronousAsynchronousReceiverTransmitter(EUSART)moduleisaserialI/Ocommunicationperipheral.Itis alsoknownasSerialCommunicationsInterface(SCI).Itcontainsallclockgenerators,shiftregistersanddatabuffersnecessarytoperform aninputoroutputserialdatatransferindependentlyofthedeviceprogramexecution.Asitsnamestates,apartfromtheusageofclockfor synchronization,thismodulecanalsoestablishasynchronousconnection,whichmakesitirreplaceableinsomeapplications. Forexample,intheeventthatitisdifficultor impossibletoprovidespecialchannelsforclock anddatatransfer(forexample,radioremote controlorinfrared),theEUSARTmodulepresents itselfasaconvenientsolution.
Fig.61RemoteControlandPlane
EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

TheEUSARTsystemintegratedintothePIC16F887microcontrollerhasthefollowingfeatures:

Fullduplex asynchronoustransmitandreceive Programmable8or9bitcharacterlength Addressdetectionin9bitmode Inputbufferoverrunerrordetectionand Halfduplexcommunicationinsynchronousmode(masterorslave).


EUSARTAsynchronousMode
TheEUSARTtransmitsandreceivesdatausingstandardnonreturntozero(NRZ)format.Asseeninfigure62below,thismodedoesnot useclocksignal,whilethedataformatbeingtransferredisverysimple:

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

Fig.62EUSARTAsynchronousMode

Briefly,eachdataistransferredinthefollowingway:

Inidlestate,datalinehashighlogiclevel(1) EachdatatransmissionstartswithSTARTbitwhichisalwaysazero(0) Eachdatais8or9bitwide(LSBbitisfirsttransferred)and EachdatatransmissionendswithSTOPbitwhichalwayshaslogiclevelwhichisalwaysaone(1).

EUSARTAsynchronousTransmitter

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

1/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Fig.63EUSARTAsynchronousTransmitter

InordertoenabledatatransmissionviaEUSARTmodule,itisnecessarytoconfigureittooperateasatransmitter.Inotherwords,itis necessarytodefinethestateofthefollowingbits: TXEN=1EUSARTtransmitterisenabledbysettingthisbitoftheTXSTAregister SYNC=0EUSARTisconfiguredtooperateinasynchronousmodebyclearingthisbitoftheTXSTAregisterand SPEN=1BysettingthisbitoftheRCSTAregister,EUSARTisenabledandtheTX/CKpinisautomaticallyconfiguredasoutput.Ifthisbitis simultaneouslyusedforsomeanalogfunction,itmustbedisabledbyclearingthecorrespondingbitoftheANSELregister. ThecentralpartoftheEUSARTtransmitteristheshiftregisterTSRwhichisnotdirectlyaccessiblebytheuser.Inordertostarttransmission, themodulemustbeenabledbysettingtheTXENbitoftheTXSTAregister.DatatobesentshouldbewrittentotheTXREGregister,which willcausethefollowingsequenceofevents:

BytewillbeimmediatelytransferredtotheshiftregisterTSR TXREGregisterremainsempty,whichisindicatedbysettingflagbitTXIFofthePIR1register.IftheTXIEbitofthe PIE1registerisset,aninterruptwillbegenerated.Besides,theflagissetregardlessofwhetheraninterruptis enabledornot.Also,itcannotbeclearedbysoftware,butbywritingnewdatatotheTXREGregister Controlelectronics"pushes"datatowardtheTXpininrhythmwithinternalclock:STARTbit(0)...data...STOPbit (1) WhenthelastbitleavestheTSRregister,theTRMTbitoftheTXSTAregisterisautomaticallysetand IftheTXREGregisterhasreceivedanewcharacterdatainthemeantime,thewholeprocedureisrepeated immediatelyaftertheSTOPbitofthepreviouscharacterhasbeentransmitted.


Sending9bitdataisenabledbysettingtheTX9bitoftheTXSTAregister.TheTX9DbitoftheTXSTAregisteristheninthandMost Significantdatabit.Whentransferring9bitdata,theTX9Ddatabitmustbewrittenbeforewritingthe8leastsignificantbitsintotheTXREG register.AllninebitsofdatawillbetransferredtotheTSRshiftregisterimmediatelyaftertheTXREGwriteiscomplete.

EUSARTAsynchronousReceiver

Fig.64EUSARTAsynchronousReceiver

SimilartotheactivationofEUSARTtransmitter,inordertoenablethereceiveritisnecessarytodefinethefollowingbits:

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

2/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

CREN=1EUSARTreceiverisenabledbysettingthisbitoftheRCSTAregister SYNC=0EUSARTisconfiguredtooperateinasynchronousmodebyclearingthisbitstoredintheTXSTAregisterand SPEN=1BysettingthisbitoftheRCSTAregister,EUSARTisenabledandtheRX/DTpinisautomaticallyconfiguredasinput.Ifthisbitis simultaneouslyusedforsomeanalogfunction,itmustbedisabledbyclearingthecorrespondingbitoftheANSELregister. WhenthisfirstandnecessarystepisaccomplishedandSTARTbitisdetected,dataistransferredtotheshiftregisterRSRthroughtheRX pin.WhentheSTOPbithasbeenreceived,thefollowingoccurs:

DataisautomaticallytransferredtotheRCREGregister(ifempty) TheflagbitRCIFissetandaninterrupt,ifenabledbytheRCIEbitofthePIE1register,occurs.Similartotransmitter, theflagbitisclearedbysoftwareonly,i.e.byreadingtheRCREGregister.Bearinmindthatthisisatwocharacter FIFOmemory(firstin,firstout)whichallowsreceptionoftwocharacterssimultaneously IftheRCREGregisterisoccupied(containstwobytes)andtheshiftregisterdetectsnewSTOPbit,theoverflowbit OERRwillbeset.Inthiscase,anewcomingdataislost,andtheOEERbitmustbeclearedbysoftware.Itisdone byclearingandresettingtheCRENbit. Note:itisnotpossibletoreceivenewdataasfarastheOERRbitisset IftheSTOPbitiszero(0),theFERRbitoftheRCSTAregisterdetectingreceiveerrorwillbesetand Toreceive9bitdataitisnecessarytosettheRX9bitoftheRCSTAregister.

ReceiveErrorDetection
Therearetwotypesoferrorswhichthemicrocontrollercanautomaticallydetect.ThefirstoneiscalledFramingerrorandoccurswhenthe receiverdoesnotdetecttheSTOPbitattheexpectedtime.SucherrorisindicatedviatheFERRbitoftheRCSTAregister.Ifthisbitisset,it meansthatthelastreceiveddatamaybeincorrect.Itisimportanttoknowseveralthings:

AFramingerrordoesnotgenerateaninterruptbyitself Ifthisbitisset,thelastreceiveddatahasanerror Aframingerror(bitset)doesnotpreventreceptionofnewdata TheFERRbitisclearedbyreadingreceiveddata,whichmeansthatcheckmustbedonebeforedatareadingand TheFERRbitcannotbeclearedbysoftware.Ifneeded,itcanbeclearedbyclearingtheSPENbitoftheRCSTA register.ItwillsimultaneouslycauseresetofthewholeEUSARTsystem.


AnothertypeoferroriscalledOverrunError.ThereceiveFIFOcanholdtwocharacters.Anoverrunerrorwillbegeneratedifthethird characterisreceived.Simply,thereisnospaceforanotheronebyteandanerrorisunavoidable!WhenthishappenstheOERRbitofthe RCSTAregisterisset.Theconsequencesarethefollowing:

DataalreadystoredintheFIFOregisters(twobytes)canbenormallyread NoadditionaldatawillbereceiveduntiltheOERRbitisclearedand Thisbitisnotdirectlyaccessed.Toclearit,itisnecessarytocleartheCRENbitoftheRCSTAregisterortoreset thewholeEUSARTsystembyclearingtheSPENbitoftheRCSTAregister.

Receiving9bitData
Inadditiontoreceivingstandard8bitdata,theEUSARTsystemsupports9bitdatareception.Onthetransmitside,theninthbitis"attached" totheoriginalbytejustbeforetheSTOPbit.Onthereceiveside,whentheRX9bitoftheRCSTAregisterisset,theninthdatabitwillbe automaticallywrittentotheRX9Dbitofthesameregister.Whenthisbyteisreceived,oneshouldtakecareofhowtoreaditsbitstheRX9D databitmustbereadbeforereadingthe8leastsignificantbitsoftheRCREGregister.Otherwise,theninthdatabitwillbeautomatically cleared.

Fig.65Receiving9bitData

AddressDetection
WhentheADDENbitoftheRCSTAregisterisset,theEUSARTmoduleisabletoreceiveonly9bitdata,whereasall8bitdatawillbe ignored.Althoughitseemslikearestriction,suchmodesenableserialcommunicationbetweenseveralmicrocontrollers.Theprincipleof

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

3/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

operationissimple.Themasterdevicesends9bitdatawhichrepresentstheaddressofonemicrocontroller.Allslavemicrocontrollers sharingthesametransmissionline,receivethisdata.Ofcourse,eachofthemmusthavetheADDENbitsetbecauseitenablesaddress detection.

Uponreceivingthisdataeachslavechecksifthataddressmatchesitsown.Software,inwhichaddressmatchoccurs,mustdisableaddress detectionbyclearingitsADDENbit.Themasterdevicekeepsonsending8bitdata.Alldatapassingthroughthetransmissionlinewillbe receivedby"recognized"EUSARTmoduleonly.Uponreceivingthelastbyte,theslavedeviceshouldsettheADDENbitinordertoenable newaddressdetection.

Fig.67SendingData

TXSTARegister

Fig.68TXSTARegister

CSRCClockSourceSelectbitdeterminesclocksource.Itisusedonlyinsynchronousmode.

1Mastermode.ClockisgeneratedinternallyfromBaudRateGeneratorand 0Slavemode.Clockisgeneratedfromexternalsource.
TX99bitTransmitEnablebit

19bitdatatransmissionviaEUSARTsystemand 08bitdatatransmissionviaEUSARTsystem.
TXENTransmitEnablebit

1Transmissionenabledand 0Transmissiondisabled.
SYNCEUSARTModeSelectbit

1EUSARToperatesinsynchronousmodeand 0EUSARToperatesinasynchronousmode.
SENDBSendBreakCharacterbitisonlyusedinasynchronousmodeandonlyincaseitisrequiredtoobserveLINbusstandard.

1SendingBreakcharacterisenabledand 0Breakcharactertransmissioniscompleted.
BRGHHighBaudRateSelectbitdeterminesbaudrateinasynchronousmode.ItdoesnotaffectEUSARTinsynchronousmode.

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

4/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

1EUSARToperatesathighspeedand 0EUSARToperatesatlowspeed.
TRMTTransmitShiftRegisterStatusbit

1TSRregisterisemptyand 0TSRregisterisfull.
TX9DNinthbitofTransmitDatacanbeusedasaddressorparitybit.

RCSTARegister

Fig.69RCSTARegister

SPENSerialPortEnablebit

1Serialportenabled.RX/DTandTX/CKpinsareautomaticallyconfiguredasinputandoutputrespectivelyand 0Serialportdisabled.
RX99bitReceiveEnablebit

1Receiving9bitdataviaEUSARTsystemand 0Receiving8bitdataviaEUSARTsystem.
SRENSingleReceiveEnablebitisusedonlyinsynchronousmodewhenthemicrocontrolleroperatesasmaster.

1Singlereceiveenabledand 0Singlereceivedisable.
CRENContinuousReceiveEnablebitactsdifferentlydependingonEUSARTmode. Asynchronousmode:

1Receiverenabledand 0Receiverdisabled.
Synchronousmode:

1EnablescontinuousreceiveuntiltheCRENbitisclearedand 0Disablescontinuousreceive.
ADDENAddressDetectEnablebitisonlyusedinaddressdetectmode.

1Enablesaddressdetectionon9bitdatareceiveand 0Disablesaddressdetection.Theninthbitcanbeusedasparitybit.
FERRFramingErrorbit

1Onreceive,FramingErrorisdetectedand 0Noframingerror.
OERROverrunErrorbit.

1Onreceive,OverrunErrorisdetectedand 0Nooverrunerror.
RX9DNinthbitofReceivedDatacanbeusedasaddressorparitybit.

EUSARTBaudRateGenerator(BRG)
IfyoucarefullylookattheasynchronousEUSARTreceiverortransmitterdiagram,youwillsee,inbothcases,thatclocksignalfromthelocal timerBRGisusedforsynchronization.Thesameclocksourceisalsousedinsynchronousmode. Thistimerconsistsoftwo8bitregisterscomprisingone16bitregister.

Fig.610EUSARTBaudRateGenerator(BRG)

Anumberwrittentothesetworegistersdeterminesthebaudrate.Besides,boththeBRGHbitoftheTXSTAregisterandtheBRGH16bitof theBAUDCTLregisteraffectclockfrequency.

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

5/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

TheformulausedtodetermineBaudRateisgiveninthetablebelow.
BITS
SYNC 0 0 0 0 1 1 BRG1G 0 0 1 1 0 1 BRGH 0 1 0 1 X X 8-bit / asynchronous 8-bit / asynchronous 16-bit / asynchronous 16-bit / asynchronous 8-bit / asynchronous 16-bit / asynchronous Fosc / [64 (n + 1)] Fosc / [16 (n + 1)] Fosc / [16 (n + 1)] Fosc / [4 (n + 1)] Fosc / [4 (n + 1)] Fosc / [4 (n + 1)]

BRG /EUSART MO DE

BAUDRAT EF O RMUL A

Table61BaudRate

Thefollowingtablescontainvaluesthatshouldbewrittentothe16bitregisterSPBRGandassignedtotheSYNC,BRGHandBRGH16bits inordertoobtainsomeofthestandardbaudrates. TheformulasusedtodeterminetheBaudRateare:

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

6/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Table62DeterminingBaudRate

BAUDCTLRegister

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

7/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Fig.611BAUDCTLRegister

ABDOVFAutoBaudDetectOverflowbitisonlyusedinasynchronousmodeduringbaudratedetection.

1Autobaudtimeroverflowedand 0Autobaudtimerdidnotoverflow.
RCIDLReceiveIdleFlagbitisonlyusedinasynchronousmode.

1Receiverisidleand 0STARTbithasbeenreceivedandreceivingisinprogress.
SCKPSynchronousClockPolaritySelectbitactsdifferentlydependingonEUSARTmode. Asynchronousmode:

1TransmitinverteddatatotheRC6/TX/CKpinand 0Transmitnoninverteddatatothesamepin.
Synchronousmode:

1Synchronizationonrisingedgeoftheclockand 0Synchronizationonfallingedgeoftheclock.
WUEWakeupEnablebit

1ReceiverwaitsforafallingedgeontheRC7/RX/DTpintostartwakingupthemicrocontrollerfromsleepmode and 0Receiveroperatesnormally.


ABDENAutoBaudDetectEnablebitisusedinasynchronousmodeonly.

1Autobauddetectmodeisenabled.Bitisautomaticallyclearedonbaudratedetectand 0Autobauddetectmodeisdisabled.
InShort:
SendingdataviaasynchronousEUSARTcommunication:

1. ThedesiredbaudrateshouldbesetbyusingbitsBRGH(TXSTAregister)andBRG16(BAUDCTLregister)and registersSPBRGHandSPBRG 2. TheSYNCbit(TXSTAregister)shouldbeclearedandtheSPENbitshouldbeset(RCSTAregister)inorderto enableserialport 3. On9bitdatatransmission,theTX9bitoftheTXSTAregistershouldbeset 4. DatatransmissionisenabledbysettingbitTXENoftheTXSTAregister.BitTXIFofthePIR1registeris automaticallyset 5. IfneededthebitTXENcausesaninterrupt,theGIEandPEIEbitsoftheINTCONregistershouldbeset 6. On9bitdatatransmission,valueoftheninthbitshouldbewrittentotheTX9DbitoftheTXSTAregisterand 7. Transmissionstartsbywriting8bitdatatotheTXREGregister.
ReceivingdataviaasynchronousEUSARTcommunication:

1. BaudRateshouldbesetbyusingbitsBRGH(TXSTAregister)andBRG16(BAUDCTLregister)andregisters SPBRGHandSPBRG 2. TheSYNCbit(TXSTAregister)shouldbeclearedandtheSPENbitshouldbeset(RCSTAregister)inorderto enableserialport 3. Ifitisnecessarythedatareceivecausesaninterrupt,boththeRCIEbitofthePIE1registerandbitsGIEand PEIEoftheINTCONregistershouldbeset 4. On9bitdatareceive,theRX9bitoftheRCSTAregistershouldbeset 5. DatareceiveshouldbeenabledbysettingtheCRENbitoftheRCSTAregister 6. TheRCSTAregistershouldbereadtogetinformationonpossibleerrorswhichhaveoccurredduring transmission.On9bitdatareceive,theninthbitwillbestoredinthisregisterand 7. Received8bitdatastoredintheRCREGregistershouldberead.
SettingAddressDetectionMode:

1. BaudRateshouldbesetbyusingbitsBRGH(TXSTAregister)andBRG16(BAUDCTLregister)andregisters SPBRGHandSPBRG 2. TheSYNCbit(TXSTAregister)shouldbeclearedandtheSPENbitshouldbeset(RCSTAregister)inorderto

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

8/18

19/05/13
enableserialport

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

3. Ifitisnecessarythedatareceivecausesaninterrupt,theRCIEbitofthePIE1bitaswellasbitsGIEandPEIE oftheINTCONregistershouldbeset 4. TheRX9bitoftheRCSTAregistershouldbeset 5. TheADDENoftheRCSTAregistershouldbeset,whichenablesadatatobeinterpretedasaddress 6. DatareceiveisenabledbysettingtheCRENbitoftheRCSTAregister 7. Immediatelyupon9bitdataisreceived,theRCIFbitofthePIR1registerwillbeautomaticallyset.Ifenabled,an interruptoccurs 8. TheRCSTAregistershouldbereadinordertogetinformationonpossibleerrorswhichhaveoccurredduring transmission.TheninthbitRX9Disalwayssetand 9. Received8bitsstoredintheRCREGregistershouldberead.Itshouldbecheckedwhetherthecombinationof thesebitsmatchesthepredefinedaddress.Ifthematchoccurs,itisnecessarytocleartheADDENbitofthe RCSTAregister,whichenablesfurther8bitdatareceive.

MasterSynchronousSerialPortModule
MSSPmodule(MasterSynchronousSerialPort)isaveryuseful,butatthesametimeoneofthemostcomplexcircuitwithinthe microcontroller.Itenableshighspeedcommunicationbetweenamicrocontrollerandotherperipheralsormicrocontrollerdevicesbyusing fewinput/outputlines(maximumtwoorthree).Therefore,itiscommonlyusedtoconnectthemicrocontrollertoLCDdisplays,A/D converters,serialEEPROMs,shiftregistersetc.Themainfeatureofthistypeofcommunicationisthatitissynchronousandsuitableforuse insystemswithasinglemasterandoneormoreslaves.Amasterdevicecontainsthenecessarycircuitryforbaudrategenerationand suppliestheclockforalldevicesinthesystem.Slavedevicesmayinthatwayeliminatetheinternalclockgenerationcircuitry.TheMSSP modulecanoperateinoneoftwomodes:

SPImode(SerialPeripheralInterface) ICmode(InterIntegratedCircuit)
Asseeninfigure612below,oneMSSPmodulerepresentsonlyahalfofthehardwareneededtoestablishserialcommunication,while anotherhalfisstoredinthedevicethedataisexchangedwith.Eventhoughthemodulesonbothendsofthelinearethesame,theirmodes areessentiallydifferentdependingonwhethertheyoperateasaMasteroraSlave: Ifthemicrocontrollertobeprogrammedcontrolsanotherdeviceorcircuit(peripherals),itshouldoperateasamasterdevice.Amodule definedassuchwillgenerateclockwhenneeded,i.e.onlywhendatareceiveandtransmitisrequiredbythesoftware.Itdependsonthe masterwhethertheconnectionwillbeestablishedornot.Otherwise,ifthemicrocontrollertobeprogrammedisapartofsomeperipheral whichbelongstosomemorecomplexdevice(forexamplePC),thenitshouldoperateasaslavedevice.Assuch,italwayshastowaitfor requestfordatatransferfrommasterdevice.

Fig.612MSSPModule

SPIMode
TheSPImodeallows8bitsofdatatobetransmittedandreceivedsimultaneouslyusing3input/outputlines:

SDOSerialDataOuttransmitline SDI SerialDataInreceivelineand SCKSerialClocksynchronizationline.


Inadditiontothesethreelines,ifthemicrocontrollerexchangesdatawithseveralperipheraldevices,theforthline(SS)maybealsoused. Refertofigure613below. SSSlaveSelectisadditionalpinusedforspecificdeviceselection.Itisactiveonlyincasethemicrocontrollerisinslavemode,i.e.when theexternalmasterdevicerequiresdataexchange. WhenoperatinginSPImode,MSSPmoduleusesintotalof4registers:

SSPSTATstatusregister

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

9/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

SSPCONcontrolregister SSPBUFbufferregisterand SSPSRshiftregister(notdirectlyavailable)


Thefirstthreeregistersarewritable/readableandcanbechangedatanymoment,whiletheforthregister,sincenotavailable,isusedfor convertingdatainto"serial"format.

Fig.613SPIMode

Asseeninfigure614,thecentralpartoftheSPImoduleconsistsoftworegistersconnectedtopinsforreceive,transmitand synchronization. Shiftregister(SSPRS)isdirectlyconnectedtothemicrocontrollerpinsandusedfordatatransmissioninserialformat.TheSSPRSregister hasitsinputandoutputandshiftsthedatainandoutofdevice.Inotherwords,eachbitappearingoninput(receiveline)simultaneously shiftsanotherbittowardoutput(transmitline). TheSSPBUFregister(Buffer)isapartofmemoryusedtotemporarilyholdthedatawrittentotheSSPRSuntilthereceiveddataisready. Uponreceivingall8bitsofdata,thatbyteismovedtotheSSPBUFregister.Thisdoublebufferingofthereceiveddata(SSPBUF)allowsthe nextbytetostartreceptionbeforereadingthedatathatwasjustreceived.AnywritetotheSSPBUFregisterduringtransmission/receptionof datawillbeignored.Sincehavingbeenthemostaccessed,thisregisterisconsideredthemostimportantfromtheprogrammerspointof view. Namely,ifmodesettingsareneglected,datatransferviaSPIactuallymeanstowriteandreaddatafromthisregister,whileanother "acrobatics"suchasmovingregistersareautomaticallyperformedbyhardware.

Fig.614SPIMode

Inshort:
PriortoinitializingtheSPI,itisnecessarytospecifyseveraloptions:

Mastermode(SCKpinistheclockoutput) Slavemode(SCKpinistheclockinput) Datainputphasemiddleorendofdataoutputtime(SMPbit) Clockedge(CKEbit) BaudRate(onlyinMastermode)and Slaveselectmode(Slavemodeonly).


Step1. DatatotransmitshouldbewrittentothebufferregisterSSPBUF.Immediatelyafterthat,iftheSPImoduleoperates inmastermode,themicrocontrollerwillautomaticallyperformthefollowingsteps2,3and4.IftheSPImodule operatesasSlave,themicrocontrollerwillnotperformthesestepsuntiltheSCKpindetectsclocksignal.
Fig.615Step1

Step2. ThisdataisnowmovedtotheSSPSRregisterandtheSSPBUFregisterisnotcleared.
Fig.616Step2

Step3. Synchronizedwithclocksignal,thisdataisshiftedtotheoutputpin(MSBbitfirst)whiletheregisterissimultaneouslybeingfilledwithbits

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

10/18

19/05/13
usesexternalclock(pinSCK).

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

throughinputpin.InMastermode,themicrocontrolleritselfgeneratesclock,whiletheSlavemode

Fig.617Step3

Step4. TheSSPSRregisterisfulloncethe8bitsofdatahavebeenreceived.Itisindicatedbysetting theBFandSSPIFbits.Thereceiveddata(thatbyte)isautomaticallymovedfromtheSSPSR registertotheSSPBUFregister.Sincedatatransferviaserialcommunicationisperformed automatically,therestoftheprogramisnormallyexecutedwhiledatatransferisinprogress.In thatcase,thefunctionoftheSSPIFbitistogenerateinterruptwhenonebytetransmissionis completed.


Fig.618Step4

Step5. Atlast,thedatastoredintheSSPBUFregisterisreadyforuseandmovedtoanyregisteravailable.
Fig.619Step5

ICmode
ICmode(InterICBus)isespeciallysuitablewhenthemicrocontrollerandintegratedcircuit,whichthemicrocontrollershouldexchange datawith,arewithinthesamedevice.Itiscommonlyaboutanothermicrocontrollersorspecialized,cheapintegratedcircuitsbelongingto thenewgenerationofsocalled"smartperipheralcomponents"(memories,temperaturesensors,realtimeclocksetc.) SimilartoserialcommunicationinSPImode,datatransferinICmodeissynchronousandbidirectional.Thistimeonlytwopinsareusedfor datatransfer.ThesearetheSDA(SerialData)andSCL(SerialClock)pins.Theusermustconfigurethesepinsasinputsoroutputsthrough theTRISCbits. Perhapsitisnotdirectlyvisible.Byobservingparticularrules(protocols),thismodeenablesupto122differentcomponentstobe simultaneouslyconnectedinasimplewaybyusingonlytwovaluableI/Opins.Briefly,everythingworksasfollows:Clocknecessaryto synchronizetheoperationofbothdevicesisalwaysgeneratedbythemasterdevice(microcontroller)anditsfrequencydirectlyaffectsbaud rate.Thereareprotocolsallowingmaximum3,4MHzclockfrequency(socalledhighspeedICbus),buttheclockfrequencyofthemost frequentlyusedprotocolislimitedto100KHz.Thereisnolimitincaseofminimalfrequency. Whenmasterandslavecomponentsaresynchronizedbytheclock,everydataexchangeisalwaysinitializedbymaster.OncetheMSSP modulehasbeenenabled,itwaitsforaStartconditiontooccur.FirstthemasterdevicesendstheSTARTbit(logiczero)throughtheSDA pin,thenthe7bitaddressoftheselectedslavedevice,andfinally,thebitwhichrequiresdatawrite(0)orread(1)tothatdevice. Accordingly,followingthestartcondition,theeightbitsareshiftedintotheSSPSRregister.Allslavedevicessharethesametransmission lineandallwillsimultaneouslyreceivethefirstbyte,butonlyoneofthemhastheaddresstomatch.

Fig.620MasterandSlaveConfiguration

Oncethefirstbytehasbeensent(only8bitdataaretransmitted),mastergoesintoreceivemodeandwaitsforacknowledgmentfromthe receivedevicethataddressmatchhasoccurred.Iftheslavedevicesendsacknowledgedatabit(1),datatransferwillbecontinueduntilthe masterdevice(microcontroller)sendstheStopbit. Thisisthesimplestexplanationofhowtwocomponentscommunicate.Ifneeded,thismicrocontrollerisabletocontrolmorecomplicated situationswhen1024differentcomponents,sharedbyseveraldifferentmasterdevices,areconnected.Suchdevicesarerarelyusedin practiceandthereisnoneedtodiscussthematgreaterlength.

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

11/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Fig.621DataTransfer

FigurebelowshowstheblockdiagramoftheMSSPmoduleinICmode.

Fig.622MSSPBlockDiagraminICMode

TheMSSPmoduleusessixregistersforICoperation.Someofthemareshowninfigureabove:

SSPCON SSPCON2 SSPSTAT SSPBUF SSPSRand SSPADD.


SSPSTATRegister

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

12/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Fig.623SSPSTATRegister

SMPSamplebit SPImastermodeThisbitdeterminesinputdataphase.

1Logicstateisreadatendofdataoutputtimeand 0Logicstateisreadinthemiddleofdataoutputtime.
SPIslavemodeThisbitmustbeclearedwhenSPIisusedinSlavemode. ICmode(masterorslave)

1Slewratecontroldisabledforstandardspeedmode(100kHz)and 0Slewratecontrolenabledforhighspeedmode(400kHz).
CKEClockEdgeSelectbitselectssynchronizationmode. CKP=0:

1Dataistransmittedonrisingedgeofclockpulse(01)and 0Dataistransmittedonfallingedgeofclockpulse(10).
CKP=1:

1Dataistransmittedonfallingedgeofclockpulse(10)and 0Dataistransmittedonrisingedgeofclockpulse(01).
D/AData/AddressbitisusedinICmodeonly.

1Indicatesthatthelastbytereceivedortransmittedwasdataand 0Indicatesthatthelastbytereceivedortransmittedwasaddress.
PStopbitisusedinICmodeonly.

1STOPbitwasdetectedlastand 0STOPbitwasnotdetectedlast.
SStartbitisusedinICmodeonly.

1STARTbitwasdetectedlastand 0STARTbitwasnotdetectedlast.
R/WReadWritebitisusedinICmodeonly.ThisbitholdstheR/Wbitinformationfollowingthelastaddressmatch.Thisbitisonlyvalid fromtheaddressmatchtothenextStartbit,StopbitornotACKbit. InICslavemode

1Datareadand 0Datawrite.
InICmastermode

1Transmitisinprogressand 0Transmitisnotinprogress.
UAUpdateAddressbitisusedin10bitICmodeonly.

1IndicatesthatitisnecessarytoupdatetheaddressintheSSPADDregisterand 0AddressintheSSPADDregisteriscorrectanddoesnotneedtobeupdated.
BFBufferFullStatusbit Duringdatareceive(inSPIandICmodes)

1Receivecomplete.TheSSPBUFregisterisfulland 0Receivenotcomplete.TheSSPBUFregisterisempty.
Duringdatatransmit(inICmodeonly)

1Datatransmitinprogress(doesnotincludethebitsACKandSTOP)and 0Datatransmitcomplete(doesnotincludethebitsACKandSTOP).
SSPCONRegister

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

13/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Fig.624SSPCONRegister

WCOLWriteCollisionDetectbit

1Collisiondetected.AwritetotheSSPBUFregisterwasattemptedwhiletheICconditionswerenotvalidfora transmissiontostartand 0Nocollision.


SSPOVReceiveOverflowIndicatorbit

1AnewbyteisreceivedwhiletheSSPSRregisterstillholdsthepreviousdata.Sincethereisnospacefornew datareceive,oneofthesetwobytesmustbecleared.Inthiscase,datainSSPSRislostand 0Serialdataiscorrectlyreceived.


SSPENSynchronousSerialPortEnablebitdeterminesthemicrocontrollerpinsfunctionandinitializesMSSPmodule: InSPImode

1EnablesMSSPmoduleandconfigurespinsSCK,SDO,SDIandSSasthesourceoftheserialportpinsand 0DisablesMSSPmoduleandconfiguresthesepinsasI/Oportpins.
InICmode

1EnablesMSSPmoduleandconfigurespinsSDAandSCLasthesourceoftheserialportpinsand 0DisablesMSSPmoduleandconfiguresthesepinsasI/Oportpins.
CKPClockPolaritySelectbitisnotusedinICmastermode. InSPImode

1Idlestateforclockisahighleveland 0Idlestateforclockisalowlevel.
InICslavemode

1Enablesclockand 0Holdsclocklow.Usedtoprovidemoretimefordatastabilization.
SSPM3SSPM0SynchronousSerialPortModeSelectbits.SSPmodeisdeterminedbycombiningthesebits:
SSPM3
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

SSPM2
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1

SSPM1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1

SSPM0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

MO DE
SPI master mode, clock = Fosc/4 SPI master mode, clock = Fosc/16 SPI master mode, clock = Fosc/64 SPI master mode, clock = (output TMR)/2 SPI slave mode, SS pin control enabled SPI slave mode, SS pin control disabled, SS can be used as I/O pin IC slave mode, 7-bit address used IC slave mode, 10-bit address used IC master mode, clock = Fosc / [4(SSPAD+1)] Mask used in IC slave mode Not used IC controlled master mode Not used Not used IC slave mode, 7-bit address used,START and STOP bits enable interrupt IC slave mode, 10-bit address used,START and STOP bits enable interrupt

Table63SynchronousSerialPortModeSelectBits

SSPCON2Register

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

14/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Fig.625SSPCON2Register

GCENGeneralCallEnablebit InICslavemodeonly

1Enablesinterruptwhenageneralcalladdress(0000h)isreceivedintheSSPSRand 0Generalcalladdressdisabled.
ACKSTATAcknowledgeStatusbit InICMasterTransmitmodeonly

1Acknowledgewasnotreceivedfromslaveand 0Acknowledgewasreceivedfromslave.
ACKDTAcknowledgedatabit InICMasterReceivemodeonly

1NotAcknowledgeand 0Acknowledge.
ACKENAcknowledgeconditionEnablebit InICMasterReceivemode

1InitiateacknowledgeconditiononSDAandSCLpinsandtransmitACKDTdatabit.Itisautomaticallyclearedby hardwareand 0Acknowledgeconditionisnotinitiated.


RCENReceiveEnablebit InICMastermodeonly

1EnablesdatareceiveinICmodeand 0Receivedisabled.
PENSTOPconditionEnablebit InICMastermodeonly

1InitiatesSTOPconditiononpinsSDAandSCL.Afterwards,thisbitisautomaticallyclearedbyhardwareand 0STOPconditionisnotinitiated.
RSENRepeatedSTARTConditionEnabledbit InICmastermodeonly

1InitiatesSTARTconditiononpinsSDAandSCL.Afterwards,thisbitisautomaticallyclearedbyhardwareand 0RepeatedSTARTconditionisnotinitiated.
SENSTARTConditionEnabled/StretchEnabledbit InICMastermodeonly

1InitiateSTARTconditiononpinsSDAandSCL.Afterwards,thisbitisautomaticallyclearedbyhardwareand 0STARTconditionisnotinitiated.

ICinMasterMode
Themostcommoncaseiswhenthemicrocontrolleroperatesasamasterandtheperipheralcomponentasaslave.Thisiswhythisbook coversjustthismode.Itisalsoconsideredthattheaddressconsistsof7bitsanddevicecontainsonlyonemicrocontroller(onemaster device). InordertoenableMSSPmoduleinthismode,itisnecessarytodothefollowing: Setbaudrate(SSPADDregister),turnoffslewratecontrol(bysettingtheSMPbitoftheSSPSTATregister)andselectmastermode (SSPCONregister).Afterthepreparationhasbeenfinishedandmodulehasbeenenabled(SSPCONregister:SSPENbit),oneshouldwait forinternalelectronicstosignalthateverythingisreadyfordatatransmission,i.e.theSSPIFbitofthePIR1registerisset. Thisbitshouldbeclearedbysoftwareandafterthat,themicrocontrollerisreadytostart"communication"withperipherals.

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

15/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Fig.627ICinMasterMode

DataTransmissioninICMasterMode
EachclockconditionontheSDApinstartswithlogiczero(0)whichappearsuponsettingtheSENbitoftheSSPCON2register.Even enabled,themicrocontrollerhastowaitacertaintimebeforeitstartscommunication.Itisthesocalled"Startcondition"duringwhich internalpreparationsandchecksareperformed.Ifallconditionsaremet,theSSPIFbitofthePIR1issetanddatatransferstartsassoonas theSSPBUFregisterisloaded. Sincemaximum112integratedcircuitsmaysimultaneouslysharethesame transmissionline,thefirstdatabytemustcontainaddresswhichmatchesonly oneslavedevice.Eachcomponenthasitsownaddresslistedintheproper datasheet.Theeighthbitofthefirstdatabytespecifiesdirectionofdata transmission,themicrocontrolleristosendorreceivedata.Inthiscase,itisall aboutdatareceiveandtheeighthbitthereforeislogiczero(0).
Fig.628DataTransmissioninICMasterMode

Whenaddressmatchoccurs,the microcontrollerhastowaitfortheacknowledge databit.Theslavedeviceacknowledges addressmatchbyclearingtheASKSTATbitof theSSPCON2register.Ifthematchproperly occurred,allbytesrepresentingdataare transmittedinthesameway. DatatransmissionendsbysettingtheSENbitof theSSPCON2register.ThesocalledSTOP conditionoccurs,whichenablestheSDApinto receivepulsecondition:StartAddress AcknowledgeDataAcknowledge....Data AcknowledgeStop!
Fig.629DataTransmissioninICMasterMode

DataReceptioninICMasterMode
Preparationsfordatareceptionaresimilartothosefordatatransmission,withexceptionthatthelastbitofthefirstsentbyte(containing address)islogicone(1).Itspecifiesthatmasterexpectstoreceivedatafromaddressedslavedevice.Withregardtothemicrocontroller,the followingeventsoccur: AfterinternalpreparationsarefinishedandSTARTbitisset,slavedevicestartssendingonebyteatatime.Thesebytesarestoredinthe serialregisterSSPSR.Eachdatais,afterreceivingthelasteighthbit,loadedtotheSSPBUFregisterfromwhereitcanberead.Byreading thisregister,theacknowledgebitisautomaticallysent,whichmeansthatmasterdeviceisreadytoreceivenewdata.

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

16/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

Attheend,similartodatatransmission,datareceptionendsbysettingtheSTOPbit:

Fig.630DataReceptioninICMasterMode

StartAddressAcknowledgeDataAcknowledge....DataAcknowledgeStop! Inthispulsecondition,theacknowledgebitissenttoslavedevice.

BaudRateGenerator
Inordertosynchronizedatatransmission,alleventstakingplaceontheSDApinmustbesynchronizedwiththeclockgeneratedinmaster device.Thisclockisgeneratedbyasimpleoscillatorwhosefrequencydependsonthemicrocontrollersmainoscillatorfrequency,value writtentotheSSPADDregisterandthecurrentSPImode. TheclockfrequencyofthemodedescribedinthisbookdependsonselectedquartzcrystalandtheSPADDregister.Theformulausedto calculateitisshowninfigurebelow.

Fig.631BaudRateGenerator

Usefulnotes...
Whenthemicrocontrollercommunicateswithperipheralcomponents,itmayhappenthatdatatransferfailsforsomereason.Inthatcase,it isrecommendedtocheckthestatusofsomebitswhichcanclarifytheproblem.Inpractice,thestateofthesebitsischeckedbyexecutinga shortsubroutineaftereachbytetransmissionandreception(justincase). WCOL(SPCON,7)IfyoutrytowriteanewdatatotheSSPBUFregisterwhileanotherdatatransmit/receiveisinprogress,theWCOLbit willbesetandthecontentsoftheSSPBUFregisterremainsunchanged.Writedoesnotoccur.Afterthis,theWCOLbitmustbeclearedin software. BF(SSPSTAT,0)Intransmitmode,thisbitissetwhentheCPUwritestotheSSPBUFregisterandremainssetuntilthebyteinserialformat isshiftedfromtheSSPSRregister.Inreceivemode,thisbitissetwhendataoraddressisloadedtotheSSPBUFregister.Itisclearedwhen theSSPBUFregisterisread. SSPOV(SSPCON,6)Inreceivemode,thisbitissetwhenanewbyteisreceivedbytheSSPSRregisterviaserialcommunication,whereas

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

17/18

19/05/13

Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

thepreviouslyreceiveddatahasnotbeenreadfromtheSSPBUFregisteryet. SDAandSCLPinsWhenSPPmoduleisenabled,thesepinsturnsintoOpenDrainoutputs.Itmeansthatthesepinsmustbeconnectedto theresistorswhich,attheotherend,areconnectedtopositivepowersupply.

Fig.632OpenDrainOutputResistors

InShort:
InordertoestablishserialcommunicationinICmode,thefollowingshouldbedone:

SettingModuleandSendingAddress:

ValuetodeterminebaudrateshouldbewrittentotheSSPADDregister SlewRatecontrolshouldbeturnedoffbysettingtheSMPbitoftheSSPSTATregister InordertoselectMastermode,binaryvalue1000shouldbewrittentotheSSPM3SSPM0bitsoftheSSPCON1 register TheSENbitoftheSSPCON2registershouldbeset(STARTcondition) TheSSPIFbitisautomaticallysetattheendofSTARTconditionwhenthemoduleisreadytooperate.Itshouldbe cleared SlaveaddressshouldbewrittentotheSSPBUFregisterand Whenthebyteissent,theSSPIFbit(interrupt)isautomaticallysetwhentheacknowledgebithasbeenreceivedfrom theSlavedevice.
DataTransmit:

DataistobesendshouldbewrittentotheSSPBUFregister Whenthebyteissent,theSSPIFbit(interrupt)isautomaticallysetupontheacknowledgebithasbeenreceivedfrom Slavedeviceand InordertoinformtheSlavedevicethattransmitiscomplete,STOPconditionshouldbeinitiatedbysettingthePEN bitoftheSSPCONregister.


DataReceive:

InordertoenablereceivetheRSENbitoftheSSPCON2registershouldbeset TheSSPIFbitsignalsdatareceive.WhendataisreadfromtheSSPBUFregister,theACKENbitoftheSSPCON2 registershouldbesetinordertoenablesendingacknowledgebitand InordertoinformSlavedevicethattransmitiscomplete,theSTOPconditionshouldbeinitiatedbysettingthePEN bitoftheSSPCONregister.


previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/

18/18

19/05/13
Products

Chapter 7: Analog Modules - Book: PIC Microcontrollers


Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter7:AnalogModules
ApartfromalargenumberofdigitalI/Olines,thePIC16F887contains14analoginputs.Theyenablethemicrocontrollertorecognize,not onlywhetherapinisdriventologiczeroorone(0or+5V),buttopreciselymeasureitsvoltageandconvertitintoanumericalvalue,i.e. digitalformat.ThewholeproceduretakesplaceintheA/Dconvertermodulewhichhasthefollowingfeatures:

Theconvertergeneratesa10bitbinaryresultusingthemethodofsuccessiveapproximationandstoresthe conversionresultsintotheADCregisters(ADRESLandADRESH) Thereare14separateanaloginputs TheA/Dconverterallowsconversionofananaloginputsignaltoa10bitbinaryrepresentationofthatsignaland ByselectingvoltagereferencesVrefandVref+,theminimalresolutionorqualityofconversionmaybeadjustedto variousneeds.

ADCModeandRegisters
EventhoughtheuseofA/Dconverterseemstobeverycomplicated,itisbasicallyverysimple,simplerthanusingtimersandserial communicationmodule,anyway.

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

Fig.71ADCModeandRegisters

Themoduleisunderthecontrolofthebitsoffourregisters:

ADRESHContainshighbyteofconversionresult ADRESLContainslowbyteofconversionresult ADCON0Controlregister0and ADCON1Controlregister1


ADRESHandADRESLRegisters
Whenconvertingananalogvalueintoadigitalone,theresultofthe10bitA/Dconversionwillbestoredinthesetworegisters.Inorderto dealwiththisvalueeasier,itcanappearintwoformatsleftjustifiedandrightjustified.TheADFMbitoftheADCON1registerdeterminesthe formatofconversionresult(seefigure72).IntheeventthatA/Dconverterisnotused,theseregistersmaybeusedasgeneralpurpose registers.

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

1/9

19/05/13

Chapter 7: Analog Modules - Book: PIC Microcontrollers

Fig.72ADRESHandADRESLRegisters

A/DAcquisitionRequirements
FortheADCtomeetitsspecifiedaccuracy,itisnecessarytoprovideacertaintimedelaybetweenselectingspecificanaloginputand measurementitself.Thistimeiscalled"acquisitiontime"andmainlydependsonthesourceimpedance.Thereisanequationusedfor accuratelycalculatingthistime,whichintheworstcaseamountstoapproximately20uS.Briefly,afterselecting(orchanging)theanalog inputandbeforestartingconversionitisnecessarytoprovideatleast20uStimedelaytoenabletheACDmaximalconversionaccuracy.

ADCClockPeriod
TimeneededtocompleteaonebitconversionisdefinedasTAD.TherequiredTADmustbeatleast1,6uS.Onefull10bitA/Dconversion isabitlongerthanexpectedandamountsto11TADperiods.However,sinceboththeconversionclockfrequencyandsourceare determinedbysoftware,oneoftheavailablecombinationofbitsADCS1andADCS0shouldbeselectedbeforevoltagemeasurementon someanaloginputstarts.ThesebitsarestoredintheADCON0register.
DEVICEF REQ UENCY( F O SC)
20 Mhz Fosc/2 Fosc/8 Fosc/32 Frc 0 0 1 1 0 1 0 1 100 nS 400 nS 1.6 uS 2 - 6 uS 8 Mhz 250 nS 1 uS 4 uS 2 - 6 uS 4 Mhz 500 nS 2 uS 8 uS 2 - 6 uS 1 Mhz 2 uS 8 uS 32 uS 2 - 6 uS

ADCCL O CKSO URCE

ADCS1

ADCS0

Table71ADCClockPeriod

AnychangeinthesystemclockfrequencywillaffecttheADCclockfrequency,whichmayadverselyaffecttheADCresult.Devicefrequency characteristicsareshowninthetableabove.Thevaluesintheshadedcellsareoutsideofrecommendedrange.

HowtoUseA/DConverter?
InordertoenabletheA/Dconvertertorunwithoutproblemsaswellastoavoidunexpectedresults,itisnecessarytoconsiderthefollowing:

A/Dconverterdoesnotdifferbetweendigitalandanalogvoltages.Inordertoavoiderrorsinmeasurementorchip damage,thepinsshouldbeconfiguredasanaloginputsbeforeconversionstarts.Thebitsusedforthispurposeare storedintheTRISandANSELHregisters WhentheportwithanaloginputsmarkedasCH0CH13isread,thecorrespondingbitswillbedriventologiczero(0) and Roughlyspeaking,voltagemeasurementintheconverterisbasedoncomparinginputvoltagewithinternalscale whichhas1024marks(210=1024).ThelowestscalemarkstandsfortheVrefvoltage,whilstthehighestmark standsfortheVref+voltage.Figure73belowshowsselectablereferentvoltagesandtheirminimumandmaximum valuesaswell.

Fig.73HowtoUseTheA/DConverter

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

2/9

19/05/13
ADCON0Register

Chapter 7: Analog Modules - Book: PIC Microcontrollers

Fig.74ADCON0Register

ADCS1,ADCS0A/DConversionClockSelectbitsselectclockfrequencyusedforinternalsynchronizationofA/Dconverter.Italso affectsdurationofconversion.
ADCS1
0 0 1 1

ADCS2
0 1 0 1

CLOCK
Fosc/2 Fosc/8 Fosc/32 RC *

Table72A/DConversionSelectBits

*Clockisgeneratedbyinternaloscillatorwhichisbuiltinconverter. CHS3CHS0AnalogChannelSelectbitsselectapinorananalogchannelforconversion,i.e.voltagemeasurement:
CHS3
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

CHS2
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1

CHS1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1

CHS0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

CHANNEL
0 1 2 3 4 5 6 7 8 9 10 11 12 13 CVref Vref = 0.6V

PIN
RA0/AN0 RA1/AN1 RA2/AN2 RA3/AN3 RA5/AN4 RE0/AN5 RE1/AN6 RE2/AN7 RB2/AN8 RB3/AN9 RB1/AN10 RB4/AN11 RB0/AN12 RB5/AN13

Table73AnalogChannelStatusBits

GO/DONEA/DConversionStatusbitdeterminescurrentstatusofconversion:

1A/Dconversionisinprogressand 0A/Dconversioniscomplete.ThisbitisautomaticallyclearedbyhardwarewhentheA/Dconversioniscompleted.
ADONA/DOnbitenablesA/Dconverter.

1A/Dconverterisenabledand 0A/Dconverterisdisabled.
ADCON1Register

Fig.75ADCON1Register

ADFMA/DResultFormatSelectbit

1Conversionresultrightjustified.SixmostsignificantbitsoftheADRESLHarenotusedand

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

3/9

19/05/13

Chapter 7: Analog Modules - Book: PIC Microcontrollers

0Conversionresultleftjustified.SixleastsignificantbitsoftheADRESLarenotused.
VCFG1VoltageReferencebitselectsnegativevoltagereferencesourceneededforA/Dconverteroperating.

1NegativevoltagereferenceisappliedontheVrefpinand 0VoltagepowersupplyVssisusedasnegativevoltagereferencesource.
VCFG0VoltageReferencebitselectspositivevoltagereferencesourceneededforA/Dconverteroperating.

1PositivevoltagereferenceisappliedontheVref+pinand 0VoltagepowersupplyVddisusedaspositivevoltagereferencesource.

InShort:
InordertomeasurevoltageonaninputpinbyA/Dconverterthefollowingshouldbedone: Step1Configuringport:

Writelogicone(1)tothecorrespondingbitoftheTRISregistertoconfigureitasinputand Writelogicone(1)tothecorrespondingbitoftheANSELregistertoconfigureitasanaloginput.
Step2ConfiguringADCmodule:

ConfigurevoltagereferenceintheADCON1register SelectADCconversionclockintheADCON0register SelectoneofinputchannelsCH0CH13oftheADCON0register SelectdataformatusingtheADFMbitoftheADCON1registerand EnableA/DconverterbysettingtheADONbitoftheADCON0register.


Step3ConfiguringADCinterrupt(optionally):

CleartheADIFbitand SettheADIE,PEIEandGIEbits.
Step4Waitfortherequiredacquisitiontime(approximately20uS)topass. Step5StartconversionbysettingtheGO/DONEbitoftheADCON0register. Step6WaitforADCconversiontocomplete.

ItisnecessarytocheckinprogramloopwhethertheGO/DONEpinisclearedorwaitforanA/Dinterrupt(mustbe previouslyenabled).
Step7ReadADCresults:

ReadtheADRESHandADRESLregisters.

AnalogComparator
InadditiontoA/Dconverter,thereisonemoremodule,whichuntilquiterecentlyhasbeenembeddedonlyinintegratedcircuits,belonging tosocalledanalogelectronics.Owingtothefactthatitishardlypossibletofindanymorecomplexautomaticdevicewhichinsomeway doesnotusethesecircuits,twohighqualitycomparatorsalongwithadditionalelectronicsareintegratedintothemicrocontrollerand connectedtoitspins. Howdoesacomparatoroperate?Basically,theanalogcomparatorisanamplifierwhichcomparesthemagnitudeofvoltagesattwoinputs. Lookingatitsphysicalfeatures,ithastwoinputsandoneoutput.Dependingonwhichinputhasahighervoltage(analogvalue),alogic zero(0)orlogicone(1)(digitalvalues)willappearonitsoutput:

Fig.76AnalogComparator

WhentheanalogvoltageatVinishigherthantheanalogvoltageatVin+,theoutputofthecomparatorisadigitallow leveland WhentheanalogvoltageatVin+ishigherthantheanalogvoltageatVin,theoutputofthecomparatorisadigitalhigh level.


ThePIC16F887microcontrollerhastwosuchvoltagecomparatorswhoseinputsareconnectedtoI/OpinsRA0RA3,whereastheoutputs areconnectedtothepinsRA4andRA5.Inadditionthereisalsoareferentvoltageinternalsourceonchipitself,butitwillbediscussed later. Thesetwocircuitsareundercontrolofthebitsstoredinthefollowingregisters: CM1CON0isincontrolofcomparatorC1 CM2CON0isincontrolofcomparatorC2and CM2CON1isincontrolofcomparatorC2.

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

4/9

19/05/13
VoltageReferenceInternalSource

Chapter 7: Analog Modules - Book: PIC Microcontrollers

Oneoftwoanalogvoltagesprovidedonthecomparatorinputsisusuallystableandunchangeable.Becauseofthosefeaturesitiscalled "voltagereference"(Vref).Togenerateit,bothexternalandspecialinternalvoltagesourcecanbeused.Afterselectingvoltagesource,Vref isderivedfromitbymeansofladdernetworkconsistingof16resistorswhichformvoltagedivider.Thevoltagesourceisselectablethrough bothendsofthatdividerthroughtheVRSSbitoftheVRCONregister. Inaddition,thevoltagefractionprovidedbyresistorladdernetworkmaybeselectedthroughthebitsVR0VR3andusedasvoltage reference.Seefigurebelow.

Fig.77VREF

Thecomparatorvoltagereferencehas2rangeswith16voltagelevelsineachrange.RangeselectioniscontrolledbytheVRRbitofthe VRCONregister.TheselectedvoltagereferencemaybeoutputtotheRA2/AN2pin. Eventhoughthemainideawastoobtainvaryingvoltagereferencefortheoperationofanalogmodules,asimpleA/Dconverterisobtained inthatwaytoo.Thisconverterisveryusefulinsomesituations. It'soperationisundercontroloftheVRCONregister.

ComparatorsandInterruptOperation
TheflagbitCMIFoftheregisterPIRissetoneverychangeoflogicstateonanycomparator'soutput.Thesamechangesalsocausean interruptifthefollowingbitsareset: CMIEbitofthePIEregister PEIEbitoftheINTCONregisterand GIEbitoftheINTCONregister. Ifinterruptisenabled,anychangeonthecomparator'soutputcanwakeupthemicrocontrollerfromsleepmodeifitissetupinthatmode.

CM1CON0Register

Fig.78CM1CON0Regsiter

BitsofthisregisterareincontrolofthecomparatorC1.Itmainlyaffectsconfigurationofitsinputs.Tounderstanditbetter,lookatfigure79 belowwhichshowsonlyapartofelectronicsdirectlyaffectedbythebitsofthisregister.

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

5/9

19/05/13

Chapter 7: Analog Modules - Book: PIC Microcontrollers

Fig.79ComparatorC1EnableBit

C1ONComparatorC1EnablebitenablescomparatorC1.

1ComparatorC1isenabledand 0ComparatorC1isdisabled.
C1OUTComparatorC1OutputbitiscomparatorC1outputbit. IfC1POL=1(comparatoroutputisinverted)

1AnalogvoltageatC1Vin+islowerthananalogvoltageatC1Vinand 0AnalogvoltageatC1Vin+ishigherthananalogvoltageatC1Vin.
IfC1POL=0(comparatoroutputisnoninverted)

1AnalogvoltageatC1Vin+ishigherthananalogvoltageatC1Vinand 0AnalogvoltageatC1Vin+islowerthananalogvoltageatC1Vin.
C1OEComparatorC1OutputEnablebit.

1ComparatorC1OUToutputisconnectedtotheC1OUTpin.*and 0Comparatoroutputisinternalonly.
*InordertoenabletheC1OUTbittobepresentonthepin,twoconditionsmustbemet:C1ON=1(comparatormustbeon)andthe correspondingTRISbit=0(pinmustbeconfiguredasoutput). C1POLComparatorC1OutputPolaritySelectbitenablescomparatorC1outputstatetobeinverted.

1ComparatorC1outputisinvertedand 0ComparatorC1outputisnoninverted.
C1RComparatorC1ReferenceSelectbit

1NoninvertinginputC1Vin+isconnectedtoreferencevoltageC1Vrefand 0NoninvertinginputC1Vin+isconnectedtotheC1IN+pin.
C1CH1,C1CH0ComparatorC1ChannelSelectbit
C1CH1
0 0 1 1

C1CH0
0 1 0 1

CO MPARAT O RC1VIN INPUT


Input C1Vin- is connected to the C12IN0- pin Input C1Vin- is connected to the C12IN1- pin Input C1Vin- is connected to the C12IN2- pin Input C1Vin- is connected to the C12IN3- pin

Table74ComparatorC1

CM2CON0Register

Fig.710CM2CON0Regsiter

BitsofthisregisterareincontrolofcomparatorC2.Similartothepreviouscase,thefigure711showsasimplifiedschematicofthecircuit affectedbythebitsofthisregister.

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

6/9

19/05/13

Chapter 7: Analog Modules - Book: PIC Microcontrollers

Fig.711ComparatorC2SchematicDiagram

C2ONComparatorC2EnablebitenablescomparatorC2.

1ComparatorC2isenabledand 0ComparatorC2isdisabled.
C2OUTComparatorC2OutputbitiscomparatorC2output. IfC2POL=1(comparatoroutputinverted)

1AnalogvoltageatC1Vin+islowerthananalogvoltageatC1Vinand 0AnalogvoltageatC1Vin+ishigherthananalogvoltageatC1Vin.
IfC2POL=0(comparatoroutputnoninverted)

1AnalogvoltageatC1Vin+ishigherthananalogvoltageatC1Vinand 0AnalogvoltageatC1Vin+islowerthananalogvoltageatC1Vin.
C2OEComparatorC2OutputEnablebit

1ComparatorC2OUToutputisconnectedtotheC2OUTpin.*and 0Comparatoroutputisinternalonly.
*InordertoenabletheC2OUTbittobepresentonthepin,twoconditionsmustbemet:C2ON=1(comparatormustbeon)andthe correspondingTRISbit=0(pinmustbeconfiguredasoutput). C2POLComparatorC2OutputPolaritySelectbitenablescomparatorC2outputstatetobeinverted.

1ComparatorC2outputisinvertedand 0ComparatorC2outputisnoninverted.
C2RComparatorC2ReferenceSelectbit

1NoninvertinginputC2Vin+isconnectedtoreferencevoltageC2Vrefand 0NoninvertinginputC2Vin+isconnectedtotheC2IN+pin.
C2CH1,C2CH0ComparatorC2ChannelSelectbit
C2CH1
0 0 1 1

C2CH0
0 1 0 1

CO MPARAT O RC2VIN INPUT


Input C2Vin- is connected to the C12IN0- pin Input C2Vin- is connected to the C12IN1- pin Input C2Vin- is connected to the C12IN2- pin Input C2Vin- is connected to the C12IN3- pin

Table75ComparatorC2ChannelSelectBit

CM2CON1Register

Fig.712CM2CON1Register

MC1OUTMirrorCopyofC1OUTbit

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

7/9

19/05/13
MC2OUTMirrorCopyofC2OUTbit C1RSELComparatorC1ReferenceSelectbit

Chapter 7: Analog Modules - Book: PIC Microcontrollers

1SelectablevoltageCVrefisusedinvoltagereferenceC1Vrefsourceand 0Fixedvoltagereference0.6VisusedinvoltagereferenceC1Vrefsource.
C2RSELComparatorC2ReferenceSelectbit

1SelectablevoltageCVrefisusedinvoltagereferenceC2Vrefsourceand 0Fixedvoltagereference0.6VisusedinvoltagereferenceC2Vrefsource.
T1GSSTimer1GateSourceSelectbit

1TimerT1gatesourceisT1Gand 0TimerT1gatesourceiscomparatorSYNCC2OUT.
C2SYNCComparatorC2OutputSynchronizationbit

1ComparatorC2outputissynchronizedtofallingedgeofTimerTMR1clockand 0Comparatoroutputisasynchronoussignal.
VRCONRegister

Fig.713VRCONRegister

VRENComparatorC1VoltageReferenceEnablebit

1VoltagereferenceCVrefsourceispoweredonand 0VoltagereferenceCVrefsourceispoweredoff.
VROEComparatorC2VoltageReferenceEnablebit

1VoltagereferenceCVrefisconnectedtothepinand 0VoltagereferenceCVrefisdisconnectedfromthepin.
VRRCVrefRangeSelectionbit

1Voltagereferencesourceissettolowrangeand 0Voltagereferencesourceissettohighrange.
VRSSComparatorVrefRangeselectionbit

1VoltagereferencesourceisintherangeofVref+toVrefand 0VoltagereferencesourceisintherangeofVddVss(powersupplyvoltage).
VR3VR0CVrefValueSelection IfVRR=1(lowrange) Voltagereferenceiscalculatedusingtheformula:CVref=([VR3:VR0]/24)Vdd IfVRR=0(highrange) Voltagereferenceiscalculatedusingtheformula:CVref=Vdd/4+([VR3:VR0]/32)Vdd

InShort:
InordertoproperlyusebuiltinComparators,itisnecessarytodothefollowing: Step1Configuringmodule:

Inordertoselecttheappropriatemode,bitsoftheregistersCM1CON0andCM2CON0shouldbeconfigured.Interrupt shouldbedisabledonanychangeofmode.
Step2ConfiguringinternalvoltagereferenceVrefsource(onlywhenused).IntheVRCONregisteritisnecessaryto:

SelectoneoftwovoltagerangesusingtheVRRbit ConfigurenecessaryVrefusingbitsVR3VR0 SettheVROEbitifneededand EnablevoltageVrefsourcebysettingtheVRENbit.


Formulausedtocalculatevoltagereference: VRR=1(lowrange) CVref=([VR3:VR0]/24)VLADDER VRR=0(highrange) CVref=(VLADDER/4)+([VR3:VR0]VLADDER/32)

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

8/9

19/05/13
Vladder=Vddor([Vref+][Vref])orVref+ Step3Startingoperation:

Chapter 7: Analog Modules - Book: PIC Microcontrollers

EnableinterruptbysettingbitsCMIE(PIEregister),PEIEandGIE(bothintheINTCONregister) ReadbitsC1OUTandC2OUToftheCMCONregisterand ReadflagbitCMIFofthePIRregister.Afterbeingset,thisbitmustbeclearedinsoftware.


previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/8/chapter-7-analog-modules/

9/9

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers


Products Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter8:OtherMCU'sCircuits
Oscillators
Asseeninfigurebelow,clocksignalmaybegeneratedbyoneoftwobuiltinoscillators.

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

Fig.81Twobuiltinoscillators

AnExternaloscillatorisinstalledwithinthemicrocontrollerandconnectedtotheOSC1andOSC2pins.Itiscalledexternalbecauseit reliesonexternalcircuitryfortheclocksignalandfrequencystabilization,suchasastandaloneoscillator,quartscrystal,ceramicresonator orresistorcapacitorcircuit.Theoscillatormodeisselectedbybitsofbytessentduringprogramming,socalledConfigWord. Internaloscillatorconsistsoftwoseparate,internaloscillators: TheHFINTOSCisahighfrequencyinternaloscillatorwhichoperatesat8MHz.Themicrocontrollercanuseclocksourcegeneratedatthat frequencyorafterbeingdividedinprescalerand TheLFINTOSCisalowfrequencyinternaloscillatorwhichoperatesat31kHz.Itsclocksourcesareusedforwatchdogandpowerup timingbutitcanalsobeusedasaclocksourcefortheoperationoftheentiremicrocontroller. ThesystemclockcanbeselectedbetweenexternalorinternalclocksourcesviatheSystemClockSelect(SCS)bitoftheOSCCONregister.

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

OSCCONRegister
TheOSCCONregistercontrolsthesystemclockandfrequencyselectionoptions.Itcontainsthefollowingbits:frequencyselectionbits (IRCF2,IRCF1,IRCF0),frequencystatusbits(HTS,LTS),systemclockcontrolbits(OSTA,SCS).

Fig.82OSCCONRegister

IRCF20InternalOscillatorFrequencySelectbits.Combinationofthesethreebitsdeterminesthedividerrate.Theclockfrequencyof internaloscillatorisalsodeterminedinthisway.
IRCF2 IRCF1 IRCF0 F REQ UENCY O SC.

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

1/10

19/05/13
1 1 1 1 0 0 0 0 1 1 0 0 1 1 0 0

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers


1 0 1 0 1 0 1 0 8 MHz 4 MHz 2 MHz 1 MHz 500 kHz 250 kHz 125 kHz 31 kHz HFINTOSC HFINTOSC HFINTOSC HFINTOSC HFINTOSC HFINTOSC HFINTOSC LFINTOSC

Table81InternalOscillatorFrequencySelectBits

OSTSOscillatorStartupTimeoutStatusbitindicateswhichclocksourceiscurrentlyinuse.Thisbitisreadableonly.

1Externalclockoscillatorisinuseand 0Oneofinternalclockoscillatorsisinuse(HFINTOSCorLFINTOSC).
HTSHFINTOSCStatusbit(8MHz125kHz)indicateswhetherhighfrequencyinternaloscillatoroperatesinastableway.

1HFINTOSCisstableand 0HFINTOSCisnotstable.
LTSLFINTOSCStablebit(31kHz)indicateswhetherlowfrequencyinternaloscillatoroperatesinastableway.

1LFINTOSCisstableand 0LFINTOSCisnotstable.
SCSSystemClockSelectbitdetermineswhichoscillatoristobeusedasaclocksource.

1Internaloscillatorisusedforsystemclock 0Externaloscillatorisusedforsystemclockand TheoscillatormodeissetbybitsinConfigWordwhicharewrittentothemicrocontrollermemoryduringprogramming.

ExternalClockModes
Inordertoenabletheexternaloscillatortooperateatdifferentspeedsandusedifferentcomponentsforfrequencystabilization,itcanbe configuredtooperateinoneofseveralmodes.Modeselectionisperformedaftertheprogramwritingandcompiling.Firstofall,itis necessarytoactivatetheprogramonPCusedforprogramming.Inthiscase,PICflash.Clickontheoscillatorcomboxandselectoneoption fromthedropdownlist.Afterthat,theappropriatebitswillbesetbecominginthatwayapartofseveralbyteswhichtogetherformConfig Word. Duringprogramming,thebytesofConfigWordarewrittentothemicrocontrollersROMmemoryandstoredinspecialregisterswhichare notavailabletotheuser.Onthebasisofthesebits,themicrocontrollerknowswhattodo,althoughitisnotexplicitlyspecifiedinthe (written)program.

Fig.83PICflashProgram

ExternaloscillatorinECmode Theexternalclock(EC)modeusesthesystemclocksourceconfiguredfromexternaloscillator.Thefrequencyofthisclocksourceis

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

2/10

19/05/13
unlimited(020MHz).

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers

Fig.84ExternalOscillator

Thismodehasthefollowingadvantages:

TheexternalclocksourceisconnectedtotheOSC1inputandtheOSC2isavailableforgeneralpurposeI/O Itispossibletosynchronizetheoperationofthemicrocontrollerwiththerestofonboardelectronics Inthismodethemicrocontrollerstartsoperatingimmediatelyafterthepowerison.Thereisnodelayrequiredfor frequencystabilizationand Temporarystoppingtheexternalclockinputhastheeffectofhaltingthedevicewhileleavingalldataintact.Upon restartingtheexternalclock,thedeviceresumesoperationasifnothinghashappened.

Fig.85ExternalOscillatorinECMode

ExternaloscillatorinLP,XTorHSmode

Fig.86TwoTypesofExternalOscillators

TheLP,XTandHSmodessupporttheusageofinternaloscillatorforconfiguringclocksource.Thefrequencyofthissourceisdetermined byquartzcrystalorceramicresonatorsconnectedtotheOSC1andOSC2pins.Dependingonfeaturesofthecomponentinuse,selectone ofthefollowingmodes: LPmode(LowPower)isusedforlowfrequencyquartzcrystalonly.Thismodeisdesignedtodriveonly32.768kHzcrystalsusually embeddedinquartzwatches.Itiseasytorecognizethembysmallsizeandspecificcylindricalshape.Thecurrentconsumptionistheleast ofthethreemodes XTmodeisusedforintermediatefrequencyquartzcrystalsupto8MHz.Thecurrentconsumptionisthemediumofthethreemodesand HSmode(HighSpeed)isusedforhighfrequencyquartzcrystalsover8MHz.Thecurrentconsumptionisthehighestofthethreemodes.

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

3/10

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers

Fig.87SchematicofExternalOscillatorandAdditionalExternalComponents

CeramicresonatorsinXTorHSmode

Fig.88CeramicResonator

Ceramicresonatorsarebytheirfeaturessimilartoquartzcrystals.Thisiswhytheyareconnectedinthesameway.Unlikequartzcrystals, theyarecheaperandoscillatorscontainingthemhaveabitworsecharacteristics.Theyareusedforclockfrequenciesrangingbetween100 kHzand20MHz.

ExternaloscillatorinRCandRCIOmode
Therearecertainlymanyadvantagesinusingelementsforfrequencystabilization,butsometimestheyarereallyunnecessary.Itismostly sufficientthattheoscillatoroperatesatfrequencynotpreciselydefinedsothatembeddingofsuchexpensiveelementsmeansawasteof money.Thesimplestandcheapestsolutioninthesesituationsistouseoneresistorandonecapacitorfortheoperationofoscillator.There aretwomodes: RCmode.InRCmode,theRCcircuitisconnectedtotheOSC1pinasshownin figure.TheOSC2pinoutputstheRCoscillatorfrequencydividedby4.Thissignal maybeusedforcalibration,synchronizationorotherapplicationrequirements.
Fig.89RCMode

RCIOmode.Similartothepreviouscase,theRCcircuitisconnectedtotheOSC1 pin.Thistime,theavailableOSC2pinisusedasadditionalgeneralpurposeI/Opin.
Fig.810RCIOMode

Inbothcases,itisrecommendedtousecomponentsasshowninfigure. Thefrequencyofsuchoscillatoriscalculatedaccordingtotheformulaf=1/Tinwhich: f=frequency[Hz] T=R*C=timeconstant[s] R=resistorresistance[] C=capacitorcapacity[F]

InternalClockModes
Theinternaloscillatorcircuitconsistsoftwoseparateoscillatorsthatcanbeselectedasthesystemclocksource: TheHFINTOSCoscillatorisfactorycalibratedandoperatesat8MHz.Itsfrequencycanbeuseradjustedviasoftwareusingbitsofthe OSCTUNEregisterand TheLFINTOSCoscillatorisnotfactorycalibratedandoperatesat31kHz. Similartotheexternaloscillator,theinternalonecanalsooperateinseveralmodes.Themodeisselectedinthesamewayasincaseof

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

4/10

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers

externaloscillatorusingbitsoftheConfigWordregister.Inotherwords,everythingisperformedwithinPCsoftware,immediatelybefore programwritingtothemicrocontrollerstarts. InternaloscillatorinINTOSCmode Inthismode,theOSC1pinisavailableasgeneralpurposeI/Owhilethe OSC2pinoutputsselectedinternaloscillatorfrequencydividedby4.


Fig.811INTOSCMode

InternaloscillatorinINTOSCIOmode Inthismode,bothpinsareavailableforgeneralpurposeI/O.
Fig.812INTOSCIOMode

InternalOscillatorSettings
Theinternaloscillatorconsistsoftwoseparatecircuits. 1.ThehighfrequencyinternaloscillatorHFINTOSCisconnectedtothepostscaler(frequencydivider).Itisfactorycalibratedandoperates at8MHz.Usingpostscaler,thisoscillatorcanoutputclocksourcesatoneofsevenfrequencieswhichcanbeselectedviasoftwareusingthe IRCF2,IRCF1andIRCF0pinsoftheOSCCONregister. TheHFINTOSCisenabledbyselectingoneofsevenfrequencies(between8MHzand125kHz)andsettingtheSystemClockSource (SCS)bitoftheOSCCONregisterafterwards.Asseeninfigurebelow,everythingisperformedusingbitsoftheOSCCONregister.

Fig.813InternalOscillatorsettings

2.ThelowfrequencyoscillatorLFINTOSCisuncalibratedandoperatesat31kHz.Itisenabledbyselectingthisfrequency(bitsofthe OSCCONregister)andsettingtheSCSbitofthesameregister.

TwoSpeedClockStartupMode
TwoSpeedClockStartupmodeisusedtoprovideadditionalpowersavingswhenthemicrocontrolleroperatesinsleepmode.Whatisthis allabout? WhenconfiguredtooperateinLP,XTorHSmodes,theexternaloscillatorwillbeswitchedoffontransitiontosleepinordertoreducethe overallpowerconsumptionofthedevice. Whenconditionsforwakeuparemet,themicrocontrollerwillnotimmediatelystartoperatingbecauseithastowaitforclocksignal frequencytobecomestable.Suchdelaylastsforexactly1024pulses.Afterthat,themicrocontrollerproceedswithprogramexecution.The problemisthatveryoftenonlyafewinstructionsareperformedbeforethemicrocontrollerissetuptoSleepmodeagain.Itmeansthatmost oftimeaswellaspowerobtainedfrombatteriesiswasted.Thisproblemissolvedbyusinginternaloscillatorforprogramexecutionwhile these1024pulsesarecounted.Afterwards,assoonastheexternaloscillatorfrequencybecomesstable,itwillautomaticallytakeoverthe leadingrole.Thewholeprocessisenabledbysettingonebitoftheconfigurationword.Inordertoprogramthemicrocontrolleritis necessarytoselecttheIntExtSwitchoveroptioninsoftware.

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

5/10

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers

Fig.814EnableIntExtSwitchover

FailSafeClockMonitor TheFailSafeClockMonitor(FSCM)monitorstheoperationofexternaloscillatorandallowsthemicrocontrollertoproceedwithprogram executioneventheexternaloscillatorfailsforsomereason.Inthiscase,theinternaloscillatortakesoveritsrole.

Fig.815FailSafeClockMonitor

Thefailsafeclockmonitordetectsafailedoscillatorbycomparingtheinternalandexternalclocksources.Incaseittakesmorethan2mS fortheexternaloscillatorclocktocome,theclocksourcewillbeautomaticallyswitched.Theinternaloscillatorwilltherebycontinue operatingcontrolledbythebitsoftheOSCCONregister.WhentheOSFIEbitofthePIE2registerisset,aninterruptwillbegenerated.The systemclockwillcontinuetobesourcedfrominternalclockuntilthedevicesuccessfullyrestartstheexternaloscillatorandswitchesbackto externaloperation. Similarlytothepreviouscases,thismoduleisenabledbychangingconfigurationwordjustbeforetheprogrammingofchipstarts.Thistime, itisdonebyselectingtheFailSafeClk.Monitoroption.

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

6/10

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers

Fig.816EnablingFailSafeClockMonitor

OSCTUNERegister
ModificationsintheOSCTUNEregisteraffecttheHFINTOSCfrequency,butnottheLFINTOSCfrequency.Furthermore,thereisno indicationduringoperationthatshifthasoccurred.

Fig.817OSCTUNERegister

TUN4TUN0FrequencyTuningbits.Bycombiningthesefivebits,the8MHzoscillatorfrequencyshifts.Inthisway,thefrequencies obtainedbyitsdivisioninthepostscalershifttoo.
TUN4
0 0 0

TUN3
1 1 1

TUN2
1 1 1

TUN1
1 1 0

TUN0
1 0 1

F REQ UENCY
Maximal

0 0 1

0 0 1

0 0 1

0 0 1

1 0 1 Calibrated

1 1 1

0 0 0

0 0 0

1 0 0

0 1 0 Minimal

Table82FrequencyTuningBits

EEPROM
EEPROMisneitherpartofprogrammemory(ROM)nordatamemory(RAM),butaspecialmemorysegment.Eventhesememorylocations

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

7/10

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers

arenoteasilyandquicklyaccessedasotherregisters,theyareofgreatimportancebecausetheEEPROMdataarepermanentlysaved (afterthepowersupplygoesoff).EEPROMdatacanbealsochangedatanymoment.Becauseoftheseexceptionalfeatures,eachbyteof EEPROMisvaluable. ThePIC16F887microcontrollerhas256locationsofdataEEPROMcontrolledbythebitsofthefollowingregisters:

EECON1(controlregister) EECON2(controlregister) EEDAT(savesdatareadyforwriteandread)and EEADR(savesaddressofEEPROMlocationtobeaccessed).


Inaddition,EECON2isnottrueregister,itdoesnotphysicallyexist.Itisusedinwriteprogramsequenceonly. TheEEDATHandEEADRHregistersbelongtothesamegroupastheregistersusedduringEEPROMwriteandread.Bothofthemare thereforeusedforprogram(FLASH)memorywriteandread. Sincethisisconsideredariskzone(yousurelydonotwantyourmicrocontrollertoaccidentallyeraseyourprogram),wewillnotdiscussit further,butadviseyoutobecareful.

EECON1Register

Fig.818EECON1Register

EEPGDProgram/DataEEPROMSelectbit

1Accessprogrammemoryand 0AccessEEPROMmemory.
WRERREEPROMErrorFlagbit

1Writeoperationisprematurelyterminatedanderrorhasoccurredand 0AccessEEPROMmemory.
WRENEEPROMWriteEnablebit.

1WritetodataEEPROMenabledand 0WritetodataEEPROMdisabled.
WRWriteControlbit

1InitiateswritetodataEEPROMand 0WritetodataEEPROMiscomplete.
RDReadControlbit

1InitiatesreadfromdataEEPROMand 0ReadfromdataEEPROMdisabled.
ReadfromEEPROMMemory
InordertoreaddataEEPROMmemory,followtheprocedurebelow: Step1:Writeanaddress(00hFFh)totheEEADRregister Step2:SelectEEPROMmemoryblockbyclearingtheEEPGDbitoftheEECON1register Step3:Toreadlocation,settheRDbitofthesameregisterand Step4:DataisstoredintheEEDATregisterandreadytouse. ThefollowingexampleillustratesdataEEPROMread:

B S F S T A T U S , R P 1 B C F S T A T U S , R P 0 A c c e s s b a n k 2 M O V F A D D R E S S , W M o v e a d d r e s s t o t h e W r e g i s t e r M O V W F E E A D R W r i t e a d d r e s s B S F S T A T U S , R P 0 A c c e s s b a n k 3 B C F E E C O N 1 , E E P G D S e l e c t E E P R O M B S F E E C O N 1 , R D R e a d d a t a B C F S T A T U S , R P 0 A c c e s s b a n k 2 M O V F E E D A T A , W D a t a i s s t o r e d i n t h e W r e g i s t e r

WritetoDataEEPROMMemory

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

8/10

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers

InordertowritedatatoEEPROMmemory,firstitisnecessarytowritetheaddresstotheEEADRregisterfirstanddatatotheEEDATregister afterwards.Thenyouhavetofollowaspecialsequencetoinitiatewriteforeachbyte.Interruptsmustbedisabledduringthisprocedure. DataEEPROMwriteisillustratedintheexamplebelow:

B S F S T A T U S , R P 1 B S F S T A T U S , R P 0 B T F S C E E C O N , W R 1 W a i t f o r t h e p r e v i o u s w r i t e t o c o m p l e t e G O T O $ 1 B C F S T A T U S , R P 0 B a n k 2 M O V F A D D R E S S , W M o v e a d d r e s s t o W M O V W F E E A D R W r i t e a d d r e s s M O V F D A T A , W M o v e d a t a t o W M O V W F E E D A T A W r i t e d a t a B S F S T A T U S , R P 0 B a n k 3 B C F E E C O N 1 , E E P G D S e l e c t E E P R O M B S F E E C O N 1 , W R E N W r i t e t o E E P R O M e n a b l e d B C F I N C O N , G I E A l l i n t e r r u p t s d i s a b l e d M O V L W 5 5 h R e q u i r e d s e q u e n c e s t a r t M O V W F E E C O N 2 M O V L W A A h M O V W F E E C O N 2 R e q u i r e d s e q u e n c e e n d B S F E E C O N 1 , W R B S F I N T C O N , G I E I n t e r r u p t s e n a b l e d B C F E E C O N 1 , W R E N W r i t e t o E E P R O M d i s a b l e d

Reset!Blackout,BrownoutorNoises?
Onreset,themicrocontrollerimmediatelystopsoperationandclearsitsregisters.Resetsignalmaybegeneratedexternallyatanymoment (lowlogiclevelontheMCLRpin).Ifneededitcanbealsogeneratedbyinternalcontrollogic.Poweronalwayscausesreset.Namely, becauseofmanytransitionaleventswhichtakeplacewhenpowersupplyison(switchcontactflashingandsparkling,slowvoltagerise, gradualclockfrequencystabilizationetc.),itisnecessarytoprovideacertaintimedelaybeforethemicrocontrollerstartsoperating.Two internaltimersPWRTandOSTareinchargeofthat.Thefirstonecanbeenabledordisabledduringprogramwriting.Thescenarioisas follows: Whenpowersupplyvoltagereaches1.21.7V,acircuitcalledPowerup timerresetsthemicrocontrollerwithinapproximately72mS.Immediately uponthistimehasrunout,theresetsignalgeneratesanothertimercalled Oscillatorstartuptimerwithin1024quartzoscillatorperiods.Whenthis delayisover(markedasTresetinfigure)andtheMCLRpinissethigh,the microcontrollerstartstoexecutethefirstinstructionintheprogram.
Fig.819OscillatorStartUpTimeDelay

Apartfromsuchcontrolledresetwhichoccursatthemomentpowergoeson,thereareanothertworesetscalledBlackoutandBrown outwhichmayoccurduringoperationaswellasatthemomentpowergoesoff.

Blackoutreset
Blackoutresettakesplacewhenthepowersupplynormallygoesoff.Inthatcase, themicrocontrollerhasnotimetodoanythingunpredictablesimplybecausethe voltagedropsveryfastbeneathitsminimalvalue.Inotherwordsthelightgoesoff, curtainfallsdownandtheshowisover!
Fig.820BlackOutResetatLossOfPower

Brownoutreset
Whenpowersupplyvoltagedropsslowly(typicalexampleofthatisbatterydischargealthoughthemicrocontrollerexperiencesfarfaster voltagedropasaslowprocess),theinternalelectronicsgraduallystopsoperatingandsocalledBrownoutresetoccurs.Inthatcase,prior tothemicrocontrollerstopsoperatingthereisaseriousdangerthatcircuitswhichoperateathighervoltagesstartperformunpredictable.It canalsocausesfatalchangesintheprogramitselfbecauseitissavedinonchipflashmemory.

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

9/10

19/05/13

Chapter 8: Other MCU's Circuits - Book: PIC Microcontrollers


Fig.821BrownOutResetatGradualLossOfPower

Noises
ThisisaspecialkindofBrownoutresetwhichoccursinindustrialenvironmentwhen thepowersupplyvoltageblinksforamomentanddropsitsvaluebeneathminimal level.Evenshort,suchnoiseinpowerlinemaycatastrophicallyaffecttheoperation ofdevice.
Fig.822Noises

MCLRpin
Logiczero(0)ontheMCLRpincausesimmediateandregularreset.Itisrecommendedtobeconnectedasshowninfigurebelow.The functionofadditionalcomponentsistosustainpurelogicone(1)duringnormaloperation.Iftheirvaluesaresuchtoprovidehighlogic levelonthepinonlyuponTresetisover,themicrocontrollerwillimmediatelystartoperating.Thisfeaturemaybeveryusefulwhenitis necessarytosynchronizetheoperationofthemicrocontrollerwithadditionalelectronicsortheoperationofseveralmicrocontrollers. InordertoavoidanyerrorwhichmayoccuronBrownoutreset,thePIC16F887has builtindefensemechanism.Itisasimplebuteffectivecircuitwhichreactsevery timethevoltagepowersupplydropsbelow4Vandholdsthatlevelformorethan100 microseconds.Inthatcase,thiscircuitgeneratesresetsignalandsincethatmoment thewholemicrocontrolleroperatesasifithasjustbeenswitchedon.
Fig.823MasterClearPin

previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/

10/10

19/05/13
Products

Chapter 9: Instruction Set - Book: PIC Microcontrollers


Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

Chapter9:InstructionSet
Ithasbeenalreadymentionedthatmicrocontrollersdiffersfromotherintegratedcircuits.Mostofthemarereadyforinstallationintothe targetdevicejustastheyare,thisisnotthecasewiththemicrocontrollers.Inorderthatthemicrocontrollermayoperate,itneedsprecise instructionsonwhattodo.Inotherwords,aprogramthatthemicrocontrollershouldexecutemustbewrittenandloadedintothe microcontroller.Thischaptercoversthecommandswhichthemicrocontroller"understands".Theinstructionsetforthe16FXXincludes35 instructionsintotal.SuchasmallnumberofinstructionsisspecifictotheRISCmicrocontrollerbecausetheyarewelloptimizedfromthe aspectofoperatingspeed,simplicityinarchitectureandcodecompactness.TheonlydisadvantageofRISCarchitectureisthatthe programmerisexpectedtocopewiththeseinstructions.
INST RUCT IO N DESCRIPT IO N Data Transfer Instructions MOVLW k MOVWF f MOVF f,d CLRW CLRF f SWAPF f,d Move constant to W Move W to f Move f to d Clear W Clear f Swap nibbles in f k -> w W -> f f -> d 0 -> W 0 -> f f(7:4),(3:0) -> f(3:0),(7:4) Z Z Z 1 1 1 1 1 1 2 1, 2 1, 2 O PERAT IO N FLAG CLK *

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

Arithmetic-logic Instructions ADDLW k ADDWF f,d SUBLW k SUBWF f,d ANDLW k ANDWF f,d ANDWF f,d IORLW k IORWF f,d XORLW k XORWF f,d INCF f,d DECF f,d RLF f,d RRF f,d COMF f,d Add W and constant Add W and f Subtract W from constant Subtract W from f Logical AND with W with constant Logical AND with W with f Logical AND with W with f Logical OR with W with constant Logical OR with W with f Logical exclusive OR with W with constant Logical exclusive OR with W with f Increment f by 1 Decrement f by 1 Rotate left f through CARRY bit Rotate right f through CARRY bit Complement f Bit-oriented Instructions BCF f,b BSF f,b Clear bit b in f Set bit b in f Program Control Instructions BTFSC f,b BTFSS f,b DECFSZ f,d INCFSZ f,d GOTO k CALL k RETURN RETLW k RETFIE Test bit b of f. Skip the following instruction if clear. Test bit b of f. Skip the following instruction if set. Decrement f. Skip the following instruction if clear. Increment f. Skip the following instruction if set. Go to address Call subroutine Return from subroutine Return with constant in W Return from interrupt Other instructions NOP CLRWDT No operation Clear watchdog timer TOS -> PC, 1 -> GIE 0 -> WDT, 1 -> TO, 1 -> PD TO, PD 1 1 Skip if f(b) = 0 Skip if f(b) = 1 f-1 -> d skip if Z = 1 f+1 -> d skip if Z = 0 k -> PC PC -> TOS, k -> PC TOS -> PC k -> W, TOS -> PC TOS -> PC, 1 -> GIE 1 (2) 1 (2) 1 (2) 1 (2) 2 2 2 2 2 3 3 1, 2, 3 1, 2, 3 0 -> f(b) 1 -> f(b) 1 1 1,2 1,2 f -> d W+k -> W W+f -> d k-W -> W f-W -> d W AND k -> W W AND f -> d W AND f -> d W OR k -> W W OR f -> d W XOR k -> W W XOR f -> d f+1 -> f f-1 -> f C, DC, Z C, DC ,Z C, DC, Z C, DC, Z Z Z Z Z Z Z Z Z Z C C Z 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1, 2 1, 2 1, 2 1, 2 1, 2 1, 2 1, 2 1, 2 1, 2 1, 2 Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo] 1, 2

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

1/18

19/05/13
SLEEP Go into sleep mode

Chapter 9: Instruction Set - Book: PIC Microcontrollers


0 -> WDT, 1 -> TO, 0 -> PD TO, PD 1

Table9116FxxInstructionSet

*1WhenanI/Oregisterismodifiedasafunctionofitself,thevalueusedwillbethatvaluepresentonthepinsthemselves. *2IftheinstructionisexecutedontheTMRregisterandifd=1,theprescalerwillbecleared. *3IfthePCismodifiedortestresultislogicone(1),theinstructionrequirestwocycles.

DataTransferInstructions
DataTransferwithinthemicrocontrollertakesplacebetweenworkingregisterW(calledaccumulator)andaregisterwhichrepresentsany locationofinternalRAMregardlessofwhetheritisaboutspecialfunctionorgeneralpurposeregisters. FirstthreeinstructionsmoveliteraltoWregister(MOVLWstandsformoveLiteraltoW),movedatafromWregistertoRAMandfromRAMto Wregister(ortothesameRAMlocationwithchangeonflagZonly).InstructionCLRFclearsfregister,whereasCLRWclearsWregister. SWAPFinstructionswapsnibbleswithinfregister(onenibblecontainsfourbits).

ArithmeticlogicInstructions
Similartomostmicrocontrollers,PICsupportsonlytwoarithmeticinstructionsadditionandsubtraction.FlagsC,DC,Zareautomaticallyset dependingontheresultsofadditionorsubtraction.TheonlyexceptionistheflagC.Sincesubtractionisperformedasadditionwith negativevalue,theflagCisinvertedaftersubtraction.ItmeansthattheflagCissetifitispossibletoperformoperationandclearedifthe largernumberissubtractedfromsmallerone.Logicone(1)ofthePICisabletoperformoperationsAND,OR,EXOR,inverting(COMF)and rotation(RLFandRRF). InstructionswhichrotatearegisteractuallyrotateitsbitsthroughtheflagCbyonebitleft(towardbit7)orright(towardbit0).Thebitshifted fromtheregisterismovedtotheflagCwhichisautomaticallymovedtothebitontheoppositesideoftheregister.

BitorientedInstructions
InstructionsBCFandBSFclearorsetanybitinmemory.Althoughitseemstobeasimpleoperation,itisnotlikethat.CPUfirstreadsthe entirebyte,changesoneitsbitandrewritesthewholebytetothesamelocation.

ProgramControlInstructions
ThePIC16F887executesinstructionsGOTO,CALL,RETURNinthesamewayasallothermicrocontrollersdo.Adifferenceisthatstackis independentfrominternalRAMandhas8levels.TheRETLWkinstructionisidenticaltoRETURNinstruction,withexceptionthata constantdefinedbyinstructionoperandiswrittentotheWregisterpriortoreturnfromsubroutine.ThisinstructionenablesLookuptablesto beeasilycreatedbycreatingatableasasubroutineconsistingofRETLWkinstructions,wheretheliteralskbelongtothetable.Thenext stepistowritethepositionoftheliteralsk(0,1,2,3...n)toWregisterandcallthesubroutine(table)usingtheCALLinstruction.Tablebelow consistsofthefollowingliterals:k0,k1,k2...kn.

M a i n m o v l w 2 w r i t e n u m b e r 2 t o a c c u m u l a t o r c a l l L o o k u p j u m p t o t h e l o o k u p t a b l e L o o k u p a d d w f P C L , f a d d a c c u m u l a t o r a n d p r o g r a m c u r r e n t a d d r e s s ( P C L ) r e t l w k 0 r e t u r n f r o m s u b r o u t i n e ( a c c u m u l a t o r c o n t a i n s k 0 ) r e t l w k 1 . . . r e t l w k 2 . . . . . . . . . . . . . . . r e t l w k n r e t u r n f r o m s u b r o u t i n e ( a c c u m u l a t o r c o n t a i n s k n )

Thefirstlineofthesubroutine(instructionA D D W F P C L , f )simplyaddsaliteral"k"fromWregisterandtablestartaddresswhichisstoredin thePCLregister.Theresultisrealdataaddressinprogrammemory.Uponreturnfromthesubroutine,theWregisterwillcontainthe addressedliteralk.Inthiscase,itisthe"k2"literal. RETFIE(RETurnFromIntErrupt)representsareturnfrominterruptroutine.IncontrasttotheRETURNinstruction,itmayautomaticallyset theGIEbit(GlobalInterruptEnable).Whenaninterruptoccursthisbitisautomaticallycleared.Onlytheprogramcounterispushedtothe stack,whichmeansthatthereisnoautosaveofregistersstatusandthecurrentstatuseither.Theproblemissolvedbysavingstatusofall importantregistersatthebeginningofinterruptroutine.Thesevaluesareretrievedtotheseregistersimmediatelybeforeleavingthe interruptroutine. Conditionaljumpsareexecutedbytwoinstructions:BTFSCandBTFSS.Dependingonthestateofbitbeingtestedinthefregister,the followinginstructionwillbeskippedornot.

InstructionExecutionTime
Allinstructionsaresinglecycleinstructions.Theonlyexceptionmaybeconditionalbranchinstructions(ifconditionismet)orinstructions beingexecutedupontheprogramcounter.Inbothcases,twocyclesarerequiredforinstructionexecutionwherethesecondcycleis executedasaNOP(NoOperation).Asinglecycleinstructionconsistsoffourclockcycles.If4MHzoscillatorisused,anominaltimefor instructionexecutionis1S.Incaseofjump,theinstructionexecutiontimeis2S.

Instructions
Legend fAnymemorylocation(register) WWorkingregister(accumulator) bBitaddresswithinan8bitregister

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

2/18

19/05/13
dDestinationbit

Chapter 9: Instruction Set - Book: PIC Microcontrollers

[label]Setof8charactersindicatingstartofparticularaddressintheprogram TOSTopofstack []Option <>bitfieldinregister(severalbitaddresses) CCarry/BorrowbitoftheSTATUSregister DCDigitCarrybitoftheSTATUSregisterand ZZerobitoftheSTATUSregister. ADDLWAddliteralandW Syntax:[label]ADDLWk Description:ThecontentoftheregisterWisaddedtothe8bitliteralk.TheresultisstoredintheWregister. Operation:(W)+k>W Operand:0k255 Statusaffected:C,DC,Z Numberofcycles:1 EXAMPLE:

. . . . [ l a b e l ] A D D L W 0 x 1 5

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 0 A f t e r i n s t r u c t i o n : W = 0 x 2 5 C = 0 ( t h e r e s u l t i s n o t g r e a t e r t h a n 0 x F F , w h i c h m e a n s t h a t C a r r y h a s n o t o c c u r r e d ) .

ADDWFAddWandf Syntax:[label]ADDWFf,d Description:AddthecontentsoftheWandfregisters. Ifd=word=0theresultisstoredintheWregister. Ifd=ford=1theresultisstoredinregisterf. Operation:(W)+(f)>d Operand:0f127,d[0,1] Statusaffected:C,DC,Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] A D D W F R E G , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 R E G = 0 x C 2 A f t e r i n s t r u c t i o n : W = 0 x D 9 R E G = 0 x C 2 C = 0 ( N o c a r r y o c c u r s , i . e . t h e r e s u l t i s m a x i m u m 8 b i t l o n g ) .

EXAMPLE2:

. . . . [ l a b e l ] A D D W F I N D F , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 F S R = 0 x C 2 R e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 2 0 A f t e r i n s t r u c t i o n : W = 0 x 1 7 F S R = 0 x C 2 , R e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 3 7

ANDLWANDliteralwithW Syntax:[label]ANDLWk Description:ThecontentoftheregisterWisANDedwiththe8bitliteralk.Itmeansthattheresultwillcontainone(1)onlyifboth

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

3/18

19/05/13

Chapter 9: Instruction Set - Book: PIC Microcontrollers

correspondingbitsofoperandareones(1).TheresultisstoredintheWregister. Operation:(W)ANDk>W Operand:0k255 Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] A N D L W 0 x 5 F

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x A 3 1 0 1 0 0 0 1 1 ( 0 x A 3 ) 0 1 0 1 1 1 1 1 ( 0 x 5 F ) A f t e r i n s t r u c t i o n : W = 0 x 0 3 0 0 0 0 0 0 1 1 ( 0 x 0 3 ) Z = 0 ( r e s u l t i s n o t 0 )

EXAMPLE2:

. . . . [ l a b e l ] A N D L W 0 x 5 5

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x A A 1 0 1 0 1 0 1 0 ( 0 x A A ) 0 1 0 1 0 1 0 1 ( 0 x 5 5 ) A f t e r i n s t r u c t i o n : W = 0 x 0 0 0 0 0 0 0 0 0 0 ( 0 x 0 0 ) Z = 1 ( r e s u l t i s 0 )

ANDWFANDWwithf Syntax:[label]ANDWFf,d Description:ANDtheWregisterwithregisterf. Ifd=word=0,theresultisstoredintheWregister. Ifd=ford=1,theresultisstoredinregisterf. Operation:(W)AND(f)>d Operand:0f127,d[0,1] Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] A N D W F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 , R E G = 0 x C 2 0 0 0 1 0 1 1 1 ( 0 x 1 7 ) 1 1 0 0 0 0 1 0 ( 0 x C 2 ) A f t e r i n s t r u c t i o n : W = 0 x 1 7 , R E G = 0 x 0 2 0 0 0 0 0 0 1 0 ( 0 x 0 2 )

EXAMPLE2:

. . . . [ l a b e l ] A N D W F F S R , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 , F S R = 0 x C 2 0 0 0 1 0 1 1 1 ( 0 x 1 7 ) 1 1 0 0 0 0 1 0 ( 0 x C 2 ) A f t e r i n s t r u c t i o n : W = 0 x 0 2 , F S R = 0 x C 2 0 0 0 0 0 0 1 0 ( 0 x 0 2 )

BCFBitClearf

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

4/18

19/05/13
Syntax:[label]BCFf,b Description:Bitbofregisterfiscleared. Operation:(0)>f(b) Operand:0f127,0b7 Statusaffected: Numberofcycles:1 EXAMPLE1:

Chapter 9: Instruction Set - Book: PIC Microcontrollers

. . . . [ l a b e l ] B C F R E G , 7

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x C 7 1 1 0 0 0 1 1 1 ( 0 x C 7 ) A f t e r i n s t r u c t i o n : R E G = 0 x 4 7 0 1 0 0 0 1 1 1 ( 0 x 4 7 )

EXAMPLE2:

. . . . [ l a b e l ] B C F I N D F , 3

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 F S R = 0 x C 2 R e g i s t e r a t a d d r e s s ( F S R ) c o n t a i n s t h e v a l u e 0 x 2 F A f t e r i n s t r u c t i o n : W = 0 x 1 7 F S R = 0 x C 2 R e g i s t e r a t a d d r e s s ( F S R ) c o n t a i n s t h e v a l u e 0 x 2 7

BSFBitsetf Syntax:[label]BSFf,b Description:Bitbofregisterfisset. Operation:1>f(b) Operand:0f127,0b7 Statusaffected: Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] B S F R E G , 7

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x 0 7 0 0 0 0 0 1 1 1 ( 0 x 0 7 ) A f t e r i n s t r u c t i o n : R E G = 0 x 8 7 1 0 0 0 0 1 1 1 ( 0 x 8 7 )

EXAMPLE2:

. . . . [ l a b e l ] B S F I N D F , 3

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 F S R = 0 x C 2 R e g i s t e r a t a d d r e s s ( F S R ) c o n t a i n s t h e v a l u e 0 x 2 0 A f t e r i n s t r u c t i o n : W = 0 x 1 7 F S R = 0 x C 2 R e g i s t e r a t a d d r e s s ( F S R ) c o n t a i n s t h e v a l u e 0 x 2 8

BTFSCBittestf,SkipifClear Syntax:[label]BTFSCf,b Description:Ifbitbofregisterfis0,thenextinstructionisdiscardedandaNOPisexecutedinstead,makingthisatwocycleinstruction.

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

5/18

19/05/13
Operation:Discardthenextinstructioniff(b)=0 Operand:0f127,0b7 Statusaffected: Numberofcycles:1or2dependingonbitb EXAMPLE:

Chapter 9: Instruction Set - Book: PIC Microcontrollers

. . . . L A B _ 0 1 B T F S C R E G , 1 T e s t b i t 1 o f R E G L A B _ 0 2 . . . . S k i p t h i s l i n e i f b i t = 1 L A B _ 0 3 . . . . J u m p h e r e i f b i t = 0

B e f o r e i n s t r u c t i o n e x e c u t i o n : T h e p r o g r a m c o u n t e r w a s a t a d d r e s s L A B _ 0 1 . A f t e r i n s t r u c t i o n : i f b i t 1 o f R E G i s c l e a r e d , p r o g r a m c o u n t e r p o i n t s t o a d d r e s s L A B _ 0 3 . i f b i t 1 o f R E G i s s e t , p r o g r a m c o u n t e r p o i n t s t o a d d r e s s L A B _ 0 2 .

BTFSSBittestf,SkipifSet Syntax:[label]BTFSSf,b Description:Ifbitbofregisterfis1,thenextinstructionisdiscardedandaNOPisexecutedinstead,makingthisatwocycleinstruction. Operation:Discardthenextinstructioniff(b)=1 Operand:0f127,0b7 Statusaffected: Numberofcycles:1or2dependingonbitb EXAMPLE:

. . . . L A B _ 0 1 B T F S S R E G , 3 T e s t b i t 3 o f R E G L A B _ 0 2 . . . . S k i p t h i s l i n e i f b i t = 0 L A B _ 0 3 . . . . J u m p h e r e i f b i t = 1

B e f o r e i n s t r u c t i o n e x e c u t i o n : T h e p r o g r a m c o u n t e r w a s a t a d d r e s s L A B _ 0 1 A f t e r i n s t r u c t i o n : i f b i t 3 o f R E G i s c l e a r e d , p r o g r a m c o u n t e r p o i n t s t o a d d r e s s L A B _ 0 3 . i f b i t 3 o f R E G i s c l e a r e d , p r o g r a m c o u n t e r p o i n t s t o a d d r e s s L A B _ 0 2 .

CALLCallsSubroutine Syntax:[label]CALLk Description:Callssubroutine.Firsttheaddressofthenextinstructiontoexecuteispushedontothestack.ItisthePC+1address. Afterwards,thesubroutineaddressiswrittentotheprogramcounter. Operation:(PC)+1>(TopOfStackTOS) k>PC(10:0),(PCLATH(4:3))>PC(12:11) Operand:0k2047 Flag: Statusaffected:2 EXAMPLE:

. . . . L A B _ 0 1 C A L L L A B _ 0 2 C a l l s u b r o u t i n e L A B _ 0 2 . . . . . . . . L A B _ 0 2 . . . .

B e f o r e i n s t r u c t i o n e x e c u t i o n : P C = a d d r e s s L A B _ 0 1 T O S ( t o p o f s t a c k ) = x A f t e r i n s t r u c t i o n : P C = a d d r e s s L A B _ 0 2 T O S ( t o p o f s t a c k ) = L A B _ 0 1

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

6/18

19/05/13
CLRFClearf Syntax:[label]CLRFf

Chapter 9: Instruction Set - Book: PIC Microcontrollers

Description:ThecontentofregisterfisclearedandtheZflagoftheSTATUSregisterisset. Operation:0>f Operand:0f127 Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] C L R F T R I S B

B e f o r e i n s t r u c t i o n e x e c u t i o n : T R I S B = 0 x F F A f t e r i n s t r u c t i o n : T R I S B = 0 x 0 0 Z = 1

EXAMPLE2:

B e f o r e i n s t r u c t i o n e x e c u t i o n : F S R = 0 x C 2 R e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 3 3 A f t e r i n s t r u c t i o n : F S R = 0 x C 2 R e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 0 0 Z = 1

CLRWClearW Syntax:[label]CLRW Description:RegisterWisclearedandtheZflagoftheSTATUSregisterisset. Operation:0>W Operand: Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] C L R W

B e f o r e i n s t r u c t i o n : W = 0 x 5 5 A f t e r i n s t r u c t i o n : W = 0 x 0 0 Z = 1

CLRWDTClearWatchdogTimer Syntax:[label]CLRWDT Description:ResetsthewatchdogtimerandtheWDTprescaler.StatusbitsTOandPDareset. Operation:0>WDT0>WDTprescaler1>TO1>PD Operand: Statusaffected:TO,PD Numberofcycles:1 EXAMPLE:

. . . . [ l a b e l ] C L R W D T

B e f o r e i n s t r u c t i o n e x e c u t i o n : W D T c o u n t e r = x W D T p r e s c a l e r = 1 : 1 2 8

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

7/18

19/05/13

Chapter 9: Instruction Set - Book: PIC Microcontrollers

A f t e r i n s t r u c t i o n : W D T c o u n t e r = 0 x 0 0 W D T p r e s c a l e r = 0 T O = 1 P D = 1 W D T p r e s c a l e r = 1 : 1 2 8

COMFComplementf Syntax:[label]COMFf,d Description:Thecontentofregisterfiscomplemented(logiczeros(0)arereplacedbyones(1)andviceversa).Ifd=word=0theresultis storedinW.Ifd=ford=1theresultisstoredinregisterf. Operation:(f)>d Operand:0f127,d[0,1] Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] C O M F R E G , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x 1 3 0 0 0 1 0 0 1 1 ( 0 x 1 3 ) c o m p l e m e n t i n g A f t e r i n s t r u c t i o n : R E G = 0 x 1 3 1 1 1 0 1 1 0 0 ( 0 x E C ) W = 0 x E C

EXAMPLE2:

. . . . [ l a b e l ] C O M F I N D F , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : F S R = 0 x C 2 R e g i s t e r a t a d d r e s s ( F S R ) c o n t a i n s t h e v a l u e 0 x A A A f t e r i n s t r u c t i o n : F S R = 0 x C 2 R e g i s t e r a t a d d r e s s ( F S R ) c o n t a i n s t h e v a l u e 0 x 5 5

DECFDecrementf Syntax:[label]DECFf,d Description:Decrementregisterfbyone.Ifd=word=0,theresultisstoredintheWregister.Ifd=ford=1,theresultisstoredinregister f. Operation:(f)1>d Operand:0f127,d[0,1] Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] D E C F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x 0 1 Z = 0 A f t e r i n s t r u c t i o n : R E G = 0 x 0 0 Z = 1

EXAMPLE2:

. . . . [ l a b e l ] D E C F R E G , w

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

8/18

19/05/13

Chapter 9: Instruction Set - Book: PIC Microcontrollers

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x 1 3 W = x , Z = 0 A f t e r i n s t r u c t i o n : R E G = 0 x 1 3 W = 0 x 1 2 , Z = 0

DECFSZDecrementf,Skipif0 Syntax:[label]DECFSZf,d Description:Decrementregisterfbyone.Ifd=word=0,theresultisstoredintheWregister.Ifd=ford=1,theresultisstoredinregister f.Iftheresultis0,thenaNOPisexecutedinstead,makingthisatwocycleinstruction. Operation:(f)1>d Operand:0f127,d[0,1] Statusaffected: Numberofcycles:1or2dependingontheresult. EXAMPLE1:

. . . . M O V L W . 1 0 M O V W F C N T 1 0 > C N T L o o p . . . . . . . . . . . . I n s t r u c t i o n b l o c k . . . . . . D E C F S Z C N T , f d e c r e m e n t R E G b y o n e G O T O L o o p S k i p t h i s l i n e i f = 0 L A B _ 0 3 . . . . . . . J u m p h e r e i f = 0

Inthisexample,instructionblockisexecutedasmanytimesastheinitialvalueofthevariableCNTis,whichinthisexampleis10. GOTOUnconditionalBranch Syntax:[label]GOTOk Description:Unconditionaljumptotheaddressk. Operation:(k)>PC(10:0),(PCLATH(4:3))>PC(12:11) Operand:0k2047 Statusaffected: Numberofcycles:2 EXAMPLE:

. . . . L A B _ 0 0 G O T O L A B _ 0 1 J u m p t o L A B _ 0 1 . . . . . . . . . . L A B _ 0 1 . . . . . P r o g r a m c o n t i n u e s f r o m h e r e

B e f o r e i n s t r u c t i o n e x e c u t i o n : P C = L A B _ 0 0 a d d r e s s A f t e r i n s t r u c t i o n : P C = L A B _ 0 1 a d d r e s s

INCFIncrementf Syntax:[label]INCFf,d Description:Incrementregisterfbyone. Ifd=word=0,theresultisstoredinregisterW. Ifd=ford=1,theresultisstoredinregisterf. Operation:(f)+1>d Operand:0f127,d[0,1] Statusaffected:Z Numberofcycles:1 EXAMPLE1:

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

9/18

19/05/13
. . . . [ l a b e l ] I N C F R E G , w

Chapter 9: Instruction Set - Book: PIC Microcontrollers

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x 1 0 W = x , Z = 0 A f t e r i n s t r u c t i o n : R E G = 0 x 1 0 W = 0 x 1 1 , Z = 0

EXAMPLE2:

. . . . [ l a b e l ] I N C F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x F F Z = 0 A f t e r i n s t r u c t i o n : R E G = 0 x 0 0 Z = 1

INCFSZIncrementf,Skipif0 Syntax:[label]INCFSZf,d Description:Registerfisincrementedbyone.Ifd=word=0,theresultisstoredinregisterW.Ifd=ford=1,theresultisstoredin registerf.Iftheresultis0,thenaNOPisexecutedinstead,makingthisatwocycleinstruction. Operation:(f)+1>d Operand:0f127,d[0,1] Statusaffected: Numberofcycles:1or2dependingontheresult. EXAMPLE:

. . . . L A B _ 0 1 I N C F S Z R E G , f I n c r e m e n t R E G b y o n e L A B _ 0 2 . . . . . . . S k i p t h i s l i n e i f r e s u l t i s 0 L A B _ 0 3 . . . . . . . J u m p h e r e i f r e s u l t i s 0

ThecontentofprogramcounterBeforeinstructionexecution,PC=LAB_01address. ThecontentofREGafterinstruction,REG=REG+1.IfREG=0,theprogramcounterpointstotheaddressoflabelLAB_03.Otherwise,the programcounterpointstoaddressofthenextinstruction,i.e.toLAB_02address. IORLWInclusiveORliteralwithW Syntax:[label]IORLWk Description:ThecontentoftheWregisterisORedwiththe8bitliteralk.TheresultisstoredinregisterW. Operation:(W)OR(k)>W Operand:0k255 Statusaffected: Numberofcycles:1 EXAMPLE:

. . . . [ l a b e l ] I O R L W 0 x 3 5

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 9 A A f t e r i n s t r u c t i o n : W = 0 x B F Z = 0

IORWFInclusiveORWwithf Syntax:[label]IORWFf,d Description:ThecontentofregisterfisORedwiththecontentofWregister.Ifd=word=0,theresultisstoredintheWregister.Ifd=for

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

10/18

19/05/13
d=1,theresultisstoredinregisterf. Operation:(W)OR(f)>d Operand:0f127,d>[0,1] Statusaffected:Z Numberofcycles:1 EXAMPLE1:

Chapter 9: Instruction Set - Book: PIC Microcontrollers

. . . . [ l a b e l ] I O R W F R E G , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x 1 3 , W = 0 x 9 1 A f t e r i n s t r u c t i o n : R E G = 0 x 1 3 , W = 0 x 9 3 Z = 0

EXAMPLE2:

. . . . [ l a b e l ] I O R W F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x 1 3 , W = 0 x 9 1 A f t e r i n s t r u c t i o n : R E G = 0 x 9 3 , W = 0 x 9 1 Z = 0

MOVFMovef Syntax:[label]MOVFf,d Description:Thecontentofregisterfismovedtoadestinationdeterminedbytheoperandd.Ifd=word=0,thecontentismovedto registerW.Ifd=ford=1,thecontentremainsinregisterf.Optiond=1isusedtotestthecontentofregisterfbecausethisinstruction affectstheZflagoftheSTATUSregister. Operation:(f)>d Operand:0f127,d>[0,1] Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] M O V F F S R , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : F S R = 0 x C 2 W = 0 x 0 0 A f t e r i n s t r u c t i o n : W = 0 x C 2 Z = 0

EXAMPLE2:

. . . . [ l a b e l ] M O V F I N D F , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 F S R = 0 x C 2 , r e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 0 0 A f t e r i n s t r u c t i o n : W = 0 x 1 7 F S R = 0 x C 2 , r e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 0 0 , Z = 1

MOVLWMoveliteraltoW Syntax:[label]MOVLWk

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

11/18

19/05/13
Description:8bitliteralkismovedtoregisterW. Operation:k>(W) Operand:0k255 Statusaffected: Numberofcycles:1 EXAMPLE1:

Chapter 9: Instruction Set - Book: PIC Microcontrollers

. . . . [ l a b e l ] M O V L W 0 x 5 A

A f t e r i n s t r u c t i o n : W = 0 x 5 A

EXAMPLE2:

C o n s t e q u 0 x 4 0 [ l a b e l ] M O V L W C o n s t

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 0 A f t e r i n s t r u c t i o n : W = 0 x 4 0

MOVWFMoveWtof Syntax:[label]MOVWFf Description:ThecontentofregisterWismovedtoregisterf. Operation:(W)>f Operand:0f127 Statusaffected: Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] M O V W F O P T I O N _ R E G

B e f o r e i n s t r u c t i o n e x e c u t i o n : O P T I O N _ R E G = 0 x 2 0 W = 0 x 4 0 A f t e r i n s t r u c t i o n : O P T I O N _ R E G = 0 x 4 0 W = 0 x 4 0

EXAMPLE2:

. . . . [ l a b e l ] M O V W F I N D F

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 1 7 F S R = 0 x C 2 , r e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 0 0 A f t e r i n s t r u c t i o n : W = 0 x 1 7 F S R = 0 x C 2 , r e g i s t e r a t a d d r e s s 0 x C 2 c o n t a i n s t h e v a l u e 0 x 1 7

NOPNoOperation Syntax:[label]NOP Description:Nooperation. Operation: Operand: Statusaffected: Numberofcycles:1

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

12/18

19/05/13
EXAMPLE:

Chapter 9: Instruction Set - Book: PIC Microcontrollers

. . . . [ l a b e l ] N O P 1 u s d e l a y ( o s c i l l a t o r 4 M H z )

B e f o r e i n s t r u c t i o n e x e c u t i o n : P C = x A f t e r i n s t r u c t i o n : P C = x + 1

RETFIEReturnfromInterrupt Syntax:[labels]RETFIE Description:Returnfromsubroutine.Thevalueispoppedfromthestackandloadedtotheprogramcounter.Interruptsareenabledby settingthebitGIEoftheINTCONregister. Operation:TOS>PC,1>GIE Operand: Statusaffected: Numberofcycles:2 EXAMPLE:

. . . . [ l a b e l ] R E T F I E

B e f o r e i n s t r u c t i o n e x e c u t i o n : P C = x G I E ( i n t e r r u p t e n a b l e b i t o f t h e S A T U S r e g i s t e r ) = 0 A f t e r i n s t r u c t i o n : P C = T O S ( t o p o f s t a c k ) G I E = 1

RETLWReturnwithliteralinW Syntax:[label]RETLWk Description:8bitliteralkisloadedintoregisterW.Thevaluefromthetopofstackisloadedtotheprogramcounter. Operation:(k)>Wtopofstack(TOP)>PC Operand: Statusaffected: Numberofcycles:2 EXAMPLE:

. . . . [ l a b e l ] R E T L W 0 x 4 3

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = x P C = x T O S ( t o p o f s t a c k ) = x A f t e r i n s t r u c t i o n : W = 0 x 4 3 P C = T O S ( t o p o f s t a c k ) T O S ( t o p o f s t a c k ) = T O S 1

RETURNReturnfromSubroutine Syntax:[label]RETURN Description:Returnfromsubroutine.Thevaluefromthetopofstackisloadedtotheprogramcounter.Thisisatwocycleinstruction. Operation:TOS>programcounterPC. Operand: Statusaffected: Numberofcycles:2 EXAMPLE:

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

13/18

19/05/13
. . . . [ l a b e l ] R E T U R N

Chapter 9: Instruction Set - Book: PIC Microcontrollers

B e f o r e i n s t r u c t i o n e x e c u t i o n : P C = x T O S ( t o p o f s t a c k ) = x A f t e r i n s t r u c t i o n : P C = T O S ( t o p o f s t a c k ) T O S ( t o p o f s t a c k ) = T O S 1

RLFRotateLeftfthroughCarry Syntax:[label]RLFf,d Description:ThecontentofregisterfisrotatedonebittotheleftthroughtheCarryflag.Ifd=word=0,theresultisstoredinregisterW.Ifd =ford=1,theresultisstoredinregisterf. Operation:(f(n))>d(n+1),f(7)>C,C>d(0) Operand:0f127,d[0,1] Statusaffected:C Numberofcycles:1

Fig.91fRegister

EXAMPLE1:

. . . . [ l a b e l ] R L F R E G , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 1 1 1 0 0 1 1 0 C = 0 A f t e r i n s t r u c t i o n : R E G = 1 1 1 0 0 1 1 0 W = 1 1 0 0 1 1 0 0 C = 1

EXAMPLE2:

. . . . [ l a b e l ] R L F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 1 1 1 0 0 1 1 0 C = 0 A f t e r i n s t r u c t i o n : R E G = 1 1 0 0 1 1 0 0 C = 1

RRFRotateRightfthroughCarry Syntax:[label]RRFf,d Description:ThecontentofregisterfisrotatedonebitrightthroughtheCarryflag.Ifd=word=0,theresultisstoredinregisterW.Ifd=f ord=1,theresultisstoredinregisterf. Operation:(f(n))>d(n1),f(0)>C,C>d(7) Operand:0f127,d>[0,1] Statusaffected:C Numberofcycles:1

Fig.92fRegister

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

14/18

19/05/13
EXAMPLE1:

Chapter 9: Instruction Set - Book: PIC Microcontrollers

. . . . [ l a b e l ] R R F R E G , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 1 1 1 0 0 1 1 0 W = x C = 0 A f t e r i n s t r u c t i o n : R E G = 1 1 1 0 0 1 1 0 W = 0 1 1 1 0 0 1 1 C = 0

EXAMPLE2:

. . . . [ l a b e l ] R R F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 1 1 1 0 0 1 1 0 , C = 0 A f t e r i n s t r u c t i o n : R E G = 0 1 1 1 0 0 1 1 , C = 0

SLEEPEnterSleepmode Syntax:[label]SLEEP Description:Theprocessorenterssleepmode.Theoscillatorisstopped.PDbit(PowerDown)oftheSTATUSregisteriscleared.TObitof thesameregisterisset.TheWDTanditsprescalerarecleared. Operation:0>WDT,0>WDTprescaler,1>TO,0>PD Operand: Statusaffected:TO,PD Numberofcycles:1 EXAMPLE:

. . . . [ l a b e l ] S L E E P

B e f o r e i n s t r u c t i o n e x e c u t i o n : W D T c o u n t e r = x W D T p r e s c a l e r = x A f t e r i n s t r u c t i o n : W D T c o u n t e r = 0 x 0 0 W D T p r e s c a l e r = 0 T O = 1 P D = 0

SUBLWSubtractWfromliteral Syntax:[label]SUBLWk Description:ThecontentofregisterWissubtractedfromtheliteralk.TheresultisstoredinregisterW. Operation:k(W)>W Operand:0k255 Statusaffected:C,DC,Z Numberofcycles:1 EXAMPLE:

. . . . [ l a b e l ] S U B L W 0 x 0 3

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 0 1 , C = x , Z = x A f t e r i n s t r u c t i o n : W = 0 x 0 2 , C = 1 , Z = 0 r e s u l t i s p o s i t i v e B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 0 3 , C = x , Z = x A f t e r i n s t r u c t i o n : W = 0 x 0 0 , C = 1 , Z = 1 r e s u l t i s 0

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

15/18

19/05/13

Chapter 9: Instruction Set - Book: PIC Microcontrollers

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x 0 4 , C = x , Z = x A f t e r i n s t r u c t i o n : W = 0 x F F , C = 0 , Z = 0 r e s u l t i s n e g a t i v e

SUBWFSubtractWfromf Syntax:[label]SUBWFf,d Description:ThecontentofregisterWissubtractedfromregisterf. Ifd=word=0,theresultisstoredinregisterW.Ifd=ford=1,theresultisstoredinregisterf. Operation:(f)(W)>d Operand:0f127,d[0,1] Statusaffected:C,DC,Z Numberofcycles:1 EXAMPLE:

. . . . [ l a b e l ] S U B W F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 3 , W = 2 , C = x , Z = x A f t e r i n s t r u c t i o n : R E G = 1 , W = 2 , C = 1 , Z = 0 r e s u l t i s p o s i t i v e B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 2 , W = 2 , C = x , Z = x A f t e r i n s t r u c t i o n : R E G = 0 , W = 2 , C = 1 , Z = 1 r e s u l t i s 0 B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 1 , W = 2 , C = x , Z = x A f t e r i n s t r u c t i o n : R E G = 0 x F F , W = 2 , C = 0 , Z = 0 r e s u l t i s n e g a t i v e

SWAPFSwapNibblesinf Syntax:[label]SWAPFf,d Description:Theupperandlowernibblesofregisterfareswapped.Ifd=word=0,theresultisstoredinregisterW.Ifd=ford=1,the resultisstoredinregisterf. Operation:f(0:3)>d(4:7),f(4:7)>d(0:3) Operand:0f127,d[0,1] Statusaffected: Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] S W A P F R E G , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x F 3 A f t e r i n s t r u c t i o n : R E G = 0 x F 3 W = 0 x 3 F

EXAMPLE2:

. . . . [ l a b e l ] S W A P F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x F 3 A f t e r i n s t r u c t i o n : R E G = 0 x 3 F

XORLWExclusiveORliteralwithW Syntax:[label]XORLWk Description:ThecontentofregisterWisXORedwiththe8bitliteralk.TheresultisstoredinregisterW. Operation:(W).XOR.k>W Operand:0k255

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

16/18

19/05/13
Statusaffected:Z Numberofcycles:1 EXAMPLE1:

Chapter 9: Instruction Set - Book: PIC Microcontrollers

. . . . [ l a b e l ] X O R L W 0 x A F

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x B 5 1 0 1 1 0 1 0 1 ( 0 x B 5 ) 1 0 1 0 1 1 1 1 ( 0 x A F ) A f t e r i n s t r u c t i o n : W = 0 x 1 A 0 0 0 1 1 0 1 0 ( 0 x 1 A ) Z = 0

EXAMPLE2:

C o n s t e q u 0 x 3 7 [ l a b e l ] X O R L W C o n s t

B e f o r e i n s t r u c t i o n e x e c u t i o n : W = 0 x A F 1 0 1 0 1 1 1 1 ( 0 x A F ) C o n s t = 0 x 3 7 0 0 1 1 0 1 1 1 ( 0 x 3 7 ) A f t e r i n s t r u c t i o n : W = 0 x 9 8 1 0 0 1 1 0 0 0 ( 0 x 9 8 ) Z = 0

XORWFExclusiveORWwithf Syntax:[label]XORWFf,d Description:ThecontentofregisterfisXORedwiththecontentofregisterW.Abitofresultissetonlyifthecorrespondingbitsofoperands aredifferent.Ifd=word=0,theresultisstoredinregisterW.Ifd=ford=1,theresultisstoredinregisterf. Operation:(W).XOR.k>d Operand:0f127,d[0,1] Statusaffected:Z Numberofcycles:1 EXAMPLE1:

. . . . [ l a b e l ] X O R W F R E G , f

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x A F , W = 0 x B 5 1 0 1 0 1 1 1 1 ( 0 x A F ) 1 0 1 1 0 1 0 1 ( 0 x B 5 ) A f t e r i n s t r u c t i o n : R E G = 0 x 1 A , W = 0 x B 5 0 0 0 1 1 0 1 0 ( 0 x 1 A )

EXAMPLE2:

. . . . [ l a b e l ] X O R W F R E G , w

B e f o r e i n s t r u c t i o n e x e c u t i o n : R E G = 0 x A F , W = 0 x B 5 1 0 1 0 1 1 1 1 ( 0 x A F ) 1 0 1 1 0 1 0 1 ( 0 x B 5 ) A f t e r i n s t r u c t i o n : R E G = 0 x A F , W = 0 x 1 A 0 0 0 1 1 0 1 0 ( 0 x 1 A )

Inadditiontotheprecedinginstructions,Microchiphasalsointroducedsomeotherinstructions.Tobemoreprecise,theyarenot instructionsassuch,butmacrossupportedbyMPLAB.Microchipcallsthem"SpecialInstructions"sinceallofthemareinfactobtainedby combiningalreadyexistinginstructions.


INST RUCT IO N ADDCF f,d DESCRIPT IO N Add with carry EQ UIVAL ENT INST RUCT IO N BTFSC INCF BTFSC ST AT USAF F ECT ED STATUS,C

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

17/18

19/05/13
ADDDCF B BC BDC BNC BNDC BNZ BZ CLRC CLRDC CLRZ MOVFW SETC SETDC SETZ SKPC SKPDC SKPNC SKPNDC SKPNZ SKPZ SUBCF SUBDCF TSTF f, d f, d f f f f,d k k k k k k k Add with Digit Carry Branch Branch on Carry Branch on Digit Carry Branch on No Carry

Chapter 9: Instruction Set - Book: PIC Microcontrollers


INCF GOTO BTFSC GOTO BTFSC GOTO BTFSS GOTO BTFSS GOTO BTFSS GOTO BTFSC GOTO BCF BCF BCF MOVF BSF BSF BSF BTFSS BTFSS BTFSC BTFSC BTFSC BTFSS BTFSC DECF BTFSC DECF MOVF STATUS,C STATUS,DC STATUS,Z STATUS,C STATUS,DC STATUS,Z STATUS,DC STATUS,Z STATUS,Z STATUS,C STATUS,DC STATUS,C STATUS,DC STATUS,C STATUS,DC STATUS,Z STATUS,Z STATUS,C STATUS,DC STATUS,Z STATUS,DC

Branch on No Digit Carry Branch on No Zero Branch on Zero Clear Carry Clear Digit Carry Clear Zero Move File to W Set Carry Set Digit Carry Set Zero Skip on Carry Skip on Digit Carry Skip on No Carry Skip on No Digit Carry Skip on Non Zero Skip on Zero Subtract Carry from File Subtract Digit Carry from File Test File

previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/10/chapter-9-instruction-set/

18/18

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers


Products Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

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.Assemblylanguageisunderstandableforhumansbecauseitconsistsofmeaningful wordsandsymbolsofthealphabet.Letustake,forexamplethecommand"RETURN"whichis,asitsnameindicates,usedtoreturnthe microcontrollerfromasubroutine.Inmachinecode,thesamecommandisrepresentedbya14bitarrayofzerosandonesunderstandable bythemicrocontroller.Allassemblylanguagecommandsaresimilarlycompiledintothecorrespondingarrayofzerosandones.Adatafile usedforstoringcompiledprogramiscalledan"executivefile",i.e."HEXdatafile".Thenamecomesfromthehexadecimalpresentationofa datafileandhasasuffixof"hex"aswell,forexample"probe.hex".Afterhasbeengenerated,thedatafileisloadedintothemicrocontroller usingaprogrammer.Assemblylanguageprogramsmaybewritteninanyprogramfortextprocessing(editor)abletocreateASCIIdatafiles onaharddiscorinaspecializedworkenvironmentsuchasMPLABdescribedlater.

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

ELEMENTSOFASSEMBLYLANGUAGE
Aprogramwritteninassemblylanguageconsistsofseveralelementsbeingdifferentlyinterpretedwhilecompilingtheprogramintoan executabledatafile.Theuseoftheseelementsrequiresstrictrulesanditisnecessarytopayspecialattentiontothemduringprogram writinginordertoavoiderrors.

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

ASSEMBLYLANGUAGESYNTAX
Asmentioned,itisnecessarytoobservesomespecificrulesinordertoenabletheprocessofcompilingintoexecutiveHEXcodetorun withouterrors.Compulsoryrulesexplaininghowsequencesofexpressionsareputtogethertoformthestatementsthatmakeupan assemblylanguageprogramarecalledsyntax.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.

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

1/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

COMMENTS
Acommentisoftenanexplanatorytextwrittenbytheprogrammerinordertomakeaprogramclearerandeasiertounderstand.Itisnot necessarytocommenteveryline.Whenthreeorfourlinesofcodeworktogethertoaccomplishsomehigherleveltask,itisbettertohavea singlehigherlevelcommentforthegroupoflines.Therefore,itisaddedifneededandhastostartwith"".Commentsaddedtoassembly sourcecodearenotcompiledintomachinecode.

INSTRUCTIONS
Instructionsaredefinedforeachmicrocontrollerfamilybythemanufacturer.Therefore,itisuptotheusertofollowtherulesoftheirusage. Thewayofwritinginstructionsisalsocalledinstructionsyntax.Theinstructions"m o v l p "and"g o t t o ",inthefollowingexample,are recognizedbythePIC16F887microcontrollerasanerrorsincetheyarenotcorrectlywritten.

OPERANDS
Anoperandisavalue(anargument)uponwhichtheinstruction,namedbymnemonic,operates.Theoperandsmaybearegister,a variable,aliteralconstant,alabeloramemoryaddress.

DIRECTIVES
Unlikeinstructionsbeingwrittentoonchipprogrammemoryaftercompilation,directivesarecommandsofassemblylanguageitselfanddo notdirectlyaffecttheoperationofthemicrocontroller.Someofthemmustbeusedineveryprogramwhileothersareonlyusedtofacilitate orenhancetheoperation.Directivesarewrittentothecolumnreservedforinstructions.Therulewhichmustbeobservedallowsonlyone directiveperprogramline. Thissectioncoversonlyafewofthemostcommonlyuseddirectives.Itwouldcertainlytakeuptoomuchspaceandtimetodescribeallthe directivesrecognizedbytheMPLABprogram.Anyway,acompletelistcontainingalldirectiveswhichtheMPLABassemblercan understandisprovidedinHelp.

PROCESSORDirective

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

2/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

Thisdirectivemustbewrittenatthebeginningofeachprogram.Itdefinesthetypeofthemicrocontrollerwhichtheprogramiswrittenfor.For example:

P r o c e s s o r 1 6 f 8 8 7

EQUdirective
Thisdirectiveisusedtoreplaceanumericvaluebyasymbol.Inthisway,someaspecificlocationinmemoryisassignedaname.For example:

M A X I M U M E Q U H 2 5

Thismeansthatamemorylocationataddress25(hex.)isassignedthename"MAXIMUM".Everyappearanceofthelabel"MAXIMUM"in theprogramwillbeinterpretedbytheassemblerastheaddress25(MAXIMUM=H25).Symbolsmaybedefinedthiswayonlyonceina program.Thatthisdirectiveismostlyusedatthebeginningoftheprogram.

ORGdirective
Thisdirectivespecifiesalocationinprogrammemorywheretheprogramfollowingdirectiveistobeplaced.Forexample:

O R G 0 x 1 0 0 S T A R T . . . . . . . . . O R G 0 x 1 0 0 0 T A B L E . . . . . .

Thisprogramstartsatlocation0x100.Thetablecontainingdataistobestoredatlocation1024(1000h).

ENDdirective
Eachprogrammustbeendedbyusingthisdirective.Onceaprogramencountersthisdirective,theassemblerimmediatelystopscompiling. Forexample:

. . . E N D E n d o f p r o g r a m

\$INCLUDEdirective
Thenameofthisdirectivefullyindicatesitspurpose.Duringcompiling,itenablestheassemblertousedatacontainedinanotherfileona computerharddisc.Forexample:

. . . # i n c l u d e < p 1 6 f 8 8 7 . i n c >

CBLOCKandENDCdirectives
Allvariables(theirnamesandaddresses)thatwillbeusedinaprogrammustbedefinedatthebeginningoftheprogram.Becauseofthisit isnotnecessarytospecifytheaddressofeachspecifiedvariablelaterintheprogram.Instead,itisenoughtospecifytheaddressofthefirst onebyusingdirectiveCBLOCKandlistallothersafterwards.Thecompilerautomaticallyassignsthesevariablesthecorresponding addressesaspertheordertheyarelisted.Lastly,thedirectiveENDCindicatestheendofthelistofvariables.

C B L O C K 0 x 2 0 S T A R T a d d r e s s 0 x 2 0 R E L E a d d r e s s 0 x 2 1 S T O P a d d r e s s 0 x 2 2 L E F T a d d r e s s 0 x 2 3 R I G H T a d d r e s s 0 x 2 4 E N D C . . .

IF,ENDIFandELSEdirectives
Thesedirectivesareusedtocreatesocalledconditionalblocksinaprogram.EachoftheseblocksstartswiththedirectiveIFandendswith thedirectiveENDIForELSE.Astatementorasymbol(inparentheses)followingthedirectiveIFrepresentsaconditionwhichdetermines whichpartoftheprogramistobecompiled:

Ifthestatementiscorrectorthevalueofasymbolisequaltoone,programcompilesallinstructionswrittenbefore directiveELSEorENDIFand Ifthestatementisnotcorrectorthevalueofasymbolisequaltozero,onlyinstructionswrittenafterdirectivesELSE orENDIFaretobecompiled.

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

3/16

19/05/13
Example1:

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

I F ( V E R S I O N > 3 ) C A L L T a b l e _ 2 C A L L E N D I F . . .

Iftheprogramisreleasedaftertheversion3(statementisright)thensubroutines"Table2"and"Extension"areexecuted.Ifthestatementin parenthesesiswrong(VERSION<3),twoinstructionscallingsubroutinesareignoredandwillnotbecompiledtherefore. Example2: Ifthevalueofsymbol"Model"isequaltoonethenfirsttwoinstructionsafterdirectiveIFarecompiledaswellasinstructionsafterdirective ENDIF(allinstructionsbetweenELSEandENDIFareignored).Otherwise,ifModel=0theninstructionsbetweenIFandELSEareignored, whereasinstructionsafterdirectiveELSEarecompiled.

I F ( M o d e l ) M O V F W B U F F E R M O V W F M A X I M U M E L S E M O V F W B U F F E R 1 M O V W F M A X I M U M E N D I F . . .

BANKSELdirective
InordertoaccessanSFRregisteritisnecessarytoselecttheappropriatebankinRAMmemorybyusingbitsRP0andRP1oftheSTATUS register.Thisdirectiveisusedinthiscase.Simply,since"inc"datafilecontainsthelistofallregistersalongwiththeiraddresses,the assemblerknowswhichbankcorrespondstowhichregister.Afterencounteringthisdirective,assemblerselectsthebitsRP0andRP1for thespecifiedregisteronitsown.Forexample:

. . . B A N K S E L T R I S B C L R F T R I S B M O V L W B 0 1 0 0 1 1 0 1 B A N K S E L P O R T B M O V W F P O R T B . . .

EXAMPLEOFHOWTOWRITEAPROGRAM
Thefollowingexampleillustrateswhatasimpleprogramwritteninassemblylanguagelookslike.

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

4/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

Apartfromtheregularrulesofassemblylanguage,therearealsosomeunwrittenruleswhichshouldbeobservedduringprogramwriting. Oneofthemistowriteinafewwordsatthebeginningofaprogramwhattheprogramsnameis,whatitisusedfor,version,releasedate, typeofthemicrocontrolleritiswrittenforandthenameoftheprogrammer.Sincethisinformationisnotofimportancefortheassembler,itis writtenasacommentwhichalwaysstartswithsemicolonandcanbewritteninanewlineorimmediatelyafteracommand. Afterwritingthisgeneralcomment,itistimetoselectthemicrocontrollerbyusingdirectivePROCESSOR.Thisdirectiveisfollowedby anotheroneusedtoincludeallthedefinitionsofthePIC16F887microcontrollersinternalregistersintheprogram.Thesedefinitionsare nothingbuttheabilitytoaddressportBandotherregistersasPORTBinsteadof06h,whichmakestheprogramclearerandmorelegible. Inorderthatthemicrocontrollerwilloperateproperly,aseveralparameterssuchasthetypeofoscillator,stateofthewatchdogandinternal resetcircuitmustbedefined.Itisdonebyutilizingthefollowingdirective:

_ C O N F I G _ C P _ O F F & _ W D T _ O F F & P W R T E _ O N & X T _ O S C

Whenallnecessaryelementsaredefined,theprocessofprogramwritingcanstart.Firstandforemost,itisnecessarytospecifytheaddress fromwhichthemicrocontrollerstartswhenthepowergoeson(o r g 0 x 0 0 )aswellastheaddressfromwhichtheprogramproceedswith executionifaninterruptoccurs(o r g 0 x 0 4 ).Sincethisprogramisverysimple,itisenoughtousecommand"g o t o M a i n "inordertodirect themicrocontrollertothebeginningoftheprogram.Thenextcommandselectsmemorybank1inordertoenableaccesstotheTRISB registertoconfigureportBasoutput(b a n k s e l T R I S B ).Themainprogramendsbyselectingmemorybank0andsettingallportBpinsto logicone(1)(m o v l w 0 x F F ,m o v w f P O R T B ). Itisnecessarytocreatealooptokeepprogramfrom"gettinglost"incaseanerroroccurs.Forthispurpose,thereisanendlessloop executedallthetimewhilethemicrocontrollerisswitchedon. "e n d "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.Itcontainslotsofinformationoncommandsandvariableslocationsinonchipmemory aswellaserrorsignalization.Thereisasymboltableattheendofeachdatafilelistcontainingallthesymbolsusedinaprogram.Other usefulelementsoflistdatafilearememoryusagemapsanderrorstatisticsprovidedattheveryendofthefilelist.

MACROSANDSUBROUTINES
Thesamesequenceofcomputinginstructionsisusuallyusedrepeatedlywithinaprogram.Assemblylanguageisverydemanding.The programmerisrequiredtotakecareofthelastlittledetailwhenwritingaprogram,becauseonlyonewrongcommandorlabelnamemay causetheprogramtonotworkproperlyoritmaynotworkatall.Therefore,itislesstediousandlesserrorpronetouseasequenceof instructionsasasingleprogramstatementwhichworksproperlyforsure.Toimplementthisidea,macrosandsubroutinesareused.

MACROS

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

5/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

Amacrocontainsprogrammerdefinedsymbolsthatstandforasequenceoftextlines.Itisdefinedbyusingdirectivemacrowhichnames macroandargumentsifneeded.Macromustbedefinedprioritisused.Onceamacrohasbeendefined,itsnamemaybeusedinthe program.Whentheassemblerencountersmacrosname,itreplacesitbytheappropriatesequenceofinstructionsandprocessesthemjust asthoughtheyhaveappearedintheprogram.Manydifferentmacroinstructionsareavailableforvariouspurposes,eliminatingsomeofthe repetitivenessoftheprogramming,aswellassimplifyingthewriting,readingandunderstandingoftheprogram.Thesimplestuseofmacros maybegivinganametoaninstructionsequencebeingrepeated.Letustake,forexample,globalinterruptenableprocedure,SFRs'bank selection.

m a c r o _ n a m e m a c r o a r g 1 , a r g 2 . . . . . . s e q u e n c e o f i n s t r u c t i o n s . . . e n d m

Thefollowingexampleshowsfourmacros.Thefirsttwomacrosselectbanks,thethirdoneenablesinterrupt,whereasthefourthone disablesinterrupt.

b a n k 0 m a c r o M a c r o b a n k 0 b c f S T A T U S , R P 0 R e s e t R P 0 b i t b c f S T A T U S , R P 1 R e s e t R P 1 b i t e n d m E n d o f m a c r o b a n k 1 m a c r o M a c r o b a n k 1 b s f S T A T U S , R P 0 S e t R P 0 b i t b c f S T A T U S , R P 1 R e s e t R P 1 b i t e n d m E n d o f m a c r o e n a b l e i n t m a c r o G l o b a l i n t e r r u p t e n a b l e b s f I N T C O N , 7 S e t b i t e n d m E n d o f m a c r o d i s a b l e i n t m a c r o G l o b a l i n t e r r u p t d i s a b l e b c f I N T C O N , 7 R e s e t b i t e n d m E n d o f m a c r o

MacrosdefinedinthiswayaresavedinaparticulardatafilewithextensionINCwhichstandsforINCLUDEdatafile.Asseen,thesefour macrosdonothavearguments.However,macrosmayincludeargumentsifneeded. Thefollowingexampleshowsmacroswitharguments.PinisconfiguredasinputifthecorrespondingbitoftheTRISregisterissettologic one(bank1).Otherwise,itisconfiguredasoutput.

i n p u t m a c r o a r g 1 , a r g 2 M a c r o I n p u t b a n k 1 B a n k c o n t a i n i n g T R I S r e g i s t e r s b s f a r g 1 , a r g 2 S e t t h e s p e c i f i e d b i t ( 1 = I n p u t ) b a n k 0 M a c r o f o r b a n k 0 s e l e c t i o n e n d m E n d o f m a c r o o u t p u t m a c r o a r g 1 , a r g 2 M a c r o O u t p u t b a n k 1 B a n k c o n t a i n i n g T R I S r e g i s t e r s b c f a r g 1 , a r g 2 C l e a r t h e s p e c i f i e d b i t ( 0 = O u t p u t ) b a n k 0 M a c r o f o r b a n k 0 s e l e c t i o n e n d m E n d o f m a c r o

Macrowithargumentsmaybecalledinthefollowingway:

. . . o u t p u t T R I S B , 7 P i n R B 7 i s c o n f i g u r e d a s o u t p u t . . .

Whencallingthismacro,thefirstspecifiedargumentTRISBisreplacedbythefirstargumentarg1inmacrodefinition.Similarly,number7is replacedbytheargumentarg2,andthefollowingcodeisgenerated:

. . . b s f S T A T U S , R P 0 S e t R P 0 b i t = B A N K 1 b c f S T A T U S , R P 1 R e s e t R P 0 b i t = B A N K 1 b c f T R I S B , 7 C o n f i g u r e R B 7 a s o u t p u t b c f S T A T U S , R P 0 C l e a r R P 0 b i t = B A N K 0 b c f S T A T U S , R P 1 C l e a r R P 1 b i t = B A N K 0 . . .

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

6/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

Itisclearatfirstsightthattheprogrambecomesmorelegibleandflexiblebyusingmacros.Themaindisadvantageofmacroisthatit occupiesalotofmemoryspacebecauseeverymacronameinaprogramisreplacedbyitspredefinedcode.Owingtothefactthat programsoftenusemacro,everythingismorecomplicatedifitislong.

c a l l c m a c r o l a b e l M a c r o c a l l c l o c a l E x i t D e f i n e l o c a l L a b e l w i t h i n m a c r o b n c E x i t I f C = 0 j u m p t o E x i t c a l l l a b e l I f C = 1 c a l l s u b r o u t i n e a t a d d r e s s L a b e l ( o u t o f m a c r o ) E x i t L o c a l L a b e l w i t h i n m a c r o e n d m E n d o f m a c r o

Intheeventthatamacrohaslabels,theymustbedefinedaslocalonesbyusingdirectivelocal.Thegivenexamplecontainsmacrowhich callsasubroutine(c a l l l a b e l inthiscase)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. When2bytevariablesareused,itisnecessarytodefinehigherandlowerbyteforeachofthem.Theprogramitselfisverysimple.Itfirst addslowerbytesofvariablesARG1andARG2andhigherafterwards.Ifthesumofadditionoftwolowerbytesisgreaterthan255(maximal bytevalue)theremainderisaddedtotheRESHvariable.

P r o g r a m t o a d d t w o 1 6 b i t n u m b e r s V e r s i o n : 1 . 0 D a t e : A p r i l 2 5 , 2 0 0 7 M C U : P I C 1 6 F 8 8 7 P R O C E S S O R 1 6 f 8 8 7 D e f i n i n g p r o c e s s o r # i n c l u d e " p 1 6 f 8 8 7 . i n c " M i c r o c h i p I N C d a t a b a s e _ _ C O N F I G _ C P _ O F F & _ W D T _ O F F & _ P W R T E _ O N & _ X T _ O S C C b l o c k 0 x 2 0 B e g i n n i n g o f R A M A R G 1 H A r g u m e n t 1 h i g h e r b y t e A R G 1 L A r g u m e n t 1 l o w e r b y t e A R G 2 H A r g u m e n t 2 h i g h e r b y t e A R G 2 L A r g u m e n t 2 l o w e r b y t e R E S H R e s u l t h i g h e r b y t e R E S L R e s u l t l o w e r b y t e e n d c E n d o f v a r i a b l e s O R G 0 x 0 0 R e s e t v e c t o r g o t o S t a r t S t a r t W r i t e v a l u e s t o v a r i a b l e s m o v l w 0 x 0 1 A R G 1 = 0 x 0 1 0 4 m o v w f A R G 1 H m o v l w 0 x 0 4 m o v w f A R G 1 L m o v l w 0 x 0 7 A R G 2 = 0 x 0 7 0 5 m o v w f A R G 2 H m o v l w 0 x 0 5 m o v w f A R G 2 L M a i n M a i n p r o g r a m c a l l A d d 1 6 C a l l s u b r o u t i n e A d d 1 6 L o o p g o t o L o o p R e m a i n h e r e A d d 1 6 S u b r o u t i n e t o a d d t w o 1 6 b i t n u m b e r s c l r f R E S H R E S H = 0

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

7/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

m o v f A R G 1 L , w w = A R G 1 L a d d w f A R G 2 L , w w = w + A R G 2 L m o v w f R E S L R E S L = w b t f s c S T A T U S , C I s t h e r e s u l t g r e a t e r t h a n 2 5 5 ? i n c f R E S H , f I f g r e a t e r , i n c r e m e n t R E S H b y o n e m o v f A R G 1 H , w w = A R G 1 H a d d w f A R G 2 H , w w = w + A R G 2 a d d w f R E S H , f R E S H = w r e t u r n R e t u r n f r o m s u b r o u t i n e e n d E n d o f p r o g r a m

InShort
Themaindifferencebetweenmacrosandsubroutinesisthatmacroisaftercompilingreplacedbyitscode(enablestheprogrammertotype less).Itmayalsohaveargumentswhilesubroutineuseslessmemory,butdoesnothavearguments.

MPLAB
MPLABisaWindowsprogrampackagewhichenableseasyprogramwritingaswellaseasyprogramdevelopment.Itisbesttodescribeit asdevelopmentenvironmentforastandardprogramlanguagedesignedforPCprogramming.MPLABtechnicallysimplifiessome operationsconsistingofalotofparameters,which,untiltheIDEenvironment*appeared,wereexecutedfromthecommandline.However, tastesaredifferentandtherearesomeprogrammerswhopreferstandardeditorsandcommandlinecompilers.Everyprogramwrittenin MPLABisclear,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:

1. StartMicrosoftWindows 2. InserttheCDintoCDROM 3. ClickSTARTandselectoptionRUN 4. ClickBROWSEandselectCDROMdriveand 5. FindfolderMPLABonCDROM.


Everythingisreadynowtostartinstallation.Thefollowingpicturesdescribetheinstallationsteps.

Clickonthisicontostartuptheprocess...

Somethingisgoingon...Thepicturecomingupindicatesthattheprocessofinstallationhasjuststarted! Nextwindowcontainstheword"Welcome".Need explanation?

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

8/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers


Actually,theprogramremindsyoutocloseallactive programsinordertonotinterferewiththeinstallation process.Nextofcourse!

Priortocontinue,youhavetoaccepttheMPLAB softwarelicenseconditions.Selecttheoption"I accept"andclickNEXT.

Doyouwanttoinstalltheentiresoftware?Yes.Next...

Similartootherprograms,MPLABshouldbealso installedintoafolder.Itmaybeanyfolderonany harddisc.Ifitisnotnecessarytomakechanges, selectthespecifiedaddressandclickNext.

Anotherlicense,anotheracceptanceofoptions specifiedbythecomputer...Next,Next... Bepatient!

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

9/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

Finally!Thisiswhatyouhavebeenwaitingfor.Click Finish.Thecomputerwillberestartedalongwiththe programsavedonharddisc.EverythingisOK!

ClicktheMPLABdesktopiconinordertostarttheprogramandlearnaboutit.

Asseen,MPLABissimilartomostWindowsprograms.Apartfromtheworkingarea,therearemenus(containsoptions:File,Editetc.), toolbars(containsdifferenticons)andastatusbaratthebottomofthewindow.SimilartoWindows,thereisaruletohaveshortcutsforthe mostcommonlyusedprogramoptionscreatedinordertoeasilyaccessthemandspeedupoperationtherefore.Theseshortcutsare actuallyiconsbelowthemenubar.Inotherwords,alloptionscontainedinthetoolbararecontainedinthemenutoo.

PROJECTMAKING
Followthesestepstoprepareprogramforloadingintothemicrocontroller:

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

10/16

19/05/13
1. Makeaproject 2. Writeaprogramand 3. Compileit.

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

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

KeeponprojectmakingbyclickingNEXT.Then selectthemicrocontrolleryouwillbeusing. Inourcase,itisPIC16F887microcontroller.

Attheend,theprojectisassignedanamewhichusuallyindicatesthepurposeandthecontentoftheprogrambeingwritten.Theproject shouldbemovedtothedesiredfolder.ItisbestthatthefolderassociateswithPICmicrocontrollers(Seefigure).

DocumentscontainedintheprojectdonotalwaysneedtobewritteninMPLAB.Documentswrittenbysomeotherprogrammayalsobe includedintheproject.Inthisexample,therearenosuchdocuments.JustclickNext.

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

11/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

ClickFINISHtocompletetheproject.Thewindowitselfcontainsprojectparameters.

WRITINGANEWPROGRAM
Whentheprojectiscreated,awindowshowninfigurebelowappears.

Thenextstepistowriteaprogram.OpenanewdocumentbyclickingFile>New.TextEditorinMPLABenvironmentappears. SavethedocumentinthefolderD:\PICprojectsbyusingtheFile>SaveAscommandandnameit"Blink.asm"indicatingthatthisprogram istobeanexampleofportdiodeblinking.Obviouslyyoucanlocateyoufileswhereveryouwish,inwhicheverharddriveyouwish.Usinga commondirectorytostoreallyourdifferentprojectsandsubdirectoriesinmakesgoodsense.

Example:

D : \ P i c P r o j e c t s L E D F l a s h P r o j e c t A l l a s s o c i a t e d f i l e s E v e n t C o u n t P r o j e c t A l l a s s o c i a t e d f i l e s L E D S c a n n i n g P r o j e c t A l l a s s o c i a t e d f i l e s

Afterthe"Blink.asm"iscreatedandsaved,itshould beincludedintheprojectbyrightclickonthe"Source Files"optioninthe"Proba.mcw"window.Afterthat,a smallwindowwithtwooptionsappears.Selectthe firstone"AddFiles".

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

12/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

ClickonthatoptionopensanotherwindowcontainingthefolderPICalongwiththedocumentBlink.asm.Seefigurebelow.

Click"Blink"toincludethedocumentBlink.asmintotheproject.

Programwritingexample
Theprogramwritingprocedurecannotstartuntilallpreviousoperationshavebeenperformed.Programwrittenbelowisasimpleillustration ofprojectmaking.

P r o g r a m t o s e t p o r t B p i n s t o l o g i c o n e ( 1 ) . V e r s i o n : 1 . 0 D a t e : A p r i l 2 5 , 2 0 0 7 M C U : P I C 1 6 F 8 8 7 P r o g r a m m e r : J o h n S m i t h * * * * * D e c l a r a t i o n a n d c o n f i g u r a t i o n o f t h e m i c r o c o n t r o l l e r * * * * * P R O C E S S O R 1 6 f 8 8 7 # i n c l u d e " p 1 6 f 8 8 7 . i n c " _ _ C O N F I G _ C P _ O F F & _ W D T _ O F F & _ P W R T E _ O N & _ X T _ O S C * * * * * V a r i a b l e d e c l a r a t i o n * * * * * C b l o c k 0 x 2 0 F i r s t f r e e R A M l o c a t i o n e n d c N o v a r i a b l e s * * * * * P r o g r a m m e m o r y s t r u c t u r e * * * * * O R G 0 x 0 0 R e s e t v e c t o r g o t o M a i n A f t e r r e s e t j u m p t o t h i s l o c a t i o n O R G 0 x 0 4 I n t e r r u p t v e c t o r g o t o M a i n N o i n t e r r u p t r o u t i n e M a i n S t a r t t h e p r o g r a m b a n k s e l T R I S B S e l e c t b a n k c o n t a i n i n g T R I S B c l r f T R I S B P o r t B i s c o n f i g u r e d a s o u t p u t b a n k s e l P O R T B S e l e c t b a n k c o n t a i n i n g P O R T B m o v l w 0 x f f W = F F m o v w f P O R T B M o v e W t o p o r t B L o o p g o t o L o o p J u m p t o l a b e l L o o p E n d

TheprogramshouldbewrittentotheBlink.asmwindoworcopiedfromdiscbymeansofoptionscopy/paste.Whencopied,theprogram shouldbecompiledintoexecutableHEXformatbyusingoptionPROJECT>BUILDALL.Anewwindowappears.Thelastsentenceisthe mostimportantbecauseittellsuswhethercompilinghassucceededornot.Clearly,BUILDSUCCEEDEDmessagemeansthatnoerror occurredandcompilinghasbeensuccessfullydone.

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

13/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

Incaseanerroroccurs,itisnecessarytoclicktwiceonthemessagereferringtoitintheOutputwindow,whichautomaticallyswitchyou overtoassemblyprogram,directlytothelinewheretheerrorhasoccurred.

SIMULATOR
AsimulatorisapartofMPLABenvironmentwhichprovidesbetterinsightintotheoperationofthemicrocontroller.Generallyspeaking,a simulationisanattempttomodelareallifeorhypotheticalsituationsothatitcanbestudiedtoseehowthesystemworks.Bymeansofthe simulator,itisalsopossibletomonitorcurrentvaluesofvariables,registersandportpinsstatesaswell.Tobehonest,asimulatorisnotof thesameimportanceforallprograms.Ifaprogramissimpler(asinourexample),thesimulationisnotofgreatimportancebecausesetting portBpinstologicone(1)isnotcomplicatedatall.However,inmorecomplexprogramscontainingtimers,differentconditionsand requests(especiallymathematicaloperations),thesimulatormaybeofgreatuse.Asthenameitselfindicates,asimulationmeansto simulatetheoperationofmicrocontroller.Likethemicrocontroller,asimulatorexecutesinstructionsoneafteranother(linebyline)and constantlyupdatesthestateofallregisters.Inthisway,theusersimplymonitorsprogramexecution.Attheendofprogramwriting,theuser shouldfirsttestitinthesimulatorpriortoexecutingitinarealenvironment.Unfortunately,thisisoneofmanygoodthingsbeingoverlooked bytheprogrammerbecauseofitscharacterassuchandthelackofhighqualitysimulatorsaswell.

SimulatorisactivatedbyclickingonDEBUGGER>SELECTTOOL>MPLABSIM,asshowninfigure.Asaresult,severaliconsrelatedto thesimulatoronlyappear.Theirmeaningsareasfollows: 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. Similartorealenvironment,thefirstthingthatshouldbedoneistoresetthemicrocontrollerusingtheoptionDEBUGGER>RESETorby

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

14/16

19/05/13

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers

clickingreseticon.Astheconsequenceofthis,agreenlineispositionedatthebeginningoftheprogramandprogramcounterPCLis clearedtozero.RefertothewindowSpecialFunctionRegistersshownbelow.

ApartfromSFRs,itisgoodtohaveaninsightinFileRegisters.AwindowcontainingthemappearsbyclickingtheVIEW>FILEREGISTERS option. Iftheprogramcontainsvariables,itisgoodtomonitortheirvaluesaswell.Eachvariableisassignedawindow(WatchWindows)byclicking VIEW>WATCHoption.

Iftheprogramcontainsvariables,itisgoodtomonitortheirvaluesaswell.Eachvariableisassignedawindow(WatchWindows)byclicking VIEW>WATCHoption. Afterallvariablesandregistersofinterestbecomeavailableonthesimulatorworkingarea,theprocessofsimulationcanstart.Thenext instructionmaybeeitherStepintoorStepoverdependingonwhetheryouwanttostepintosubroutineornot.Thesameinstructionsmay besetbyusingkeyboardpushbuttons<F7>or<F8>(generally,allimportantinstructionshavethecorrespondingpushbuttonsonthe keyboard). previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers

Additional Software
Visual TFT Visual GLCD Package Manager

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

15/16

19/05/13
PIC Kits PIC Books

Appendix A: Programming a Microcontroller - Book: PIC Microcontrollers


dsPIC Kits dsPIC Books PIC32 Kits Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards GSM/GPRS boards GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/

16/16

19/05/13
Products

Appendix B: Examples - Book: PIC Microcontrollers


Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

AppendixB:Examples
Thepurposeofthischapteristoprovidebasicinformationaboutmicrocontrollersthatoneneedstoknowinordertobeabletousethem successfullyinpractice.Thischapter,therefore,doesnotcontainanysuperinterestingprogramordeviceschematicwithamazing solutions.Instead,thefollowingexamplesaremoreproofthatprogramwritingisneitheraprivilegenoratalentissuebuttheabilityofsimply puttingpuzzlepiecestogetherusingdirectives.Restassuredthatdesignanddevelopmentofdevicesmainlyconsistsofthefollowing method"testcorrectrepeat".Ofcourse,themoreyouareinitthemorecomplicateditbecomessincethepuzzlepiecesareputtogetherby bothchildrenandfirstclassarchitects...

BASICCONNECTING
Asseeninthefigurebelow,inordertoenablethemicrocontrollertooperateproperlyitisnecessarytoprovide:

PowerSupply ResetSignaland ClockSignal.

EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

Clearly,itisaboutsimplecircuits,butitdoesnothavetoalwaysbelikethat.Ifthetargetdeviceisusedforcontrollingexpensivemachines ormaintainingvitalfunctions,everythinggetsmoreandmorecomplicated!However,thissolutionissufficientforthetimebeing...

POWERSUPPLY
EventhoughthePIC16F887canoperateatdifferentsupplyvoltages,whytotest"Murphy'slow"?!A5DCpowersupplyisshownabove.The circuit,usesacheapintegratedthreeterminalpositiveregulator,LM7805,provideshighqualityvoltagestabilityandquiteenoughcurrent toenablemicrocontrollerandperipheralelectronicstooperatenormally(enoughinthiscasemeans1Amp).

RESETSIGNAL
Inorderthatthemicrocontrollercanoperateproperly,alogicone(VCC)mustbeappliedontheresetpinitexplainstheconnectionpin resistor10KVCC.ThepushbuttonconnectingtheresetpinMCLRtoGNDisnotnecessary.However,itisalmostalwaysprovidedbecause itenablesthemicrocontrollersafereturntonormaloperatingconditionsifsomethinggoeswrong.Bypushingthisbutton,0Visbroughtto thepin,themicrocontrollerisresetandprogramexecutionstartsfromthebeginning.The10Kresistoristheretoallow0Vtobeappliedto theMCLRpin,viathepushbutton,withoutshortingthe5VDCrailtoground.

CLOCKSIGNAL
Eventhoughthemicrocontrollerhasabuiltinoscillator,itcannotoperatewithoutexternalcomponentswhichstabilizeitsoperationand determineitsfrequency(operatingspeedofthemicrocontroller).Dependingonwhichelementsareinuseaswellastheirfrequencies,the oscillatorcanberuninfourdifferentmodes:

LPLowPowerCrystal XTCrystal/Resonator HSHighspeedCrystal/Resonatorand RCResistor/Capacitor.


Whyarethesemodessoimportant?Owingtothefact thatitisalmostimpossibletomakeastableoscillator whichoperatesoverawidefrequencyrange,the microcontrollermustknowwhichcrystalisconnected inorderthatitcanadjusttheoperationofitsinternal

www.mikroe.com/chapters/view/12/appendix-b-examples/

1/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers


electronicstoit.Thisiswhyallprogramsusedfor chiploadingcontainsanoptionforoscillatormode selection.Seeabovefigure.

Quartzresonator
Whenaquartzcrystalisusedforfrequencystabilization,thebuiltinoscillatoroperatesataveryprecisefrequencywhichisisolatedfrom changesintemperatureandvoltagepowersupplyaswell.Thisfrequencyisnormallylabelledonthemicrocontrollerpackage. Apartfromthecrystal,capacitorsC1andC2mustbealsoconnectedaspertheschematicbelow.Theircapacitanceisnotofgreat importance,therefore,thevaluesprovidedinthetableshouldbeconsideredasarecommendationratherthanastrictrule.

Ceramicresonator
Ceramicresonatorischeaper,butverysimilartoquartzbyitsfunctionandthewayofoperating.Thisiswhytheschematicsillustratingtheir connectiontothemicrocontrollerareidentical.However,thecapacitorvalueisabitdifferentinthiscaseduetodifferentelectricfeatures. Refertothetable.

Theseoscillatorsareusedwhenitisnotnecessarytohaveextremelyprecisefrequency.

RCoscillator
Iftheoperatingfrequencyisnotofimportancethenthereisnoneedforadditionalexpensivecomponentsforstabilization.Instead,asimple RCnetwork,asshowninthefigurebelow,willbeenough.Sinceonlytheinputofthelocaloscillatorinputisinusehere,theclocksignal withfrequencyFosc/4willappearontheOSC2pin.Furthermore,thatfrequencybecomesoperatingfrequencyofthemicrocontroller,i.e.the speedofinstructionexecution.

www.mikroe.com/chapters/view/12/appendix-b-examples/

2/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

Externaloscillator
Ifitisrequiredtosynchronizetheoperationofseveralmicrocontrollersorifforsomereasonitisnotpossibletouseanyoftheprevious schematics,aclocksignalmaybegeneratedbyanexternaloscillator.Refertothefigurebelow.

ADDITIONALCOMPONENTS
Regardlessofthefactthatthemicrocontrollerisaproductofmoderntechnology,itisofnousewithoutbeingconnectedtoadditional components.Simply,theappearanceofvoltageonthemicrocontrollerpinsmeannothingifnotusedforperformingcertainoperations(turn somethingon/off,shift,displayetc.). Thissectionintentionallycoversonlythemostcommonlyusedadditionalcomponentsinpracticesuchasresistors,transistors,LEDdiodes, LEDdisplays,LCDdisplaysandRS232communicationcircuits.

SWITCHESANDPUSHBUTTONS
Thereisnothingsimplerthanswitchesandpushbuttons!Thisisdefinitelythesimplestwayofdetectingtheappearanceofavoltageonthe microcontrollerinputpinandthereisnoneedforadditionalexplanationofhowthesecomponentsoperate.Nevertheless,itisnotsosimple inpractice...Then,whatisitallabout?

Itisaboutcontactbounceacommonproblemwithmechanicalswitches.Whenthecontactsstriketogether,theirmomentumandelasticity acttogethertocausebounce.Theresultisarapidlypulsedelectricalcurrentinsteadofacleantransitionfromzerotofullcurrent.Generally, itmostlyoccursduetovibrations,slightroughspotsanddirtbetweencontacts.Thiseffectisusuallyunnoticeablewhenusingthese componentsineverydaylifebecausethebouncehappenstooquicklytoaffectmostequipment,butcausesproblemsinsomeanalogue andlogiccircuitsthatrespondfastenoughtomisinterprettheonoffpulsesasadatastream.Anyway,thewholeprocessdoesnotlastlong (afewmicroormilliseconds),butlongenoughtoberegisteredbythemicrocontroller.Whenusingonlyapushbuttonasapulsecounter, errorsoccursinalmost100%ofcases! ThisproblemmaybeeasilysolvedbyconnectingasimpleRCcircuittosurpressquickvoltagechanges.Sincethebounceperiodisnot defined,thevaluesofcomponentsarenotpreciselydetermined.Inmostcases,itisrecommendedtousethevaluesasshowninfigure below.

www.mikroe.com/chapters/view/12/appendix-b-examples/

3/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

Ifcompletestabilityisneededthenradicalmeasuresshouldbetaken!Theoutputofthecircuit,showninfigurebelow(RSflipflop),will changeitslogicstateonlyafterdetectingthefirstpulsetriggeredbycontactbounce.Thissolutionismoreexpensive(SPDTswitch),butthe problemisdefinitelysolved!

Inadditiontothesehardwaresolutions,thereisalsoasimplesoftwaresolution.Whenaprogramteststhestateofaninputpinanddetects achange,thecheckshouldbedoneonemoretimeafteracertaindelay.Iftheprogramconfirmsthechange,itmeansthataswitch/push buttonhaschangeditsposition.Theadvantagesofsuchsolutionareobvious:itisfreeofcharge,effectsofnoisesareeliminatedanditcan beappliedtothepoorerqualitycontactsaswell.

RELAY
Arelayisanelectricalswitchthatopensandclosesunderthecontrolofanother electricalcircuit.Itisthereforeconnectedtooutputpinsofthemicrocontrollerand usedtoturnon/offhighpowerdevicessuchasmotors,transformers,heaters,bulbs, etc.Thesedevicesarealmostalwaysplacedawayfromtheboardssensitive components.Therearevarioustypesofrelays,butallofthemoperateinthesame way.Whenacurrentflowsthroughthecoil,therelayisoperatedbyanelectromagnet toopenorcloseoneormanysetsofcontacts.Similartooptocouplers,thereisno galvanicconnection(electricalcontact)betweeninputandoutputcircuits.Relays usuallydemandbothhighervoltageandcurrenttostartoperationbuttherearealso miniatureonesthatcanbeactivatedbyalowcurrentdirectlyobtainedfroma microcontrollerpin.

Thisfigureshowsthemostcommonlyused solution. Inordertopreventtheappearanceofhigh voltageselfinductioncausedbyasuddenstop ofcurrentflowthroughthecoil,aninverted polarizeddiodeisconnectedinparalleltothe coil.Thepurposeofthisdiodeisto"cutoff"the voltagepeak.

LEDDIODES
YouprobablyknowallyouneedtoknowaboutLEDdiodes,butweshouldalsothinkoftheyoungergenerations...HowtodestroyaLED?! Well...Verysimple.

www.mikroe.com/chapters/view/12/appendix-b-examples/

4/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

Quick burning
Likeanyotherdiode,LEDshavetwoendsananodeandacathode.Connectitproperlytoapowersupplyvoltage.Thediodewillhappily emitlight.Turnitupsidedownandapplythesamepowersupplyvoltage(evenforamoment).ItwillnotemitlightNEVERAGAIN!

Slow burning
Thereisanominal,i.e.maximumcurrentdeterminedforeveryLEDwhichshouldnotbeexceeded.Ifithappens,thediodewillemitmore intensivelight,butnotforalongtime!

Something to remember
Similartothepreviousexample,allyouneedtodoistodiscardacurrentlimitingresistorshownbelow.Dependingonpowersupply voltage,theeffectmightbespectacular!

LEDDISPLAY
Basically,LEDdisplayisnothingmorethanseveralLEDsmouldedinthesameplasticcase.Therearemanytypesofdisplayscomposedof severaldozensofbuiltindiodeswhichcandisplaydifferentsymbols.Themostcommonlyusedissocalled7segmentdisplay.Itis composedof8LEDs7segmentsarearrangedasarectangleforsymboldisplayingandthereisanadditionalsegmentfordecimalpoint displaying.Inordertosimplifyconnection,anodesorcathodesofalldiodesareconnectedtothecommonpinsothattherearecommon anodedisplaysandcommoncathodedisplays,respectively.Segmentsaremarkedwiththelettersfromatog,plusdp,asshowninfigure below.Onconnecting,eachdiodeistreatedseparately,whichmeansthateachmusthaveitsowncurrentlimitingresistor.

HereareafewimportantthingsthatoneshouldpayattentiontowhenbuyingLEDdisplays:

Dependingonwhetheranodesorcathodesareconnectedtothecommonpin,therearecommonanodedisplaysand commoncathodedisplays.Thefigureaboveshowsacommonanodedisplay.Lookingatphysicalfeatures,thereis nodifferencebetweenthesedisplaysatallsoitisrecommendedtocheckcarefullypriorinstallationwhichofthemis inuse Foreachmicrocontrollerpin,thereisamaximumcurrentlimitationitcanreceiveorgive.Becauseofthis,ifseveral displaysareconnectedtothemicrocontrolleritisrecommendedtousesocalledLowcurrentLEDsusingonly2mA foroperationand Displaysegmentsareusuallymarkedwiththelettersfromatog,butthereisnofastruleindicatingtowhichmicro controllerpinstheyshouldbeconnected.Forthisreasonitisveryimportanttocheckconnectingpriortocommencing programwritingordesigningadevice.
DisplaysconnectedtothemicrocontrollerusuallyoccupyalargenumberofvaluableI/Opins,whichcanbeabigproblemespeciallywhen itisneededtodisplaymultidigitalnumbers.Theproblemismorethanobviousif,forexample,itisneededtodisplaytwo6digitnumbers(a simplecalculationshowsthat96outputpinsareneededinthiscase)!ThisproblemhasasolutioncalledMULTIPLEXING. Hereishowanopticalillusionbasedonthesameoperatingprincipleasafilmcameraismade.Onlyonedigitatatimeisactive,butthey changetheirstatesoquicklythatonegetsimpressionthatalldigitsofanumberareactivesimultaneously.

www.mikroe.com/chapters/view/12/appendix-b-examples/

5/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

Hereisanexplanationonthefigureabove.FirstabyterepresentingunitsisappliedonamicrocontrollerportandatransistorT1is activatedsimultaneously.Afterawhile,thetransistorT1isturnedoff,abyterepresentingtensisappliedonaportandtransistorT2is activated.Thisprocessisbeingcyclicallyrepeatedathighspeedforalldigitsandcorrespondingtransistors. Adisappointingfactwhichindicatesthatthemicrocontrollerisjustakindofminiaturecomputerdesignedtounderstandonlythelanguage ofzerosandonesisfullyexpressedwhendisplayinganydigit.Namely,themicrocontrollerdoesnotknowwhatunits,tensorhundredsare, norwhattendigitsweareusedtolooklike.Therefore,eachnumbertobedisplayedmustgothroughthefollowingprocedure: Firstofall,inaparticularsubroutineamultidigitalnumbermustbesplitintounits,tensetc.Then,thesemustbestoredinspecialbytes each.Digitsgetrecognizableformatbyperforming"masking".Inotherwords,abinaryformatofeachdigitisreplacedbyadifferent combinationofbitsusingasimplesubroutine.Forexample,thedigit8(00001000)isreplacedbybinarynumber01111111inorderto activateallLEDsdisplayingdigit8.Theonlydioderemaininginactiveinthiscaseisreservedforthedecimalpoint. Ifamicrocontrollerportisconnectedtothedisplayinawaythatbit0activatessegment"a",bit1activatessegment"b",bit2segment"c" etc.,thenthetablebelowshowsthemaskforeachdigit.

DIG IT ST O DISPL AY dp 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 a 1 0 1 1 0 1 1 1 1 1

DISPL AYSEG MENT S b 1 1 1 1 1 0 0 1 1 1 c 1 1 0 1 1 1 1 1 1 1 d 1 0 1 1 0 1 1 0 1 1 e 1 0 1 0 0 0 1 0 1 0 f 1 0 0 0 1 1 1 0 1 1 g 0 0 1 1 1 1 1 0 1 1

Inadditiontodigitsfrom0to9,therearesomelettersA,C,E,J,F,U,H,L,b,c,d,o,r,tthatcanbealsodisplayedbymeansofthe appropriatemasking. Intheeventthatthecommonanodedisplaysareused,allonescontainedintheprevioustableshouldbereplacedbyzerosandviceversa. Additionally,NPNtransistorsshouldbeusedasdriversaswell.

OPTOCOUPLER

www.mikroe.com/chapters/view/12/appendix-b-examples/

6/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

Anoptocouplerisadevicecommonlyusedtogalvanicallyseparatemicrocontrollerelectronicsfromanypotentiallydangerouscurrentor voltageinitssurroundings.Optocouplersusuallyhaveone,twoorfourlightsources(LEDdiodes)ontheirinputwhileontheiroutput, oppositetodiodes,thereisthesamenumberofelementssensitivetolight(phototransistors,photothyristorsorphototriacs).Thepointis thatanoptocouplerusesashortopticaltransmissionpathtotransferasignalbetweenelementsofcircuit,whilekeepingthemelectrically isolated.Thisisolationmakessenseonlyifdiodesandphotosensitiveelementsareseparatelypowered.Inthisway,themicrocontroller andexpensiveadditionalelectronicsarecompletelyprotectedfromhighvoltageandnoiseswhicharethemostcommoncauseof destroying,damagingorunstableoperationofelectronicdevicesinpractice.Themostfrequentlyusedoptocouplersarethosewith phototransistorsontheiroutputs.Additionally,optocouplerswithinternalbasetopin6connection(therearealsooptocouplerswithoutit), thebasemaybeleftunconnected.

TheR/Cnetworkrepresentedbythebrokenlineinthefigureabovedenotesoptionalconnectionwhichlessenstheeffectsofnoisesby eliminatingveryshortpulses.

LCDDISPLAY
Thiscomponentisspecificallymanufacturedtobeusedwithmicrocontrollers,whichmeansthatitcannotbeactivatedbystandardIC circuits.Itisusedfordisplayingdifferentmessagesonaminiatureliquidcrystaldisplay.Themodeldescribedhereisforitslowpriceand greatcapabilitiesmostfrequentlyusedinpractice.ItisbasedontheHD44780microcontroller(Hitachi)andcandisplaymessagesintwo lineswith16characterseach.Itdisplaysallthelettersofalphabet,Greekletters,punctuationmarks,mathematicalsymbolsetc.Inaddition, itispossibletodisplaysymbolsmadeupbytheuser.Otherusefulfeaturesincludeautomaticmessageshift(leftandright),cursor appearance,LEDbacklightetc.

Alongonesideofasmallprintedboardtherearepinsusedforconnectingtothemicrocontroller.Thereareintotalof14pinsmarkedwith numbers(16ifthebacklightisbuiltin).Theirfunctionisdescribedinthetablebellow:
FUNCTION Ground Power supply Contrast PINNUMBER 1 2 3 4 5 NAME Vss Vdd Vee RS R/W L O G ICST AT E 0 1 0 1 0 1 From 1 to 0 0/1 0/1 0/1 0/1 0/1 0/1 0/1 DESCRIPT IO N 0V +5V 0 - Vdd D0 D7 are interpreted as commands D0 D7 are interpreted as data Write data (from controller to LCD) Read data (from LCD to controller) Access to LCD disabled Normal operating Data/commands are transferred to LCD Bit 0 LSB Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6

Control of operating

6 7 8 9 Data / commands 10 11 12 13

E D0 D1 D2 D3 D4 D5 D6

www.mikroe.com/chapters/view/12/appendix-b-examples/

7/43

19/05/13
14 D7

Appendix B: Examples - Book: PIC Microcontrollers


0/1 Bit 7 MSB

LCDscreen
TheLCDscreenconsistsoftwolineswith16characterseach.Everycharacterconsistsof5x8or5x11dotmatrix.Thisbookcoversthe5x8 characterdisplay,whichisindeedthemostcommonlyused.

Displaycontrastdependsonthepowersupplyvoltageandwhethermessagesaredisplayedinoneortwolines.Forthisreason,varying voltage0VddisappliedonthepinmarkedasVee.Trimmerpotentiometerisusuallyusedforthatpurpose.SomeLCDdisplayshavebuilt inbacklight(blueorgreendiodes).Whenusedduringoperation,acurrentlimitingresistorshouldbeseriallyconnectedtooneofthepins forbacklight(similartoLEDdiodes).

Iftherearenocharactersdisplayedorifallofthemaredimmedwhenthedisplayisswitchedon,thefirstthingthatshouldbedoneisto checkthepotentiometerforcontrastadjustment.Isitproperlyadjusted?Thesameappliesifthemodeofoperationhasbeenchanged (writinginoneortwolines).

LCDMemory
LCDdisplaycontainsthreememoryblocks:

DDRAMDisplayDataRAM CGRAMCharacterGeneratorRAMand CGROMCharacterGeneratorROM.


DDRAMMemory
DDRAMmemoryisusedforstoringcharactersthatshouldbedisplayed.Thesizeofthismemoryissufficientforstoring80characters. Somememorylocationsaredirectlyconnectedtothecharactersondisplay. Itworksquitesimply:itisenoughtoconfigurethedisplaytoincrementaddressesautomatically(shiftright)andsetthestartingaddressfor themessagethatshouldbedisplayed(forexample00hex). Afterthat,allcharacterssentthroughlinesD0D7willbedisplayedasamessageformatweareusedtofromlefttoright.Inthisverycase, displayingstartsfromthefirstfieldofthefirstlinebecausetheaddressis00hex.Ifmorethan16charactersaresentthenallofthemwillbe memorized,butonlythefirstsixteencharacterswillbevisible.Inordertodisplaytherestofthem,ashiftcommandshouldbeused.Virtually, everythinglooksasiftheLCDdisplayisawindowwhichshiftsleftrightovermemorylocationscontainingdifferentcharacters.Inreality,this ishowtheeffectofmessageshiftingonthescreenhasbeencreated.

Ifthecursorison,itappearsatthelocationwhichiscurrentlyaddressed.Inotherwords,whenacharacterappearsatthecursorposition,it willautomaticallymovetothenextaddressedlocation.

www.mikroe.com/chapters/view/12/appendix-b-examples/

8/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

ThisisasortofRAMmemorysodatacanbewrittentoandreadfromit,butitscontentsisirretrievablylostuponthepowergoesoff.

CGROMMemory
CGROMmemorycontainsthedefaultcharactermapwithallcharactersthatcanbedisplayedonthescreen.Eachcharacterisassignedto onememorylocation:

TheaddressesofCGROMmemorylocationsmatchthecharactersofASCII.Iftheprogrambeingcurrentlyexecutedencountersacommand "sendcharacterPtoport"thenthebinaryvalue01010000appearsontheport.ThisvalueistheASCIIequivalenttothecharacterP.Itis thenwrittentoLCD,whichresultsindisplayingthesymbolfromthe01010000locationofCGROM.Inotherwords,thecharacter"P"is displayed.Thisappliestoalllettersofthealphabet(capitalsandsmall),butnottothenumbers! Asseenonthepreviousmap,addressesofalldigitsarepushedforwardby48relativetotheirvalues(digit0addressis48,digit1address is49,digit2addressis50etc.).Accordingly,inordertodisplaydigitscorrectlyitisnecessarytoaddadecimalnumber48toeachofthem priortosendingthemtoLCD. WhatisASCII?Fromtheirinceptiontilltoday,computerscanrecognizeonlynumbers,butnotletters.Itmeansthatalldataacomputer swapswithaperipheraldevicehasabinaryformateventhoughthesameisrecognizedbythemanasletters(Thekeyboardisanexcellent example)!Itsassimpleasthateverycharactermatchestheuniquecombinationofzeroesandones.ASCIIischaracterencodingbasedon theEnglishalphabet.ASCIIcodespecifiesacorrespondencebetweenstandardcharactersymbolsandtheirnumericalequivalents.

LCDBasicCommands
AlldatatransferredtoLCDthroughtheoutputsD0D7willbeinterpretedasacommandoradata,whichdependsonthepinRSlogicstate: RS=1BitsD0D7areaddressesofthecharacterstobedisplayed.LCDprocessoraddressesonecharacterfromthecharactermapand displaysit.TheDDRAMaddressspecifiesthelocationonwhichthecharacteristobedisplayed.Thisaddressisdefinedpriorcharacter transferortheaddressofthepreviouslytransferredcharacterisautomaticallyincremented. RS=0BitsD0D7arecommandswhichdeterminedisplaymode. ThecommandsrecognizedbytheLCDarelistedintablebelow:
CO MMAND Clear display Cursor home Entry mode set Display on/off control Cursor/Display Shift Function set RS 0 0 0 0 0 0 RW 0 0 0 0 0 0 D7 0 0 0 0 0 0 D6 0 0 0 0 0 0 D5 0 0 0 0 0 1 D4 0 0 0 0 1 DL D3 0 0 0 1 D/C N D2 0 0 1 D R/L F D1 0 1 I/D U x x D0 1 x S B x x EXECUT IO NT IME 1.64mS 1.64mS 40uS 40uS 40uS 40uS

www.mikroe.com/chapters/view/12/appendix-b-examples/

9/43

19/05/13
Set CGRAM address Set DDRAM address Read "BUSY" flag (BF) Write to CGRAM or DDRAM Read from CGRAM or DDRAM 0 0 0 1 1 0 0 1 0 1 0 1 BF D7 D7

Appendix B: Examples - Book: PIC Microcontrollers


1 CGRAM address DDRAM address DDRAM address D6 D6 D5 D5 D4 D4 D3 D3 D2 D2 D1 D1 D0 D0 40uS 40uS 40uS 40uS

I / D 1 = I n c r e m e n t ( b y 1 ) R / L 1 = S h i f t r i g h t 0 = D e c r e m e n t ( b y 1 ) 0 = S h i f t l e f t S 1 = D i s p l a y s h i f t o n D L 1 = 8 b i t i n t e r f a c e 0 = D i s p l a y s h i f t o f f 0 = 4 b i t i n t e r f a c e D 1 = D i s p l a y o n N 1 = D i s p l a y i n t w o l i n e s 0 = D i s p l a y o f f 0 = D i s p l a y i n o n e l i n e U 1 = C u r s o r o n F 1 = C h a r a c t e r f o r m a t 5 x 1 0 d o t s 0 = C u r s o r o f f 0 = C h a r a c t e r f o r m a t 5 x 7 d o t s B 1 = C u r s o r b l i n k o n D / C 1 = D i s p l a y s h i f t 0 = C u r s o r b l i n k o f f 0 = C u r s o r s h i f t

WhatisBusyflag?
Comparedtothemicrocontroller,theLCDisanextremelyslowcomponent.Becauseofthis,itwasnecessarytoprovideasignalwhich would,uponcommandexecution,indicatethatthedisplayisreadyforthenextpieceofdata.Thatsignal,calledthebusyflag,canberead fromthelineD7.Whenthevoltageonthislineis0V(BF=0),thedisplayisreadytoreceivenewdata.

LCDConnecting
DependingonhowmanylinesareusedforconnectingtheLCDtothemicrocontroller,thereare8bitand4bitLCDmodes.The appropriatemodeisselectedatthebeginningoftheoperationinthisprocesscalled"initialization".8bitLCDmodeusesoutputsD0D7to transferdataasexplainedonthepreviouspage. Themainpurposeof4bitLEDmodeistosavevaluableI/Opinsofthemicrocontroller.Only4higherbits(D4D7)areusedfor communication,whileothersmaybeunconnected.EachpieceofdataissenttotheLCDintwostepsfourhigherbitsaresentfirst (normallythroughthelinesD4D7)andfourlowerbitsaresentafterwards.InitializationenablestheLCDtolinkandinterpretreceivedbits correctly.

DataisrarelyreadfromtheLCD(itismainlytransferredfromthemicrocontrollertoLCD)soitisoftenpossibletosaveanextraI/Opinby simpleconnectingR/WpintotheGround.Suchsavinghasitsprice.Messageswillbenormallydisplayed,butitwillnotbepossibletoread thebusyflagsinceitisnotpossibletoreadthedisplayaswell.Fortunately,thereisasimplesolution.Aftersendingacharacterora commanditisimportanttogivetheLCDenoughtimetodoitsjob.Owingtothefactthattheexecutionoftheslowestcommandlastsfor approximately1.64mS,itwillbesufficienttowaitapproximately2mSforLCD.

LCDInitialization
TheLCDisautomaticallyclearedwhenpoweredup.Itlastsforapproximately15mS.Afterthis,displayisreadyforoperation.Themodeof operationissetbydefault.Itmeansthat:

1. Displayiscleared. 2. Mode DL=1Communicationthrough8bitinterface

www.mikroe.com/chapters/view/12/appendix-b-examples/

10/43

19/05/13
N=0Messagesaredisplayedinoneline F=0Characterfont5x8dots

Appendix B: Examples - Book: PIC Microcontrollers

3. Display/Cursoron/off D=0Displayoff U=0Cursoroff B=0Cursorblinkoff 4. Characterentry ID=1Displayedaddressesareautomaticallyincrementedby1 S=0Displayshiftoff


Automaticresetismostlydonewithoutanyproblems.Mostly,butnotalways!Ifforanyreasonpowersupplyvoltagedoesnotreachfull valuewithin10mS,displaywillstartperformingcompletelyunpredictably.Ifvoltagesupplyunitisnotabletomeetthatconditionorifitis neededtoprovidecompletelysafeoperation,theprocessofinitializationisapplied.Initialization,amongotherthings,causesanewreset enablingdisplaytooperatenormally. Refertothefigurebelowfortheprocedureon8bitinitialization:

Itisnotamistake!Inthisalgorithm,thesamevalueistransferredthreetimesinarow. Incaseof4bitinitialization,theprocedureisasfollows:

www.mikroe.com/chapters/view/12/appendix-b-examples/

11/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

EXAMPLE1
WritingheaderandconfiguringI/Opins
TheonlypurposeofthisprogramistoturnonafewLEDdiodesonportB.Itisnothingspecial.Anyway,usethisexampletostudywhata realprogramlookslike.Thefigurebelowshowsaconnectionscheme,whiletheprogramisonthenextpage.

www.mikroe.com/chapters/view/12/appendix-b-examples/

12/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

Whenswitchingon,everyotherLEDdiodeontheportBemitslight.Thatisenoughtoindicatethatthemicrocontrollerisproperlyconnected andoperatesnormally. Thisexamplegivesthedescriptionofacorrectlywrittenheaderandafewinitialdirectives.Theyrepresentapartoftheprogramusedinall programsdescribedinthisbook.Toskiprepetitiveness,itwillnotbewritteninthefollowingexamples,butisconsideredtobeatthe beginningofeveryprogram(markedasa"Header").

Thepurposeoftheheaderandinitialdirectivesisbrieflydescribedbelow.

Header:
Theheaderisplacedatthebeginningoftheprogramandgivesbasicinformationintheformofcomments(nameoftheprogram,release dateetc.).Don'tbedeludedintothinkingthatafterafewmonthsyouwillknowwhatthatprogramisaboutandwhyitissavedinyour computer.

Initialdirectives:

www.mikroe.com/chapters/view/12/appendix-b-examples/

13/43

19/05/13
l i s t p = 1 6 f 8 8 7

Appendix B: Examples - Book: PIC Microcontrollers

Thisdirectivedefinesprocessortoexecuteaprogram.

# i n c l u d e < p 1 6 f 8 8 7 . i n c >

Itenablesthecompilertoaccessthedocumentp16f887.inc(IfyouhaveMPLABinstalled,itisplacedbydefaultonC:\Program files\Microchip\MPASMSuite).EverySFRregistercontainedinthisdocument,aswellaseverybit,hasitsownnameandaddress.Ifthe programreadsforexample:

b s f I N T C O N , G I E

ItmeansthattheGIEbitoftheINTCONregistershouldbeset.Instruction,assuch,makesnosensetothecompiler.Ithastoaccessthe ".inc"documentinordertoknowthattheseventhbitoftheSFRattheaddress000Bhexshouldbeset.

e r r o r l e v e l 3 0 2

Thisisa"cosmetic"directivewhichdisablestheirritatingmessage"Registerinoperandnotin..."toappearattheendofeverycompiling process.Itisnotnecessary,butuseful.

_ _ c o n f i g

Thisdirectiveisusedtoincludeconfigwordintheprogramuponcompiling.Itisnotnecessarybecausethesameoperationisperformedby softwareforloadingprogramintochip.However,doyouhaveanyideawhichsoftwarewillbeusedbytheenduser?Whatoptionswillbe setbydefault?Youaretheenduser?!DoyouknowwhichprogramyouwillbeusingforMCUprogrammingnextyear?Makelifeeasierfor yourself,takethisdirectiveasanecessaryoneandincludeitinyourprogram.

EXAMPLE2
UsingprogramloopandinternaloscillatorLFINTOSC
Thisisacontinuationofthepreviousexample,butdealswithabitmorecomplicatedproblem...TheideaistomaketheLEDdiodesonthe portBblink.Asimplethingatfirstglance!ItisenoughtoperiodicallychangelogicstateontheportB.Inthiscase,numbers01010101and 10101010areselectedtochangeinthefollowingway:

1. Setbinarycombination01010101onportB 2. Remaininloop1

www.mikroe.com/chapters/view/12/appendix-b-examples/

14/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

3. ReplaceexistingbitscombinationonportBwith10101010 4. Remaininloop2and 5. Returntothestep1andrepeatthewholeprocedure.


Doyouknowhowfastthisshouldbedone?ItwouldbepossibletoobservechangesonportBonlyif,apartfromthedelaysprovidedin loop1andloop2,thewholeprocessissloweddownapproximately250timesmore.Becauseofthis,themicrocontrollerusesinternal oscillatorLFINTOSCwiththefrequencyof31kHzinsteadoftheexternaloscillatorwithquartzcrystal(8MHz). Youhavenoticedthattheclocksignalsourcehaschanged"onthefly".Ifyouwanttomakesureofit,removequartzcrystalpriortoswitching themicrocontrolleron.Whatwillhappen?Themicrocontrollerwillnotstartoperatingbecausetheconfigwordloadedwiththeprogram requirestheuseofthecrystalonswitchingon.Ifyouremovethecrystallaterduringtheoperation,itwillnotaffectthemicrocontrolleratall!

SorceCode

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h c o u n t e r 1 V a r i a b l e " c o u n t e r 1 " a t a d d r e s s 2 0 h e n d c * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n b a n k s e l O S C C O N S e l e c t s m e m o r y b a n k c o n t a i n i n g r e g i s t e r O S C C O N b c f O S C C O N , 6 S e l e c t s i n t e r n a l o s c i l l a t o r L F I N T O S C w i t h b c f O S C C O N , 5 t h e f r e q u e n c y o f 3 1 K H z b c f O S C C O N , 4 b s f O S C C O N , 0 M i c r o c o n t r o l l e r u s e s i n t e r n a l o s c i l l a t o r b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B A l l p o r t B p i n s a r e c o n f i g u r e d a s o u t p u t s b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r P O R T B l o o p m o v l w B ' 0 1 0 1 0 1 0 1 ' B i n a r y n u m b e r 0 1 0 1 0 1 0 1 i s w r i t t e n t o W m o v w f P O R T B N u m b e r i s m o v e d t o P O R T B m o v l w h ' F F ' N u m b e r h F F i s m o v e d t o W m o v w f c o u n t e r 1 N u m b e r i s m o v e d t o v a r i a b l e " c o u n t e r 1 " l o o p 1 d e c f s z c o u n t e r 1 V a r i a b l e " c o u n t e r 1 " i s d e c r e m e n t e d b y 1 g o t o l o o p 1 I f r e s u l t i s 0 , c o n t i n u e . I f n o t , r e m a i n i n l o o p 1 m o v l w B ' 1 0 1 0 1 0 1 0 ' B i n a r y n u m b e r 1 0 1 0 1 0 1 0 i s m o v e d t o W m o v w f P O R T B N u m b e r i s m o v e d t o P O R T B m o v l w h ' F F ' N u m b e r h F F i s m o v e d t o W

www.mikroe.com/chapters/view/12/appendix-b-examples/

15/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

m o v w f c o u n t e r 1 N u m b e r i s m o v e d t o v a r i a b l e " c o u n t e r 1 " l o o p 2 d e c f s z c o u n t e r 1 V a r i a b l e " c o u n t e r 1 " i s d e c r e m e n t e d b y 1 g o t o l o o p 2 I f r e s u l t i s 0 , c o n t i n u e . I f n o t , r e m a i n i n l o o p 2 g o t o l o o p G o t o l a b e l l o o p e n d E n d o f p r o g r a m

EXAMPLE3
Usingnestedloop
Theconnectionschemeisagainthesame.Tomakethisabitmoreinteresting,adifferentcombinationofportBbitschangeeachother. And,thatsnotallofcourse.Asseenfromtheprevioustwoexamples,themicrocontrollerisveryfastandoften,itneedstobesloweddown. TheuseofthebuiltinoscillatorLF,asinexample2,isthelastmeasurethatshouldbeapplied.Theproblemismoreoftensolvedbyusing nestedloopsinaprogram.Inthisexample,thevariable"counter1"isdecremented255timesby1intheshorterloop1.Priortoleavingthis loop,theprogramwillcountdown255timesfrom255to0.ItmeansthatbetweenonlytwoLEDdiodesblinkontheport,thereare255x255 pulsescomingfromthequartzoscillator.Preciselyspeaking,thenumberofpulsesamountstoapproximately196000sinceitalsotakes sometimetoexecutejumpinstructionsanddecrementinstructions.Yes,itstrue,themicrocontrollermostlywaitsanddoesnothing...

SourceCode

* * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h c o u n t e r 1 V a r i a b l e " c o u n t e r 1 " a t a d d r e s s 2 0 h c o u n t e r 2 V a r i a b l e " c o u n t e r 2 " a t a d d r e s s 2 1 h e n d c * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B C l e a r s T R I S B b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r P O R T B l o o p m o v l w B ' 1 1 1 1 0 0 0 0 ' B i n a r y n u m b e r 1 1 1 1 0 0 0 0 i s m o v e d t o W m o v w f P O R T B N u m b e r i s m o v e d t o P O R T B m o v l w h ' F F ' N u m b e r h F F i s m o v e d t o W m o v w f c o u n t e r 2 N u m b e r i s m o v e d t o v a r i a b l e " c o u n t e r 2 " l o o p 2 m o v l w h ' F F ' N u m b e r h F F i s m o v e d t o W m o v w f c o u n t e r 1 N u m b e r i s m o v e d t o " c o u n t e r 1 " l o o p 1 d e c f s z c o u n t e r 1 D e c r e m e n t s " c o u n t e r 1 " b y 1 . I f r e s u l t i s 0 g o t o l o o p 1 s k i p n e x t i n s t r u c t i o n d e c f s z c o u n t e r 2 D e c r e m e n t s " c o u n t e r 2 " b y 1 . I f r e s u l t i s 0 g o t o l o o p 2 s k i p n e x t i n s t r u c t i o n m o v l w B ' 0 0 0 0 1 1 1 1 ' B i n a r y n u m b e r 0 0 0 0 1 1 1 1 i s m o v e d t o W m o v w f P O R T B N u m b e r i s m o v e d t o P O R T B m o v l w h ' F F ' N u m b e r h F F i s m o v e d t o W m o v w f c o u n t e r 2 N u m b e r i s m o v e d t o v a r i a b l e " c o u n t e r 2 " l o o p 4 m o v l w h ' F F ' N u m b e r h F F i s m o v e d t o W m o v w f c o u n t e r 1 N u m b e r i s m o v e d t o v a r i a b l e " c o u n t e r 1 " l o o p 3 d e c f s z c o u n t e r 1 D e c r e m e n t s " c o u n t e r 1 " b y 1 . I f r e s u l t i s 0 s k i p n e x t i n s t r u c t i o n g o t o l o o p 3 d e c f s z c o u n t e r 2 D e c r e m e n t s " c o u n t e r 2 " b y 1 . I f r e s u l t i s 0 g o t o l o o p 4 s k i p n e x t i n s t r u c t i o n g o t o l o o p J u m p t o l a b e l l o o p e n d E n d o f p r o g r a m

Example4

www.mikroe.com/chapters/view/12/appendix-b-examples/

16/43

19/05/13
UsingtimerTMR0andInterrupts

Appendix B: Examples - Book: PIC Microcontrollers

Ifyouhavereadthepreviousexample,youwouldhavenoticedadisadvantageofprovidingdelaysusingloops.Inallthesecases,the microcontrolleris"captive"anddoesnothing.Itsimplywaitsforsometimetopass.Suchwastingoftimeisanunacceptableluxuryand someothermethodshouldbeapplied. Doyourememberthestoryaboutthetimers?Aboutinterrupts?Thisexamplemakeslinksbetweentheminapracticalway.Theschematic isstillthesameaswellasthechallenge.Itisnecessarytoprovidedelaylongenoughtonoticechangesonaport.Thistime,thetimer TMR0withtheassignedprescalerisusedforthatpurpose.Interruptoccursoneverytimerregisteroverflowandinterruptroutineincrements thenumberinportBby1.Thewholeprocedureisperformed"behindthescenes"ofthewholeprocess,whichenablesthemicrocontroller todootherthings.

Payattentiontoafewdetails:

Eventhoughitisunnecessaryinthiscase,thecontentsofthemostimportantregisters(W,STATUSandPCLATH) mustbesavedatthebeginningoftheinterruptroutine InterruptcausestheappropriateflagbittobeautomaticallysetandtheGIEbittobeautomaticallycleared.Attheend oftheinterruptroutine,donotforgettoreturnthesebitstothestatetheyhadpriortotheinterruptoccurringand Attheendoftheinterruptrutine,importantregistersshouldbegiventheoriginalcontent.


SourceCode

* * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h w _ t e m p V a r i a b l e a t a d d r e s s 2 0 h p c l a t h _ t e m p V a r i a b l e a t a d d r e s s 2 1 h s t a t u s _ t e m p V a r i a b l e a t a d d r e s s 2 2 h e n d c * * * * * * * * * * * * * * * * * * * * * * * * S T A R T O F P R O G R A M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n g o t o m a i n G o t o l a b e l " m a i n " * * * * * * * * * * * * * * * * * * * * * * * * I N T E R R U P T R O U T I N E * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 4 I n t e r r u p t v e c t o r m o v w f w _ t e m p S a v e s v a l u e i n r e g i s t e r W m o v f S T A T U S S a v e s v a l u e i n r e g i s t e r S T A T U S m o v w f s t a t u s _ t e m p m o v f P C L A T H S a v e s v a l u e i n r e g i s t e r P C L A T H m o v w f p c l a t h _ t e m p b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g P O R T B i n c f P O R T B I n c r e m e n t s r e g i s t e r P O R T B b y 1 b a n k s e l I N T C O N S e l e c t s b a n k c o n t a i n i n g I N T C O N b c f I N T C O N , T M R 0 I F C l e a r s i n t e r r u p t f l a g T M R 0 I F

www.mikroe.com/chapters/view/12/appendix-b-examples/

17/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

m o v f p c l a t h _ t e m p , w P C L A T H i s g i v e n i t s o r i g i n a l c o n t e n t m o v w f P C L A T H m o v f s t a t u s _ t e m p , w S T A T U S i s g i v e n i t s o r i g i n a l c o n t e n t m o v w f S T A T U S s w a p f w _ t e m p , f W i s g i v e n i t s o r i g i n a l c o n t e n t s w a p f w _ t e m p , w b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d r e t f i e R e t u r n f r o m i n t e r r u p t r o u t i n e * * * * * * * * * * * * * * * * * * * * * * * * M A I N P R O G R A M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * m a i n S t a r t o f t h e m a i n p r o g r a m b a n k s e l A N S E L B a n k c o n t a i n i n g r e g i s t e r A N S E L c l r f A N S E L C l e a r s r e g i s t e r s A N S E L a n d A N S E L H c l r f A N S E L H A l l p i n s a r e d i g i t a l b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B A l l p o r t B p i n s a r e c o n f i g u r e d a s o u t p u t s b a n k s e l O P T I O N _ R E G B a n k c o n t a i n i n g r e g i s t e r O P T I O N _ R E G b c f O P T I O N _ R E G , T 0 C S T M R 0 c o u n t s p u l s e s f r o m o s c i l l a t o r b c f O P T I O N _ R E G , P S A P r e s c a l e r i s a s s i g n t o t i m e r T M R 0 b s f O P T I O N _ R E G , P S 0 P r e s c a l e r r a t e i s 1 : 2 5 6 b s f O P T I O N _ R E G , P S 1 b s f O P T I O N _ R E G , P S 2 b a n k s e l I N T C O N B a n k c o n t a i n i n g r e g i s t e r I N T C O N b s f I N T C O N , T M R 0 I E T M R 0 i n t e r r u p t o v e r f l o w e n a b l e d b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d b a n k s e l P O R T B B a n k c o n t a i n i n g r e g i s t e r P O R T B c l r f P O R T B C l e a r s p o r t B l o o p g o t o l o o p R e m a i n h e r e e n d E n d o f p r o g r a m

Example5
Usingsubroutine,usingpushbuttons
Inthepreviousexamplesthemicrocontrollerexecutestheprogramwithoutbeinginfluencedinanywayitssurrounding.Inpractice,devices operatinginthiswayareveryrare(forexample,simpleneonsigns).Youguess,amongothercomponents,inputpinswillalsobeusedin thisexample.Thereisaschematicinthefigurebelow,whiletheprogramisonthenextpage.Everythingisstillverysimple.

Atthebeginningoftheprogram,immediatelyupondefiningvariables,themicrocontrollerpins*areconfiguredbyusingregistersTRISAand TRISB. Inthemainprogram,onebitonportBissetfirst.Thenthecontentsofthisregisterisconstantlymovedbyoneplacetotheleft(instructionrlf

www.mikroe.com/chapters/view/12/appendix-b-examples/

18/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

PORTB).ItgivesustheimpressionthatthelitLEDdiodesismoving.Tomakeitvisible,thewholeprocessmustbeslowenough.Presson thepushbutton"STOP"stopsthemovementandtheprogramremainsinloop3.Delayisprovidedbymeansofanestedloop.Thistime,itis placedinashortsubroutine"DELAY". *ItisnotnecessaryforPORTApinssincetheyareautomaticallyconfiguredasinputsaftereveryreset.

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h c o u n t e r 1 V a r i a b l e " c o u n t e r 1 " a t a d d r e s s 2 0 h c o u n t e r 2 V a r i a b l e " c o u n t e r 2 " a t a d d r e s s 2 1 h e n d c B l o c k o f v a r i a b l e s e n d s * * * * * * * * * * * * * * * * * * * * * * * * M A I N P R O G R A M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g r e g i s t e r A N S E L c l r f A N S E L C l e a r s r e g i s t e r s A N S E L a n d A N S E L H t o c l r f A N S E L H c o n f i g u r e a l l i n p u t s a s d i g i t a l b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B A l l p o r t B p i n s a r e c o n f i g u r e d a s o u t p u t s m o v l w B ' 0 0 0 0 0 0 1 0 ' m o v w f T R I S A P i n R A 1 i s i n p u t b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B m o v l w B ' 0 0 0 0 0 0 0 1 ' W r i t e s 1 t o r e g i s t e r W m o v w f P O R T B N u m b e r i s m o v e d t o P O R T B l o o p r l f P O R T B P o r t B b i t s r o t a t e s b y o n e p l a c e l e f t c a l l D E L A Y C a l l s s u b r o u t i n e " D E L A Y " l o o p 3 b t f s s P O R T A , 1 T e s t s t h e f i r s p o r t A b i t g o t o l o o p 3 " 0 " i s a p p l i e d t o p i n . G o t o l a b e l " l o o p 3 " g o t o l o o p " 1 " i s a p p l i e d t o p i n . G o t o l a b e l " l o o p " * * * * * * * * * * * * * * * * * * * * * * * * S U B R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E L A Y c l r f c o u n t e r 2 C l e a r s v a r i a b l e " c o u n t e r 2 " l o o p 1 c l r f c o u n t e r 1 C l e a r s v a r i a b l e " c o u n t e r 1 " l o o p 2 d e c f s z c o u n t e r 1 D e c r e m e n t s v a r i a b l e " c o u n t e r 1 " b y 1 g o t o l o o p 2 R e s u l t i s n o t 0 . G o t o l a b e l l o o p 2 d e c f s z c o u n t e r 2 D e c r e m e n t s v a r i a b l e " c o u n t e r 2 " b y 1 g o t o l o o p 1 R e s u l t i s n o t 0 . G o t o l a b l o o p 1 r e t u r n R e t u r n f r o m s u b r o u t i n e " D E L A Y " e n d E n d o f p r o g r a m

EXAMPLE6
TMR0asacounter,definingnewvariables,usingrelay
Thistime,TMR0isusedasacounter.Theideaistoconnectthecounterinputtoonepushbuttonsothatitcountsonepulseatatimeupon everybuttonpress.WhenthenumberofcountedpulsesbecomesequaltothenumberinregisterTEST,logiconevoltage(5V)willbe appliedtothePORTD,3pin.Sincethisvoltageactivatesanelectromechanicalrelay,thisbitiscalledthesame"Relay". Inthisexample,theTESTregistercontainsnumber5.Naturally,itcouldbeanynumberandcouldbecalculatedorenteredviathe keyboard.Insteadofarelay,themicrocontrollercanactivatesomeotherdeviceandinsteadofpushbuttonsitcanusesensors.This exampleillustratesoneofthemostcommonusesofthemicrocontrollerinindustry.Whensomethingisdoneasmanytimesasneeded, thensomethingelseshouldbeswitchedonoroff...

www.mikroe.com/chapters/view/12/appendix-b-examples/

19/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * T E S T e q u B ' 0 0 0 0 0 1 0 1 ' B i n a r y n u m b e r 0 0 0 0 0 1 0 1 = T E S T # d e f i n e R E L A Y P O R T D , 3 P i n P O R T D , 3 = R E L A Y * * * * * * * * * * * * * * * * * * * * * * * * M A I N P R O G R A M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B A l l p o r t B p i n s a r e c o n f i g u r e d a s o u t p u t s c l r f T R I S D A l l p o r t D p i n s a r e c o n f i g u r e d a s o u t p u t s m o v l w B ' 0 0 0 1 0 0 0 0 ' T h i s n u m b e r i s w r i t t e n t o W r e g i s t e r m o v w f T R I S A O n l y t h e f o r t h p i n o f p o r t A i s i n p u t b a n k s e l O P T I O N _ R E G B a n k c o n t a i n i n g O P T I O N _ R E G r e g i s t e r b s f O P T I O N _ R E G , T 0 C S P i n R A 4 i s s u p p l i e d w i t h p u l s e s b s f O P T I O N _ R E G , P S A P r e s c a l e r r a t e i s 1 : 1 b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g P O R T B r e g i s t e r c l r f T M R 0 C l e a r s t i m e r r e g i s t e r b c f P O R T D , 3 P i n P O R T D , 3 = 0 l o o p m o v f w T M R 0 T i m e r r e g i s t e r i s m o v e d t o W r e g i s t e r m o v w f P O R T B W r e g i s t e r i s m o v e d t o P O R T B x o r l w T E S T O p e r a t i o n e x c l u s i v e O R b e t w e e n W r e g i s t e r a n d n u m b e r T E S T ( 0 0 0 0 0 1 0 1 ) b t f s c S T A T U S , Z I f n u m b e r s a r e e q u a l , r e s u l t i s 0 a n d b s f P O R T D , 3 b i t S T A T U S , Z = 1 . B i t P O R T D , 3 i s s e t g o t o l o o p a n d j u m p t o l a b e l l o o p i s e x e c u t e d e n d E n d o f p r o g r a m

EXAMPLE7
Usingmacrosintheprogram,usingdebounceroutine
Youhaveprobablynoticedinthepreviousexamplethatthemicrocontrollerdoesnotalwaysoperateasexpected.Namely,bypressingthe pushbutton,thenumberonportBisnotalwaysincrementedby1.Mechanicalpushbuttonsmakeseveralshortsuccessivecontactswhen theyhavebeenactivated.Youguess,themicrocontrollerregistersandcountsallthat...

www.mikroe.com/chapters/view/12/appendix-b-examples/

20/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

Thereareseveralwaystosolvethisproblem.Thisprogramusesprogramdelayknownasdebounce.Basically,itisasimpleprocedure. Uponinputchangedetection(buttonpress),ashortprogramdelayisprovidedandtheprogramwaitsforanotherchange(buttonrelease). Onlyafterthis,theprogramcomestoaconclusionthatthebuttonisactivated. Inthisverycase,thepushbuttonistestedbymeansofmacrocalledbutton.Besides,thismacrocontainsaprogramdelaywhichis providedbymeansofanothermacropausems. Themainprogramisrelativelysimpleandenablesthevariable"cnt"tobeincrementedanddecrementedbyusingtwopushbuttons.This variableisthereaftercopiedtoportBandaffectstheLED(logicone(1)turnsLEDdiodeon,whilelogiczero(0)turnsLEDdiodeoff).

SourceCode

* * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h e x H I c n t L O c n t L O O P c n t c n t e n d c E n d o f b l o c k o f v a r i a b l e s * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 R e s e t v e c t o r n o p g o t o m a i n G o t o p r o g r a m s t a r t ( l a b e l " m a i n " ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * i n c l u d e " p a u s e . i n c " i n c l u d e " b u t t o n . i n c " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * m a i n b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g A N S E L c l r f A N S E L A l l p i n s a r e d i g i t a l c l r f A N S E L H b a n k s e l T R I S B b s f T R I S A , 0 b s f T R I S A , 1 c l r f T R I S B b a n k s e l P O R T B c l r f c n t L o o p b u t t o n P O R T , 0 , 0 , I n c r e m e n t b u t t o n P O R T , 1 , 0 , D e c r e m e n t g o t o L o o p I n c r e m e n t i n c f c n t , f m o v f c n t , w m o v w f P O R T B

www.mikroe.com/chapters/view/12/appendix-b-examples/

21/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

g o t o L o o p D e c r e m e n t d e c f c n t , f m o v f c n t , w m o v w f P O R T B g o t o L o o p e n d E n d o f p r o g r a m

Macro"pausems"

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * p a u s e m s M A C R O a r g 1 l o c a l L o o p 1 l o c a l d e c h i l o c a l D e l a y 1 m s l o c a l L o o p 2 l o c a l E n d m o v l w H i g h ( a r g 1 ) H i g h e r b y t e o f a r g u m e n t i s m o v e d t o H I c n t m o v w f H I c n t m o v l w L o w ( a r g 1 ) L o w e r b y t e o f a r g u m e n t i s m o v e d t o L O c n t m o v w f L O c n t L o o p 1 m o v f L O c n t , f D e c r e m e n t s H I c n t a n d L O c n t w h i l e b t f s c S T A T U S , Z n e e d e d a n d c a l l s s u b r o u t i n e D e l a y 1 m s g o t o d e c h i c a l l D e l a y 1 m s d e c f L O c n t , f g o t o L o o p 1 d e c h i m o v f H I c n t , f b t f s c S T A T U S , Z g o t o E n d c a l l D e l a y 1 m s d e c f H I c n t , f d e c f L O c n t , f g o t o L o o p 1 D e l a y 1 m s : D e l a y 1 m s p r o v i d e s d e l a y o f m o v l w . 1 0 0 1 0 0 * 1 0 u s = 1 m s m o v w f L O O P c n t L O O P c n t < 1 0 0 L o o p 2 : n o p n o p n o p n o p n o p n o p n o p d e c f s z L O O P c n t , f g o t o L o o p 2 E x e c u t i o n t i m e o f L o o p 2 r e t u r n i s 1 0 u s E n d E N D M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Macro"button"

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * b u t t o n M A C R O p o r t , p i n , h i l o , l a b e l l o c a l P r e s s e d 1 A l l l a b e l s a r e l o c a l l o c a l P r e s s e d 2 l o c a l E x i t 1 l o c a l E x i t 2 I F N D E F d e b o u n c e d e l a y E n a b l e s d e b o u n c e t i m e t o b e d e f i n e d i n m a i n p r o g r a m # d e f i n e d e b o u n c e d e l a y . 1 0 E N D I F

www.mikroe.com/chapters/view/12/appendix-b-examples/

22/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

I F ( h i l o = = 0 ) I f p u l l u p u s e d b t f s c p o r t , p i n I f " 1 " , p u s h b u t t o n i s p r e s s e d g o t o E x i t 1 p a u s e m s d e b o u n c e d e l a y W a i t f o r 1 0 m s d e b o u n c e P r e s s e d 1 b t f s s p o r t , p i n g o t o P r e s s e d 1 p a u s e m s d e b o u n c e d e l a y W a i t u n t i l r e l e a s e d a n d g o t o l a b e l j u m p t o s p e c i f i e d a d d r e s s E x i t 1 E L S E I f p u l l d o w n u s e d b t f s s p o r t , p i n g o t o E x i t 2 I f " 0 " , p u s h b u t t o n i s r e l e a s e d p a u s e m s d e b o u n c e d e l a y W a i t f o r 1 0 m s d e b o u n c e P r e s s e d 2 b t f s c p o r t , p i n g o t o P r e s s e d 2 p a u s e m s d e b o u n c e d e l a y W a i t u n t i l r e l e a s e d a n d g o t o l a b e l j u m p t o s p e c i f i e d a d d r e s s E x i t 2 E N D I F E N D M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

EXAMPLE8
UsingtimerTMR1andusinginterrupt
16bittimerTMR1isusedinthisexample.ByoccupyingitsregistersTMR1LandTMR1H,aninterruptoccursandthenumberonportBis incremented.Thishasalreadybeenseeninthepreviousexamples.Thedifferenceisintheprogramdelaywhichisabitlongerthistime becausetheprescalerrateis1:8.

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h w _ t e m p V a r i a b l e a t a d d r e s s 2 0 h p c l a t h _ t e m p V a r i a b l e a t a d d r e s s 2 1 h s t a t u s _ t e m p V a r i a b l e a t a d d r e s s 2 2 h e n d c * * * * * * * * * * * * * * * * * * * * * * * * P R O G R A M S T A R T * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n g o t o m a i n J u m p t o l a b e l " m a i n " * * * * * * * * * * * * * * * * * * * * * * * * I N T E R R U P T R O U T I N E * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

www.mikroe.com/chapters/view/12/appendix-b-examples/

23/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

o r g 0 x 0 0 0 4 I n t e r r u p t v e c t o r m o v w f w _ t e m p S a v e r e g i s t e r W m o v f S T A T U S S a v e r e g i s t e r S T A T U S m o v w f s t a t u s _ t e m p m o v f P C L A T H S a v e r e g i s t e r P C L A T H m o v w f p c l a t h _ t e m p b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g P O R T B i n c f P O R T B R e g i s t e r P O R T B i s i n c r e m e n t e d b y 1 m o v f p c l a t h _ t e m p , w P C L A T H i s g i v e n i t s o r i g i n a l c o n t e n t m o v w f P C L A T H m o v f s t a t u s _ t e m p , w S T A T U S i s g i v e n i t s o r i g i n a l c o n t e n t m o v w f S T A T U S s w a p f w _ t e m p , f W i s g i v e n i t s o r i g i n a l c o n t e n t s w a p f w _ t e m p , w b a n k s e l P I R 1 S e l e c t s b a n k c o n t a i n i n g P I R 1 b c f P I R 1 , T M R 1 I F C l e a r s i n t e r r u p t f l a g T M R 1 I F b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d r e t f i e R e t u r n f r o m i n t e r r u p t r o u t i n e * * * * * * * * * * * * * * * * * * * * * * * * M A I N P R O G R A M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * m a i n S t a r t o f m a i n p r o g r a m b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g r e g i s t e r A N S E L c l r f A N S E L C l e a r s r e g i s t e r s A N S E L a n d A N S E L H c l r f A N S E L H A l l p i n s a r e d i g i t a l b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B A l l p o r t B p i n s a r e c o n f i g u r e d a s o u t p u t s b a n k s e l T 1 C O N S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T 1 C O N b c f T 1 C O N , T M R 1 C S T M R 1 c o u n t s p u l s e s g e n e r a t e d b y o s c i l l a t o r b s f T 1 C O N , T 1 C K P S 0 P r e s c a l e r r a t e i s 1 : 8 b s f T 1 C O N , T 1 C K P S 1 b s f T 1 C O N , T M R 1 O N T u r n s o n t i m e r T M R 1 b a n k s e l P I E 1 S e l e c t s b a n k c o n t a i n i n g r e g i s t e r P I E 1 b s f P I E 1 , T M R 1 I E T M R 1 i n t e r r u p t o v e r f l o w e n a b l e d b s f I N T C O N , P E I E P e r i p h e r a l m o d u l e s i n t e r r u p t e n a b l e d T i m e r T M R 1 b e l o n g s t o p e r i p h e r a l m o d u l e s b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r P O R T B c l r f P O R T B C l e a r s p o r t B l o o p g o t o l o o p R e m a i n h e r e e n d E n d o f p r o g r a m

EXAMPLE9
UsingtimerTMR2,configuringquartzoscillator
ThisexampleillustratestheuseoftimerTMR2.ThemicrocontrollerusesinternaloscillatorHFINTOSCwiththefrequencyof500kHz.The wholeprogramworksasfollows:AftertheperiodoftimedefinedbyregisterPR,prescalerandpostscalerhasexpired,aninterruptoccurs. InterruptroutinedecrementsthecontentofthePRregisterandsimultaneouslyincrementsthecontentofportB.Sincethenumberinregister PR,whichdetermineswheninterruptistooccurisconstantlydecremented,interruptwilloccurforshorterandshorterperiodsoftime.In otherwords,countingwillbecarriedoutfaster.AnewcycleofacceleratedcountingstartsaftereveryregisterPRoverflow.

SourceCode

* * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h w _ t e m p V a r i a b l e a t a d d r e s s 2 0 h p c l a t h _ t e m p V a r i a b l e a t a d d r e s s 2 1 h s t a t u s _ t e m p V a r i a b l e a t a d d r e s s 2 2 h

www.mikroe.com/chapters/view/12/appendix-b-examples/

24/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

e n d c * * * * * * * * * * * * * * * * * * * * * * * * P R O G R A M S T A R T * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n g o t o m a i n J u m p t o l a b e l " m a i n " * * * * * * * * * * * * * * * * * * * * * * * * I N T E R R U P T R O U T I N E * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 4 I n t e r r u p t v e c t o r m o v w f w _ t e m p S a v e r e g i s t e r W m o v f S T A T U S S a v e r e g i s t e r S T A T U S m o v w f s t a t u s _ t e m p m o v f P C L A T H S a v e r e g i s t e r P C L A T H m o v w f p c l a t h _ t e m p b a n k s e l P O R T B S e l e c t s b a n k c o n t a i n i n g P O R T B i n c f P O R T B I n c r e m e n t s P O R T B r e g i s t e r b y 1 b a n k s e l P R 2 S e l e c t s b a n k c o n t a i n i n g P R 2 d e c f P R 2 P R 2 i s d e c r e m e n t e d b y 1 m o v f p c l a t h _ t e m p , w P C L A T H i s g i v e n i t s o r i g i n a l s t a t e m o v w f P C L A T H m o v f s t a t u s _ t e m p , w S T A T U S i s g i v e n i t s o r i g i n a l s t a t e m o v w f S T A T U S s w a p f w _ t e m p , f W i s g i v e n i t s o r i g i n a l s t a t e s w a p f w _ t e m p , w b a n k s e l P I R 1 S e l e c t s b a n k c o n t a i n i n g P I R 1 b c f P I R 1 , T M R 2 I F C l e a r s i n t e r r u p t f l a g T M R 2 I F b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d r e t f i e R e t u r n f r o m i n t e r r u p t r o u t i n e * * * * * * * * * * * * * * * * * * * * * * * * M A I N P R O G R A M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * m a i n S t a r t o f t h e m a i n p r o g r a m b a n k s e l O S C C O N S e l e c t s b a n k c o n t a i n i n g r e g i s t e r O S C C O N b c f O S C C O N , 6 S e l e c t s i n t e r n a l o s c i l l a t o r H F I N T O S C w i t h b s f O S C C O N , 5 f r e q u e n c y o f 5 0 0 K H z b s f O S C C O N , 4 b s f O S C C O N , 0 M i c r o c o n t r o l l e r u s e s i n t e r n a l o s c i l l a t o r b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g r e g i s t e r A N S E L c l r f A N S E L C l e a r s r e g i s t e r s A N S E L a n d A N S E L H c l r f A N S E L H A l l p i n s a r e d i g i t a l b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B A l l p o r t B p i n s a r e c o n f i g u r e d a s o u t p u t s c l r f P R 2 b a n k s e l T 2 C O N S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T 2 C O N m o v l w H ' F F ' S e t s a l l c o n t r o l r e g i s t e r b i t s m o v w f T 2 C O N p r e s c a l e r = 1 : 1 6 , p o s t s c a l e r = 1 : 1 6 T M R 2 = O N c l r f P O R T B b a n k s e l P I E 1 S e l e c t s b a n k c o n t a i n i n g r e g i s t e r P I E 1 b s f P I E 1 , T M R 2 I E T M R 2 i n t e r r u p t e n a b l e d b s f N T C O N , P E I E P e r i p h e r a l m o d u l e s i n t e r r u p t e n a b l e d T i m e r T M R 2 b e l o n g s t o p e r i p h e r a l m o d u l e s b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d l o o p g o t o l o o p R e m a i n h e r e e n d E n d o f p r o g r a m

EXAMPLE10
ModuleCCP1asPWMsignalgenerator
SincetheCCPmoduleshaveawiderangeofpossibilitiestheyarecommonlyusedinpractice.ThisexampleillustratestheuseofCCP1 moduleinPWMmode.BitsoftheCCP1CONregisterdeterminethatthemoduleoperatesasasingleoutputPWM.Thesamebitsdetermine thePWMfrequencytobe4.88kHz.Tomakethingsmoreinteresting,thedurationoftheoutputP1A(PORTC,2)pulsesmaybechangedby meansofpushbuttonssymbolicallycalled"DARK"and"BRIGHT".PushbuttonsaretestedininterruptroutineinitiatedbythetimerTMR1. AnychangeaffectstheLEDdiodesothatitchangeslightintensity.NotethatportBdoesnotuseexternalresistorsbecauseinternalpullup resistorsareenabled.ThewholeprocessofgeneratingPWMsignalisperformed"behindthescenes",whichenablesthemicrocontrollerto

www.mikroe.com/chapters/view/12/appendix-b-examples/

25/43

19/05/13
dootherthings.

Appendix B: Examples - Book: PIC Microcontrollers

SourceCode

* * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h w _ t e m p V a r i a b l e a t a d d r e s s 2 0 h p c l a t h _ t e m p V a r i a b l e a t a d d r e s s 2 1 h s t a t u s _ t e m p V a r i a b l e a t a d d r e s s 2 2 h e n d c # d e f i n e D A R K P O R T B , 0 P u s h b u t t o n " D A R K " i s c o n n e c t e d t o P O R T B , 0 p i n # d e f i n e B R I G H T P O R T B , 1 P u s h b u t t o n " B R I G H T " i s c o n n e c t e d t o P O R T B , 1 p i n * * * * * * * * * * * * * * * * * * * * * * * * P R O G R A M S T A R T * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 F i r s t p r o g r a m i n s t r u c t i o n a d d r e s s g o t o m a i n J u m p t o l a b e l " m a i n " * * * * * * * * * * * * * * * * * * * * * * * * I N T E R R U P T R O U T I N E * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 4 I n t e r r u p t v e c t o r m o v w f w _ t e m p S a v e r e g i s t e r W m o v f S T A T U S S a v e r e g i s t e r S T A T U S m o v w f s t a t u s _ t e m p m o v f P C L A T H S a v e r e g i s t e r P C L A T H m o v w f p c l a t h _ t e m p b a n k s e l C C P R 1 L b t f s s D A R K T e s t s p u s h b u t t o n " D A R K " d e c f C C P R 1 L P u s h b u t t o n i s p r e s s e d d e c r e m e n t C C P 1 L b y 1 b t f s s B R I G H T T e s t i n g p u s h b u t t o n " B R I G H T " i n c f C C P R 1 L P u s h b u t t o n i s p r e s s e d i n c r e m e n t C C P 1 L b y 1 m o v f p c l a t h _ t e m p , w P C L A T H i s g i v e n i t s o r i g i n a l c o n t e n t m o v w f P C L A T H m o v f s t a t u s _ t e m p , w S T A T U S i s g i v e n i t s o r i g i n a l c o n t e n t m o v w f S T A T U S s w a p f w _ t e m p , f W i s g i v e n i t s o r i g i n a l c o n t e n t

www.mikroe.com/chapters/view/12/appendix-b-examples/

26/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

s w a p f w _ t e m p , w b a n k s e l P I R 1 S e l e c t s b a n k c o n t a i n i n g P I R 1 b c f P I R 1 , T M R 1 I F C l e a r s i n t e r r u p t f l a g T M R 1 I F b s f T M R 1 H , 7 A c c e l e r a t e s t i m e r T M R 0 c o u n t i n g b s f T M R 1 H , 6 b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d r e t f i e R e t u r n f r o m i n t e r r u p t r o u t i n e * * * * * * * * * * * * * * * * * * * * * * * * M A I N P R O G R A M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * m a i n S t a r t o f t h e m a i n p r o g r a m b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g r e g i s t e r A N S E L c l r f A N S E L C l e a r s r e g i s t e r s A N S E L a n d A N S E L H c l r f A N S E L H A l l p i n s a r e d i g i t a l b a n k s e l O P T I O N _ R E G S e l e c t s b a n k c o n t a i n i n g r e g i s t e r A N S E L b c f O P T I O N _ R E G , 7 P u l l u p r e s i s t o r s e n a b l e d b s f W P U B , 0 P u l l u p r e s i s t o r s e n a b l e d b s f W P U B , 1 o n p o r t B p i n s 0 a n d 1 b a n k s e l T R I S C S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S C c l r f T R I S C A l l p o r t C p i n s a r e c o n f i g u r e d a s o u t p u t s b a n k s e l T 1 C O N S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T 1 C O N b c f T 1 C O N , T M R 1 C S T M R 1 o p e r a t e s a s a t i m e r b c f T 1 C O N , T 1 C K P S 0 P r e s c a l e r r a t e i s 1 : 8 b c f T 1 C O N , T 1 C K P S 1 b s f T 1 C O N , T M R 1 O N A c t i v a t e s t i m e r T M R 1 b a n k s e l P I E 1 S e l e c t s b a n k c o n t a i n i n g r e g i s t e r P I E 1 b s f P I E 1 , T M R 1 I E I n t e r r u p t T M R 1 i s e n a b l e d b s f I N T C O N , P E I E P e r i p h e r a l m o d u l e s i n t e r r u p t s a r e e n a b l e d b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d m o v l w B ' 1 1 1 1 1 1 0 1 ' P r e s c a l e r T M R 2 = 1 : 4 b a n k s e l T 2 C O N m o v w f T 2 C O N m o v l w B ' 1 1 1 1 1 1 1 1 ' N u m b e r i n r e g i s t e r P R 2 b a n k s e l P R 2 m o v w f P R 2 b a n k s e l C C P 1 C O N m o v l w B ' 0 0 0 0 1 1 0 0 ' B i t s t o c o n f i g u r e C C P 1 m o d u l e m o v w f C C P 1 C O N l o o p g o t o l o o p R e m a i n h e r e e n d E n d o f p r o g r a m

EXAMPLE11
UsingA/Dconverter
PIC16F887A/Dconverterisusedinthisexample.Everythingisquitesimple.AvariableanalogsignalisappliedontheAN2pinwhilethe resultofconversionisshownonportBasabinarynumber.Inordertosimplifytheprogramasmuchaspossible,only8lowerbitsofthe resultofconversionareshown.GNDisusedasanegativevoltagereferenceVref,whilepositivevoltagereferenceisappliedontheAN3 pin.Itenablesvoltagemeasurementscaleto"stretchandshrink". Tomakethisclear,theA/Dconverteralwaysgeneratesa10bitbinaryresult,whichmeansthatitdetectsatotalof1024voltagelevels (210=1024).Thedifferencebetweentwovoltagelevelsisnotalwaysthesame.ThelessthedifferencebetweenVref+andVref,thelessthe differencewillbebetweentwoof1024levels.Accordingly,theA/Dconverterisabletodetectslightchangesinvoltage.

www.mikroe.com/chapters/view/12/appendix-b-examples/

27/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * P R O G R A M S T A R T * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * o r g 0 x 0 0 0 0 A d d r e s s o f t h e f i r s t p r o g r a m i n s t r u c t i o n b a n k s e l T R I S B S e l e c t s b a n k c o n t a i n i n g r e g i s t e r T R I S B c l r f T R I S B A l l p o r t B p i n s a r e c o n f i g u r e d a s o u t p u t s m o v l w B ' 0 0 0 0 1 1 0 0 ' m o v w f T R I S A P i n s R A 2 a n d R A 3 a r e c o n f i g u r e d a s i n p u t s b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g r e g i s t e r A N S E L m o v l w B ' 0 0 0 0 1 1 0 0 ' I n p u t s A N 2 a n d A N 3 a r e a n a l o g w h i l e m o v w f A N S E L a l l o t h e r p i n s a r e d i g i t a l c l r f A N S E L H b a n k s e l A D C O N 1 S e l e c t s b a n k i n c l u d i n g r e g i s t e r A D C O N 1 b s f A D C O N 1 , A D F M R i g h t j u s t i f i c a t i o n o f r e s u l t b c f A D C O N 1 , V C F G 1 V o l t a g e V s s i s u s e d a s V r e f b s f A D C O N 1 , V C F G 0 R A 3 p i n v o l t a g e i s u s e d a s V r e f + b a n k s e l A D C O N 0 S e l e c t s b a n k c o n t a i n i n g r e g i s t e r A D C O N 0 m o v l w B ' 0 0 0 0 1 0 0 1 ' A D c o n v e r t e r u s e s c l o c k F o s c / 2 , A D c h a n n e l m o v w f A D C O N 0 o n R A 2 p i n i s u s e d f o r c o n v e r s i o n a n d A D c o n v e r t e r i s e n a b l e d l o o p b a n k s e l A D C O N 0 b t f s c A D C O N 0 , 1 T e s t s b i t G O / D O N E g o t o l o o p C o n v e r s i o n i n p r o g r e s s , r e m a i n i n l o o p b a n k s e l A D R E S L m o v f A D R E S L , w L o w e r b y t e o f c o n v e r s i o n r e s u l t i s c o p i e d t o W b a n k s e l P O R T B m o v w f P O R T B B y t e i s c o p i e d t o P O R T B b s f A D C O N 0 , 1 S t a r t s n e w c o n v e r s i o n g o t o l o o p J u m p t o l a b e l " l o o p " e n d E n d o f p r o g r a m

EXAMPLE12
UsingEEPROMmemory
ThisexampledemonstrateswritetoandreadfrombuiltinEEPROMmemory.Theprogramworksasfollows.Themainloopconstantly readsEEPROMmemorylocationataddress5(decimal).ThisnumberisdisplayedonportD.Thesameloopteststhestateofthreepush buttonsconnectedtoportA.Thepushbuttons"INCREMENT"and"DECREMENT"havethesamepurposelikeinexample7increment anddecrementthevariable"cnt"whichisthereafterdisplayedonportB.Thepushbutton"MEMO"enablesthatvariabletobewrittento EEPROMmemory.Inordertocheckit,itisenoughtopressthispushbuttonandswitchoffthedevice.Onthenextswitchon,theprogram displaysthevalueofthevariableonportD(atthemomentofwriting,thisvaluewasdisplayedonportB).

www.mikroe.com/chapters/view/12/appendix-b-examples/

28/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

SourceCode

* * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D e f i n i n g v a r i a b l e s i n p r o g r a m * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h H I c n t L O c n t L O O P c n t c n t e n d c E n d o f b l o c k * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 R e s e t v e c t o r n o p g o t o m a i n G o t o s t a r t o f t h e p r o g r a m ( l a b e l " m a i n " ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * i n c l u d e " p a u s e . i n c " i n c l u d e " b u t t o n . i n c " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * m a i n b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g A N S E L c l r f A N S E L c l r f A N S E L H A l l p i n s a r e d i g i t a l b a n k s e l T R I S B b s f T R I S A , 0 I n p u t p i n b s f T R I S A , 1 I n p u t p i n b s f T R I S A , 2 I n p u t p i n c l r f T R I S B A l l p o r t B p i n s a r e o u t p u t s c l r f T R I S D A l l p o r t D p i n s a r e o u t p u t s b a n k s e l P O R T B c l r f P O R T B P O R T B = 0 c l r f P O R T D P O R T D = 0 c l r f c n t c n t = 0 L o o p b a n k s e l P O R T A b u t t o n P O R T A , 0 , 0 , I n c r e m e n t

www.mikroe.com/chapters/view/12/appendix-b-examples/

29/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

b u t t o n P O R T A , 1 , 0 , D e c r e m e n t b u t t o n P O R T A , 2 , 0 , S a v e b a n k s e l E E A D R m o v l w . 5 R e a d s E E P R O M m e m o r y l o c a t i o n m o v w f E E A D R a t a d d r e s s 5 b a n k s e l E E C O N 1 b c f E E C O N 1 , E E P G D b s f E E C O N 1 , R D R e a d s d a t a f r o m E E P R O M m e m o r y b a n k s e l E E D A T A m o v f w E E D A T A M o v e s d a t a t o W b a n k s e l P O R T D m o v w f P O R T D D a t a i s m o v e d f r o m W t o P O R T D g o t o L o o p I n c r e m e n t I n c r e m e n t s n u m b e r o n p o r t B i n c f c n t , f m o v f c n t , w m o v w f P O R T B g o t o L o o p D e c r e m e n t D e c r e m e n t s n u m b e r o n p o r t B d e c f c n t , f m o v f c n t , w m o v w f P O R T B g o t o L o o p S a v e C o p i e s d a t a f r o m p o r t B t o E E P R O M b a n k s e l E E A D R m e m o r y l o c a t i o n a t a d d r e s s 5 m o v l w . 5 m o v w f E E A D R W r i t e s a d d r e s s b a n k s e l P O R T B m o v f w P O R T B C o p i e s p o r t B t o r e g i s t e r W b a n k s e l E E D A T m o v w f E E D A T W r i t e s d a t a t o t e m p o r a r y r e g i s t e r b a n k s e l E E C O N 1 b c f E E C O N 1 , E E P G D b s f E E C O N 1 , W R E N W r i t e e n a b l e d b c f I N T C O N , G I E A l l i n t e r r u p t s d i s a b l e d b t f s c I N T C O N , G I E g o t o $ 2 m o v l w 5 5 h m o v w f E E C O N 2 m o v l w H ' A A ' m o v w f E E C O N 2 b s f E E C O N 1 , W R b t f s c E E C O N 1 , W R W a i t f o r w r i t e t o c o m p l e t e g o t o $ 1 b s f I N T C O N , G I E I n t e r r u p t e n a b l e d b c f E E C O N 1 , W R E N g o t o L o o p T e s t s p u s h b u t t o n s a g a i n e n d E n d o f p r o g r a m

EXAMPLE13
TwodigitLEDcounter,multiplexing
Inthisexample,themicrocontrolleroperatesasatwodigitcounter.Concretely,thevariableDvalisdecremented(slowenoughtobe visible)anditsvalueisdisplayedontwodigitLEDdisplay(990).Thechallengeistoenablebinarynumbertobeconvertedindecimalone andsplititintwodigits(tensandones).Besides,sincetheLEDdisplaysegmentsareconnectedinparallel,itisnecessarytoensurethat theychangefastinordertomakeimpressionofsimultaneouslightemission(timedivisionmultiplexing).Rememberthatinelectronics, multiplexingallowsseveralanalogsignalstobeprocessedbyoneanalogtodigitalconverter(ADC).Inthisverycase,timedivision multiplexingisperformedbythetimerTMR0,whilebinarytodecimalnumberconversionisperformedinmacro"digbyte".Countermaybe resettoitsstartingvalue(99)atanymomentbypressingthepushbutton"COUNTERRESET".

www.mikroe.com/chapters/view/12/appendix-b-examples/

30/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S I N P R O G R A M w _ t e m p E Q U 0 x 7 D V a r i a b l e f o r s a v i n g W r e g i s t e r s t a t u s _ t e m p E Q U 0 x 7 E V a r i a b l e f o r s a v i n g S T A T U S r e g i s t e r p c l a t h _ t e m p E Q U 0 x 7 F V a r i a b l e f o r s a v i n g P C L A T H r e g i s t e r C B L O C K 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h D i g t e m p D i g 0 V a r i a b l e s f o r d i s p l a y i n g d i g i t s L S B D i g 1 D i g 2 D i g 3 V a r i a b l e s f o r d i s p l a y i n g d i g i t s M S B D v a l C o u n t e r v a l u e O n e A u x i l i a r y v a r i a b l e w h i c h d e t e r m i n e s w h i c h d i s p l a y i s t o b e s w i t c h e d o n E N D C E n d o f b l o c k o f v a r i a b l e s p o c _ v r E Q U . 9 9 I n i t i a l c o u n t e r v a l u e i s 9 9 i n c l u d e " D i g b y t e . i n c " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 0 F i r s t i n s t r u c t i o n a d d r e s s g o t o m a i n J u m p t o l a b e l " m a i n " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 4 I n t e r r u p t v e c t o r a d d r e s s m o v w f w _ t e m p M o v e w r e g i s t e r t o w _ t e m p r e g i s t e r m o v f S T A T U S , w M o v e S T A T U S r e g i s t e r t o s t a t u s _ t e m p m o v w f s t a t u s _ t e m p r e g i s t e r m o v f P C L A T H , w M o v e P C L A T H r e g i s t e r t o p c l a t h _ t e m p m o v w f p c l a t h _ t e m p r e g i s t e r S t a r t o f i n t e r r u p t r o u t i n e . . . B A N K S E L T M R 0 m o v l w . 1 0 0 m o v w f T M R 0 b c f I N T C O N , T 0 I F

www.mikroe.com/chapters/view/12/appendix-b-examples/

31/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

b c f P O R T A , 0 b c f P O R T A , 1 b t f s c O n e , 0 g o t o L s d o n g o t o M s d o n L s d o n i n c f O n e , f m o v l w H I G H ( B c d t o 7 s e g ) m o v w f P C L A T H d i g b y t e D v a l m o v f D i g 1 , w c a l l B c d t o 7 s e g P l a c e L 1 m a s k o n t h e P O R T D m o v w f P O R T D b s f P O R T A , 1 g o t o I S R _ e n d M s d o n i n c f O n e , f m o v l w H I G H ( B c d t o 7 s e g ) m o v w f P C L A T H d i g b y t e D v a l m o v f D i g 0 , w c a l l B c d t o 7 s e g P l a c e L O m a s k o n t h e P O R T D m o v w f P O R T D b s f P O R T A , 0 g o t o I S R _ e n d E n d o f i n t e r r u p t r o u t i n e . . . I S R _ e n d m o v f p c l a t h _ t e m p , w P C L A T H r e g i s t e r i s g i v e n i t s o r i g i n a l m o v w f P C L A T H s t a t e m o v f s t a t u s _ t e m p , w S T A T U S r e g i s t e r i s g i v e n i t s o r i g i n a l m o v w f S T A T U S s t a t e s w a p f w _ t e m p , f W r e g i s t e r i s g i v e n i t s o r i g i n a l s t a t e s w a p f w _ t e m p , w r e t f i e R e t u r n f r o m i n t e r r u p t r o u t i n e m a i n b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g A N S E L c l r f A N S E L A l l p i n s a r e d i g i t a l c l r f A N S E L H B A N K S E L T R I S A m o v l w b ' 1 1 1 1 1 1 0 0 ' R A 0 a n d R A 1 a r e c o n f i g u r e d a s o u t p u t s a n d u s e d f o r 7 s e g m e n t d i s p l a y m u l t i p l e x i n g R A 2 i s i n p u t p u s h b u t t o n f o r i n i t i a l i z a t i o n m o v w f T R I S A c l r f T R I S D B A N K S E L O P T I O N _ R E G m o v l w b ' 1 0 0 0 0 1 1 0 ' T M R 0 i s i n c r e m e n t e d e a c h 3 2 u s ( F c l k = 8 M H z ) m o v w f O P T I O N _ R E G B A N K S E L P O R T A m o v l w p o c _ v r m o v w f D v a l D v a l c o n t a i n s c o u n t e r v a l u e m o v l w b ' 0 0 0 0 0 0 0 1 ' I n i t i a l i z e s v a r i a b l e s p e c i f y i n g d i s p l a y m o v w f O n e t o s w i t c h o n m o v w f P O R T A m o v l w . 1 0 0 m o v w f T M R 0 T M R 0 i n t e r r u p t a p p r . e v e r y 1 0 m s b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d b s f I N T C O N , T 0 I E T i m e r T M R 0 i n t e r r u p t e n a b l e d b c f I N T C O N , T 0 I F L o o p b t f s s O n e , 3 F a l l i n g e d g e e n c o u n t e r e d ? g o t o D e c Y e s ! G o t o D e c b t f s s P O R T A , 2 C o u n t e r r e s e t b u t t o n p r e s s e d ?

www.mikroe.com/chapters/view/12/appendix-b-examples/

32/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

g o t o R e s e t Y e s ! G o t o R e s e t g o t o L o o p D e c r e m e n t D v a l c o u n t e r b y 1 D e c b t f s s O n e , 3 g o t o D e c m o v f D v a l , f b t f s c S T A T U S , Z I s D v a l e q u a l t o 0 ? g o t o L o o p I f i t i s , g o t o l o o p a n d w a i t f o r T 2 d e c f D v a l , f I f D v a l n o t e q u a l t o 0 , d e c r e m e n t i t b y 1 g o t o L o o p R e s e t b t f s s P O R T A , 2 W a i t f o r r i s i n g e d g e g o t o R e s e t m o v l w p o c _ v r m o v w f D v a l W r i t e i n i t i a l v a l u e t o c o u n t e r g o t o L o o p * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 3 0 0 L o o k u p t a b l e i s a t t h e t o p o f t h i r d p a g e , b u t c a n b e p l a c e d a t s o m e o t h e r p l a c e , i t i s i m p o r t a n t t o h a v e i t a l l o n o n e p a g e B c d t o 7 s e g a d d w f P C L , f D T 0 x 3 f , 0 x 0 6 , 0 x 5 b , 0 x 4 f , 0 x 6 6 , 0 x 6 d , 0 x 7 d , 0 x 0 7 , 0 x 7 f , 0 x 6 f * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * E N D E n d o f p r o g r a m

Macro"digbyte":

d i g b y t e M A C R O a r g 0 L O C A L E x i t 0 L O C A L E x i t 1 L O C A L E x i t 2 c l r f D i g 0 c l r f D i g 1 c l r f D i g 2 c l r f D i g 3 m o v f a r g 0 , w m o v w f D i g t e m p m o v l w . 1 0 0 E x i t 2 i n c f D i g 2 , f s u b w f D i g t e m p , f b t f s c S T A T U S , C g o t o E x i t 2 d e c f D i g 2 , f a d d w f D i g t e m p , f E x i t 1 m o v l w . 1 0 i n c f D i g 1 , f s u b w f D i g t e m p , f b t f s c S T A T U S , C g o t o E x i t 1 d e c f D i g 1 , f a d d w f D i g t e m p , f E x i t 0 m o v f D i g t e m p , w m o v w f D i g 0 E N D M

Macrodigbyteisusedtoconvertthenumberfromdigitaltodecimalformat.Besides,digitsofsuchdecimalnumberarestoredintospecial registersinordertoenablethemtobedisplayedonLEDdisplays.

EXAMPLE14
Soundgenerating,usingmacros
Thegenerationofsoundisataskcommonlyassignedtothemicrocontroller.Basically,itallcomestogeneratingapulsesequenceonone outputpin.Whiledoingso,theproportionoflogiczero(0)tologicone(1)durationdeterminesthetonepitchandbychangingdifferent tones,differentmelodiesarise. Inthisexample,anypressonpushbuttonsT1andT2generatesasound.Theappropriateinstructionsarestoredinmacro"beep"

www.mikroe.com/chapters/view/12/appendix-b-examples/

33/43

19/05/13
containingtwoarguments.

Appendix B: Examples - Book: PIC Microcontrollers

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D e f i n i n g v a r i a b l e s i n p r o g r a m * * * * * * * * * * * * * * * * * * * * c b l o c k 0 x 2 0 H I c n t A u x i l i a r y v a r i a b l e s f o r m a c r o p a u s e m s L O c n t L O O P c n t P R E S C w a i t B e e p _ T E M P 1 B e l o n g s t o m a c r o " B E E P " B e e p _ T E M P 2 B e e p _ T E M P 3 e n d c # d e f i n e B E E P p o r t P O R T D , 2 S p e a k e r p i n # d e f i n e B E E P t r i s T R I S D , 2 e x p a n d * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 0 R E S E T v e c t o r a d d r e s s g o t o m a i n J u m p t o p r o g r a m s t a r t ( l a b e l m a i n ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * r e m a i n i n g c o d e g o e s h e r e i n c l u d e " p a u s e . i n c " i n c l u d e " b u t t o n . i n c " i n c l u d e " b e e p . i n c " m a i n b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g A N S E L c l r f A N S E L A l l o u t p u t s a r e d i g i t a l c l r f A N S E L H b a n k s e l T R I S D m o v l w b ' 1 1 1 1 1 0 1 1 ' P O R T A D i n i t i a l i z a t i o n m o v w f T R I S D b a n k s e l P O R T D B E E P i n i t M a c r o " B e e p " L o o p

www.mikroe.com/chapters/view/12/appendix-b-examples/

34/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

b u t t o n P O R T D , 0 , 0 , P l a y 1 P u s h b u t t o n 1 b u t t o n P O R T D , 1 , 0 , P l a y 2 P u s h b u t t o n 2 g o t o L o o p P l a y 1 F i r s t t o n e B E E P 0 x F F , 0 x 0 2 B E E P 0 x 9 0 , 0 x 0 5 B E E P 0 x C 0 , 0 x 0 3 B E E P 0 x F F , 0 x 0 3 g o t o L o o p P l a y 2 S e c o n d t o n e B E E P 0 x B B , 0 x 0 2 B E E P 0 x 8 7 , 0 x 0 5 B E E P 0 x A 2 , 0 x 0 3 B E E P 0 x 9 8 , 0 x 0 3 g o t o L o o p * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * E N D E n d o f p r o g r a m

Macro"beep":

B E E P i n i t M A C R O b c f S T A T U S , R P 0 b c f S T A T U S , R P 1 b c f B E E P p o r t b s f S T A T U S , R P 0 b c f S T A T U S , R P 1 b c f B E E P t r i s m o v l w b ' 0 0 0 0 0 1 1 1 ' T M R 0 p r e s c a l e r r a t e 1 : 2 5 6 m o v w f O P T I O N _ R E G O P T I O N < W b c f S T A T U S , R P 0 b c f S T A T U S , R P 1 E N D M B E E P M A C R O f r e q , d u r a t i o n b c f S T A T U S , R P 0 b c f S T A T U S , R P 1 m o v l w f r e q m o v w f B e e p _ T E M P 1 m o v l w d u r a t i o n m o v w f B e e p _ T E M P 2 c a l l B E E P s u b E N D M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * S u b r o u t i n e s B E E P s u b c l r f T M R 0 C o u n t e r i n i t i a l i z a t i o n b c f I N T C O N , T 0 I F b c f B E E P p o r t B E E P a b c f I N T C O N , T 0 I F C l e a r s T M R 0 O v e r f l o w F l a g B E E P b b s f B E E P p o r t c a l l B _ W a i t L o g i c o n e " 1 " d u r a t i o n b c f B E E P p o r t c a l l B _ W a i t L o g i c z e r o " 0 " d u r a t i o n b t f s s I N T C O N , T 0 I F C h e c k T M R 0 O v e r f l o w F l a g , g o t o B E E P b s k i p n e x t i f s e t d e c f s z B e e p _ T E M P 2 , f I s B e e p _ T E M P 2 = 0 ? g o t o B E E P a G o t o B E E P a a g a i n r e t u r n B _ W a i t m o v f B e e p _ T E M P 1 , w m o v w f B e e p _ T E M P 3 B _ W a i t a d e c f s z B e e p _ T E M P 3 , f g o t o B _ W a i t a r e t u r n

EXAMPLE15

www.mikroe.com/chapters/view/12/appendix-b-examples/

35/43

19/05/13
UsingLCDdisplay

Appendix B: Examples - Book: PIC Microcontrollers

ThisexampleillustratestheuseofthealphanumericLCDdisplay.Theprogramitselfisverysimplebecausemacrosareused(usuallythe effortofcreatingMacrospaysoffintheend). Twomessageswrittenontwolineschangeondisplay.Thesecondmessageisintendedtodisplaythecurrenttemperature.Sinceno sensorisinstalled,themeasurementisnotreallycarriedout,thevariable"temp"appearsonthedisplayinsteadofthemeasured temperature. Inreality,thecurrenttemperatureorsomeothermeasuredvaluewouldbedisplayed.

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S I N P R O G R A M C B L O C K 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h H I c n t B e l o n g s t o m a c r o " p a u s e m s " L O c n t L O O P c n t L C D b u f B e l o n g s t o f u n c t i o n s " L C D x x x " L C D t e m p L C D p o r t B u f L C D P o r t B u f f e r D i g t e m p B e l o n g s t o m a c r o " d i g b y t e " D i g 0 D i g 1 D i g 2 D i g 3 t e m p E N D C E n d o f b l o c k L C D p o r t E Q U P O R T B L C D i s o n P O R T B ( 4 d a t a l i n e s o n R B 0 R B 3 ) R S E Q U 4 R S l i n e c o n n e c t e d t o R B 4 E N E Q U 5 E N l i n e c o n n e c t e d t o R B 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 0 R e s e t v e c t o r a d d r e s s n o p g o t o m a i n G o t o b e g i n n i n g o f t h e p r o g r a m ( l a b e l " m a i n " ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * i n c l u d e " L C D . i n c " i n c l u d e " d i g b y t e . i n c " i n c l u d e " p a u s e . i n c " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * m a i n b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g A N S E L c l r f A N S E L A l l p i n s a r e d i g i t a l c l r f A N S E L H

www.mikroe.com/chapters/view/12/appendix-b-examples/

36/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

b c f S T A T U S , R P 0 B a n k 0 a c t i v e o n l y b c f S T A T U S , R P 1 m o v l w . 2 3 m o v w f t e m p M o v e a r b i t r a r y v a l u e t o v a r i a b l e i s t o b e d i s p l a y e d o n L C D l c d i n i t L C D i n i t i a l i z a t i o n L o o p l c d c m d 0 x 0 1 I n s t r u c t i o n t o c l e a r L C D l c d t e x t 1 , " m i k r o e l e k t r o n i k a " W r i t e t e x t f r o m t h e b e g i n n i n g o f t h e f i r s t l i n e l c d t e x t 2 , " B e o g r a d " W r i t e t e x t f r o m t h e b e g i n n i n g o f t h e s e c o n d l i n e p a u s e m s . 2 0 0 0 2 s e c . d e l a y l c d c m d 0 x 0 1 I n s t r u c t i o n t o c l e a r L C D l c d t e x t 1 , " T e m p e r a t u r a 1 " W r i t e t e x t f r o m t h e b e g i n n i n g o f t h e f i r s t l i n e l c d t e x t 2 , " t e m p = " W r i t e t e x t f r o m t h e b e g i n n i n g o f t h e s e c o n d l i n e l c d b y t e t e m p W r i t e v a r i a b l e ( d e c . ) l c d t e x t 0 , " C " W r i t e t e x t a f t e r c u r s o r p a u s e m s . 2 0 0 0 2 s e c . d e l a y g o t o L o o p * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * e n d E n d o f p r o g r a m

LCD.inc

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * I n i t i a l i z a t i o n m u s t b e d o n e b y u s i n g m a c r o l c d i n i t b e f o r e a c c e s s i n g L C D * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * l c d i n i t M A C R O b c f S T A T U S , R P 0 B a n k 0 b c f S T A T U S , R P 1 c l r f L C D p o r t B u f m o v f L C D p o r t B u f , w m o v w f L C D p o r t b s f S T A T U S , R P 0 B a n k 1 b c f S T A T U S , R P 1 c l r f T R I S B L C D p o r t w i t h o u t p u t L C D b c f S T A T U S , R P 0 B a n k 0 b c f S T A T U S , R P 1 F u n c t i o n s e t ( 4 b i t m o d e c h a n g e ) m o v l w b ' 0 0 1 0 0 0 0 0 ' m o v w f L C D b u f s w a p f L C D b u f , w m o v w f L C D p o r t B u f b c f L C D p o r t B u f , R S m o v f L C D p o r t B u f , w m o v w f L C D p o r t b s f L C D p o r t B u f , E N m o v f L C D p o r t B u f , w m o v w f L C D p o r t b c f L C D p o r t B u f , E N m o v f L C D p o r t B u f , w m o v w f L C D p o r t c a l l D e l a y 1 m s 1 m s d e l a y F u n c t i o n s e t ( d i s p l a y m o d e s e t ) l c d c m d b ' 0 0 1 0 1 1 0 0 ' c a l l D e l a y 1 m s 1 m s d e l a y D i s p l a y O N / O F F C o n t r o l l c d c m d b ' 0 0 0 0 1 1 0 0 ' c a l l D e l a y 1 m s 1 m s d e l a y E n t r y M o d e S e t l c d c m d b ' 0 0 0 0 0 1 1 0 ' c a l l D e l a y 1 m s 1 m s d e l a y D i s p l a y C l e a r

www.mikroe.com/chapters/view/12/appendix-b-examples/

37/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

l c d c m d b ' 0 0 0 0 0 0 0 1 ' p a u s e m s . 4 0 4 0 m s d e l a y F u n c t i o n s e t ( 4 b i t m o d e c h a n g e ) m o v l w b ' 0 0 1 0 0 0 0 0 ' m o v w f L C D b u f s w a p f L C D b u f , w m o v w f L C D p o r t B u f b c f L C D p o r t B u f , R S m o v f L C D p o r t B u f , w m o v w f L C D p o r t b s f L C D p o r t B u f , E N m o v f L C D p o r t B u f , w m o v w f L C D p o r t b c f L C D p o r t B u f , E N m o v f L C D p o r t B u f , w m o v w f L C D p o r t c a l l D e l a y 1 m s 1 m s d e l a y F u n c t i o n s e t ( d i s p l a y m o d e s e t ) l c d c m d b ' 0 0 1 0 1 1 0 0 ' c a l l D e l a y 1 m s 1 m s d e l a y D i s p l a y O N / O F F C o n t r o l l c d c m d b ' 0 0 0 0 1 1 0 0 ' c a l l D e l a y 1 m s 1 m s d e l a y E n t r y M o d e S e t l c d c m d b ' 0 0 0 0 0 1 1 0 ' c a l l D e l a y 1 m s 1 m s d e l a y D i s p l a y C l e a r l c d c m d b ' 0 0 0 0 0 0 0 1 ' p a u s e m s . 4 0 4 0 m s d e l a y E N D M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * l c d c m d s e n d s c o m m a n d t o L C D ( s e e t h e t a b l e o n t h e p r e v i o u s p a g e ) l c d c l r i s t h e s a m e a s l c d c m d 0 x 0 1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * l c d c m d M A C R O L C D c o m m a n d S e n d c o m m a n d t o L C D m o v l w L C D c o m m a n d c a l l L C D c o m d E N D M L C D c o m d m o v w f L C D b u f b c f L C D p o r t B u f , R S m o v f L C D p o r t B u f , w m o v w f L C D p o r t g o t o L C D w r L C D d a t a m o v w f L C D b u f b s f L C D p o r t B u f , R S m o v f L C D p o r t B u f , w m o v w f L C D p o r t g o t o L C D w r L C D w r s w a p f L C D b u f , w c a l l S e n d W m o v f L C D b u f , w c a l l S e n d W r e t u r n S e n d W a n d l w 0 x 0 F m o v w f L C D t e m p m o v l w 0 x F 0 a n d w f L C D p o r t B u f , f m o v f L C D t e m p , w i o r w f L C D p o r t B u f , f m o v f L C D p o r t B u f , w m o v w f L C D p o r t

www.mikroe.com/chapters/view/12/appendix-b-examples/

38/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

c a l l D e l a y 1 m s b s f L C D p o r t B u f , E N m o v f L C D p o r t B u f , w m o v w f L C D p o r t b c f L C D p o r t B u f , E N m o v f L C D p o r t B u f , w m o v w f L C D p o r t c a l l D e l a y 1 m s r e t u r n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * l c d t e x t w r i t e s t e x t c o n t a i n i n g 1 6 c h a r a c t e r s w h i c h r e p r e s e n t s a m a c r o a r g u m e n t . T h e f i r s t a r g u m e n t s e l e c t s e l e c t s t h e l i n e i n w h i c h t e x t w r i t i n g i s t o s t a r t . I f s e l e c t i s 0 , t e x t w r i t i n g s t a r t s f r o m c u r s o r c u r r e n t p o s i t i o n . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * l c d t e x t M A C R O s e l e c t , t e x t T h i s m a c r o w r i t e s t e x t f r o m c u r s o r c u r r e n t p o s i t i o n . T e x t i s s p e c i f i e d i n a r g u m e n t c o n s i s t i n g o f 1 6 c h a r a c t e r s l o c a l M e s s a g e l o c a l S t a r t l o c a l E x i t l o c a l i = 0 g o t o S t a r t M e s s a g e D T t e x t C r e a t e l o o k u p t a b l e f r o m a r g u m e n t s D T 0 S t a r t I F ( s e l e c t = = 1 ) l c d c m d b ' 1 0 0 0 0 0 0 0 ' E L S E I F ( s e l e c t = = 2 ) l c d c m d b ' 1 1 0 0 0 0 0 0 ' E N D I F E N D I F W H I L E ( i < 1 6 ) R e p e a t c o n d i t i o n a l p r o g r a m c o m p i l i n g 1 6 t i m e s c a l l M e s s a g e + i R e a d l o o k u p t a b l e a n d p l a c e v a l u e i n W a d d l w 0 b z E x i t u n t i l 0 i s r e a d c a l l L C D d a t a C a l l r o u t i n e d i s p l a y i n g W o n L C D i = i + 1 E N D W E x i t E N D M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * T h i s m a c r o w r i t e s v a l u e i n s i z e o f 1 b y t e o n L C D e x c l u d i n g l e a d i n g z e r o s * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * l c d b y t e M A C R O a r g 0 d i g b y t e a r g 0 A h u n d r e d i s i n D i g 2 , A t e n i s i n D i g 1 a n d o n e i n D i g 0 m o v f D i g 2 , w a d d l w 0 x 3 0 c a l l L C D d a t a m o v f D i g 1 , w I f d i g i t i s 0 m o v e c u r s o r a d d l w 0 x 3 0 c a l l L C D d a t a m o v f D i g 0 , w I f d i g i t i s 0 m o v e c u r s o r a d d l w 0 x 3 0 c a l l L C D d a t a E N D M * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 1 m s D e l a y D e l a y 1 m s : m o v l w . 2 0 0 m o v w f L O O P c n t D e l a y 1 0 u s : n o p 1 u s n o p 1 u s n o p 1 u s n o p 1 u s n o p 1 u s

www.mikroe.com/chapters/view/12/appendix-b-examples/

39/43

19/05/13
n o p 1 u s n o p 1 u s d e c f s z L O O P c n t , f 1 u s g o t o D e l a y 1 0 u s 2 u s r e t u r n

Appendix B: Examples - Book: PIC Microcontrollers

EXAMPLE16
RS232serialcommunication
Thisexampleillustratestheuseofthemicrocontroller'sEUSARTmodule.ConnectiontothePCisenabledthroughRS232standard.The programworksinthefollowingway:EverybytereceivedviatheserialcommunicationisdisplayedusingLEDdiodesconnectedtoportB andisautomaticallyreturnedtothetransmitterthereafter.Ifanerroroccursonreceive,itwillbesignalledbyswitchingtheLEDdiodeon. TheeasiestwaytotestdeviceoperationinpracticeisbyusingastandardWindowsprogramcalledHyperTerminal.

SourceCode

* * * * * * * * * * * * * * * * * * * * * * * H e a d e r * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * D E F I N I N G V A R I A B L E S I N P R O G R A M w _ t e m p E Q U 0 x 7 D V a r i a b l e f o r s a v i n g W r e g i s t e r s t a t u s _ t e m p E Q U 0 x 7 E V a r i a b l e f o r s a v i n g S T A T U S r e g i s t e r p c l a t h _ t e m p E Q U 0 x 7 F V a r i a b l e f o r s a v i n g P C L A T H w r e g i s t e r c b l o c k 0 x 2 0 B l o c k o f v a r i a b l e s s t a r t s a t a d d r e s s 2 0 h P o r t _ A V a r i a b l e a t a d d r e s s 2 0 h P o r t _ B V a r i a b l e a t a d d r e s s 2 1 h R S 2 3 2 t e m p V a r i a b l e a t a d d r e s s 2 2 h R X c h r V a r i a b l e a t a d d r e s s 2 3 h e n d c E n d o f b l o c k o f v a r i a b l e s * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 0 R e s e t v e c t o r n o p g o t o m a i n G o t o b e g i n n i n g o f p r o g r a m ( l a b e l " m a i n " ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * O R G 0 x 0 0 0 4 I n t e r r u p t v e c t o r a d d r e s s m o v w f w _ t e m p S a v e v a l u e o f W r e g i s t e r m o v f S T A T U S , w S a v e v a l u e o f S T A T U S r e g i s t e r m o v w f s t a t u s _ t e m p m o v f P C L A T H , w S a v e v a l u e o f P C L A T H r e g i s t e r m o v w f p c l a t h _ t e m p * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

www.mikroe.com/chapters/view/12/appendix-b-examples/

40/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

T h i s p a r t o f t h e p r o g r a m i s e x e c u t e d i n i n t e r r u p t r o u t i n e b a n k s e l P I E 1 b t f s s P I E 1 , R C I E g o t o I S R _ N o t _ R X 2 3 2 i n t b a n k s e l P I E 1 b t f s c P I R 1 , R C I F c a l l R X 2 3 2 _ i n t _ p r o c I S R _ N o t _ R X 2 3 2 i n t m o v f p c l a t h _ t e m p , w m o v w f P C L A T H P C L A T H i s g i v e n i t s o r i g i n a l v a l u e m o v f s t a t u s _ t e m p , w m o v w f S T A T U S S T A T U S i s g i v e n i t s o r i g i n a l v a l u e s w a p f w _ t e m p , f s w a p f w _ t e m p , w W i s g i v e n i t s o r i g i n a l v a l u e r e t f i e R e t u r n f r o m i n t e r r u p t r o u t i n e * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * R X 2 3 2 _ i n t _ p r o c C h e c k i f e r r o r h a s o c c u r r e d b a n k s e l R C S T A m o v f R C S T A , w m o v w f R S 2 3 2 t e m p b t f s c R S 2 3 2 t e m p , F E R R g o t o R X 2 3 2 _ i n t _ p r o c _ F E R R b t f s c R S 2 3 2 t e m p , O E R R g o t o R X 2 3 2 _ i n t _ p r o c _ O E R R g o t o R X 2 3 2 _ i n t _ p r o c _ C o n t R X 2 3 2 _ i n t _ p r o c _ F E R R b c f R C S T A , C R E N T o c l e a r F E R R b i t , r e c e i v e r i s f i r s t s w i t c h e d o f f a n d o n a f t e r w a r d s n o p D e l a y . . . n o p b s f R C S T A , C R E N m o v f R C R E G , w R e a d s r e c e i v e r e g i s t e r a n d c l e a r s F E R R b i t b s f P o r t _ A , 0 S w i t c h e s L E D o n ( U A R T e r r o r i n d i c a t o r ) m o v f P o r t _ A , w m o v w f P O R T A g o t o R S 2 3 2 _ e x i t R X 2 3 2 _ i n t _ p r o c _ O E R R b c f R C S T A , C R E N C l e a r s O E R R b i t n o p D e l a y . . . n o p b s f R C S T A , C R E N m o v f R C R E G , w R e a d s r e c e i v e r e g i s t e r a n d c l e a r s F E R R b i t b s f P o r t _ A , 1 S w i t c h e s L E D o n ( U A R T e r r o r i n d i c a t o r ) m o v f P o r t _ A , w m o v w f P O R T A g o t o R S 2 3 2 _ e x i t R X 2 3 2 _ i n t _ p r o c _ C o n t m o v f R C R E G , W R e a d s r e c e i v e d d a t a m o v w f R X c h r m o v w f P O R T B m o v w f T X R E G S e n d s d a t a b a c k t o P C R S 2 3 2 _ e x i t r e t u r n R e t u r n f r o m i n t e r r u p t r o u t i n e * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * M a i n p r o g r a m m a i n b a n k s e l A N S E L S e l e c t s b a n k c o n t a i n i n g A N S E L c l r f A N S E L A l l i n p u t s a r e d i g i t a l c l r f A N S E L H P o r t c o n f i g u r a t i o n b a n k s e l T R I S A m o v l w b ' 1 1 1 1 1 1 0 0 ' m o v w f T R I S A

www.mikroe.com/chapters/view/12/appendix-b-examples/

41/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers

m o v l w b ' 0 0 0 0 0 0 0 0 ' m o v w f T R I S B S e t t i n g i n i t i a l v a l u e s b a n k s e l P O R T A m o v l w b ' 1 1 1 1 1 1 0 0 ' m o v w f P O R T A m o v w f P o r t _ A m o v l w b ' 0 0 0 0 0 0 0 0 ' m o v w f P O R T B m o v w f P o r t _ B U S A R T s e t t i n g f o r 3 8 4 0 0 b p s b a n k s e l T R I S C b c f T R I S C , 6 R C 6 / T X / C K = o u t p u t b s f T R I S C , 7 R C 7 / R X / D T = i n p u t b a n k s e l B A U D C T L b s f B A U D C T L , B R G 1 6 b a n k s e l S P B R G m o v l w . 5 1 b a u d r a t e = 3 8 4 0 0 ( F o s c / ( 4 * ( S P B R G + 1 ) ) ) E r r o r + 0 . 1 6 % m o v w f S P B R G c l r f S P B R G H b a n k s e l T X S T A b c f T X S T A , T X 9 D a t a i s 8 b i t w i d e b s f T X S T A , T X E N D a t a t r a n s m i s s i o n e n a b l e d b c f T X S T A , S Y N C A s y n c h r o n o u s m o d e b s f T X S T A , B R G H H i g h s p e e d B a u d r a t e b a n k s e l R C S T A b s f R C S T A , S P E N R X / D T a n d T X / C K o u t p u t s c o n f i g u r a t i o n b c f R C S T A , R X 9 S e l e c t m o d e f o r 8 b i t d a t a r e c e i v e b s f R C S T A , C R E N R e c e i v e d a t a e n a b l e d b c f R C S T A , A D D E N N o a d d r e s s d e t e c t i o n , n i n t h b i t m a y b e u s e d a s p a r i t y b i t m o v f R C S T A , W m o v f R C R E G , W I n t e r r u p t s e n a b l e d b a n k s e l P I E 1 b s f P I E 1 , R C I E U S A R T R x i n t e r r u p t e n a b l e d b s f I N T C O N , P E I E A l l p e r i p h e r a l i n t e r r u p t s e n a b l e d b s f I N T C O N , G I E G l o b a l i n t e r r u p t e n a b l e d R e m a i n h e r e g o t o $ e n d E n d o f p r o g r a m

previouschapter|tableofcontents|nextchapter

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards GPS boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books 8051 Kits

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers AVR Kits

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers ARM Kits

www.mikroe.com/chapters/view/12/appendix-b-examples/

42/43

19/05/13

Appendix B: Examples - Book: PIC Microcontrollers


GSM/GPRS boards

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/12/appendix-b-examples/

43/43

19/05/13

Appendix C: Development Systems - Book: PIC Microcontrollers


Products Solutions Store Distributors Libstock Contact Us

search here

Login | Cart (0)

Book:PICMicrocontrollers
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

FeaturedDevelopmentTools EasyPICv7DevelopmentSystem

AppendixC:DevelopmentSystems
Howtostartworking?
Amicrocontrollerisagoodnatured"genieinthebottle"andnoextraknowledgeisrequiredtouseit. Inordertocreateadevicecontrolledbythemicrocontroller,itisnecessarytoprovidethesimplestPC,programforcompilingandsimple devicetotransferthatcodefromPCtochipitself. Eventhoughthisprocessisquitelogical,thereareoftensomequeries,notbecauseitiscomplicated,butfornumerousvariations.Let'stake alook...
EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures USB2.0programmer/debuggerandover 17essentialmodulesnecessaryin development.Boardcomeswith PIC18F45K22.[moreinfo]

WRITINGPROGRAMINASSEMBLYLANGUAGE
Inordertowriteaprogramforthemicrocontroller,aspecializedprogramintheWindowsenvironmentmaybeused.Anyprogramfortext processingcanbeusedforthispurpose.Thepointistowriteallinstructionsinsuchanordertheyshouldbeexecutedbythe microcontroller,observetherulesofassemblylanguageandwriteinstructionsexactlyastheyaredefined.Inotherwords,youjusthaveto followtheprogramidea!That'sall!Whenusingcustomsoftware,therearenumeroustoolswhicharealsoinstalledtoaidinthe developmentprocess.OnesuchtoolistheSimulator.ThisenablestheusertotestthecodepriortoburningittotheMCU.

FreeOnlineBooks Book:PICMicrocontrollers ProgramminginC

L o o p b u t t o n P O R T A , 0 , 0 , I n c r e m e n t b u t t o n P O R T A , 1 , 0 , D e c r e m e n t g o t o L o o p I n c r e m e n t i n c f c n t , f m o v f c n t , w m o v w f P O R T B g o t o L o o p D e c r e m e n t d e c f c n t , f m o v f c n t , w m o v w f P O R T B
Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone singlechipcapableofcontrollingasmall submarine,acraneoranelevator anything.Itsuptoyoutodecidewhat youwantthemtodo.Youjusthaveto writeaprogramanddumpitintothe microcontroller.[moreinfo]

Toenablethecompilertoperformitstasksuccessfully,itisnecessarythatadocumentcontainingthisprogramhastheextension,.asminits name,forexample:Program.asm Whenaspecializedprogram(MPLAB)isused,thisextensionwillbeautomaticallyadded.Ifanyotherprogramfortextprocessing (Notepad)isusedthenthedocumentshouldbesavedandrenamed.Forexample:Program.txt>Program.asm. Noteforlazyones:skipthisprocedure,openanew.asmdocumentinMPLABandsimplycopy/pastethetextoftheprogramwrittenin assemblylanguage.

COMPILINGPROGRAM
Themicrocontrollerdoesnotunderstandassemblylanguageassuch.Thisiswhyitisnecessarytocompiletheprogramintomachine language.Itismorethansimplewhenusingaspecializedprogram(MPLAB)becauseacompilerispartofthesoftware!Justoneclickon theappropriateiconsolvestheproblemandanewdocumentwith.hexextensionpopsout.Itisactuallythesameprogram,butcompiled intocomputerlanguagewhichthemicrocontrollerperfectlyunderstands.Suchdocumentationiscommonlynamed"hexcode"and seeminglyrepresentsameaninglesssequenceofnumbersinhexadecimalnumericalsystem.

: 0 3 0 0 0 0 0 0 0 2 0 1 0 0 F A 1 0 0 1 0 0 0 0 7 5 8 1 3 F 7 5 9 0 F F B 2 9 0 1 2 0 1 0 D 8 0 F 9 7 A 1 4 7 9 D 4 0 9 0 1 1 0 0 0 3 2 7 8 5 8 9 E A F 3 6 9 8 E 8 E B 2 5 B A 5 8 5 F E A 2 5 6 9 A D 9 6 E 6 D 8 F E D 9 F A D A F 6 D D 0 0 0 0 0 0 0 1 F F 2 5 5 A F E D 5 8 9 E A F 3 6 9 8 E 8 E B 2 5 B A 5 8 5 F E A 2 5 6 9 A D 9 6 D A C 5 9 7 0 0 D 0 0 0 0 0 2 7 8 E 6 D 8 F E D 9 F A D A F 6 D D 0 0 0 0 0 0 0 1 F F 2 5 5 A F E D 8 F E D 9 F A D A F 6 D D 0 0 0 F 7 5 9 0 F F B 2 9 0 1 3 2 7 8 E 6 D 8 F E D 9 F A D A F 6 D D 0 0 0 0 0 0 0 1 F F 2 5 5 A F E D 5 8 9 E A F 3 6 9 8 E 8 E B 2 5 B A 5 8 5 F E A 2 5 6 9 A D 9 6 D A C 5 9 D 9 F A D A F 6 D D 0 0 0 0 0 0 0 1 F F 2 5 5 A F E D 8 F E D 9 F A D A F 6 D D 0 0 0 F 7 5 9 0 F F B 2 9 0 1 3 2 7 8 E 6 D 8 2 7 8 E 6 D 8 F E D 9 F A 5 8 9 E A F 3 6 9 8 E 8 E B 2 5 B A 5 8 5 F E A 2 5 6 9 A D 9 6 D A F 6 D D 0 0 0 0 0 0 0 1 F F 2 D A F 6 D D 0 0 0 0 0 0 0 1 F F 2 5 5 A

www.mikroe.com/chapters/view/13/appendix-c-development-systems/

1/4

19/05/13
A D A F 6 D D 0 0 0 0 0 0 0 1 F F 2 5 5 A F E D 8 F E D 9 F A

Appendix C: Development Systems - Book: PIC Microcontrollers

Incaseothersoftwareforprogramwritinginassemblylanguageisused,specialsoftwareforcompilingtheprogrammustbeinstalledand usedasfollows:setupthecompiler,openthedocumentwith.asmextensionandcompile.Theresultisthesameanewdocumentwith .hexextension.TheonlyproblemyouhavenowisthatitisstoredinyourPC.

PROGRAMMINGAMICROCONTROLLER
Toenable"hexcode"transmissiontothemicrocontrolleritisnecessarytoprovideacableforserialcommunicationandaspecialdevice calledprogrammerwithappropriatesoftware.Thereareseveralwaystodoit. AlotofprogramsandelectroniccircuitshavingthispurposecanbefoundontheInternet.Doasfollows:openhexcodedocument,setafew parametersandclicktheiconforcompiling.Afterawhile,asequenceofzerosandonesistobeprogrammedintothemicrocontroller throughtheserialconnectioncableandprogrammerhardware.Thereisnothingelsetobedoneexceptforplacingtheprogrammedchip intothetargetdevice.Incaseitisnecessarytomakesomechangesintheprogram,thepreviousproceduremayberepeatedanunlimited numberoftimes.

Isthisahappyending?
ThissectionbrieflydescribestheuseofMPLABandprogrammersoftwaredevelopedbyMikroelektronika.Everythingisverysimple... YouhavealreadyinstalledMPLAB,haventyou?Openanewprojectandanewdocumentwithextension.asm.

OK.Youhavewrittenaprogramandtesteditwiththesimulator.Theprogramdidnotreportsanyerrorduringthecompilingprocess?It seemsthateverythingisundercontrol...

Theprogramiswrittenandsuccessfullycompiled.Allthatsleftistodumptheprogramtothemicrocontroller.Forthispurposeitis necessarytohavesoftwarethattakesthewrittenandcompiledprogramandpassesitintothemicrocontroller(PICFlashforexample).Start upthisprogram... Thesettingsaresimpleandthereisnoneedforadditionalexplanations(thetypeofthemicrocontroller,frequencyandclockoscillatoretc.).

ConnectthePCandprogrammerviaaUSBcable LoadtheHEXcodeusingcommand:File>LoadHEXand Clickthe"Write"pushbuttonandwait...

www.mikroe.com/chapters/view/13/appendix-c-development-systems/

2/4

19/05/13

Appendix C: Development Systems - Book: PIC Microcontrollers

That'sit!Themicrocontrollerisprogrammedandeverythingisreadyforoperation.Ifyouarenotsatisfied,makesomechangesinthe programandrepeattheprocedure.Untilwhen?Untilyoufeelsatisfied...

Developmentsystems
Adevice,whichintestingprogramphase,cansimulateanyenvironmentiscalledadevelopmentsystem.Apartfromtheprogrammer,the powersupplyunitandthemicrocontrollerssocket,thedevelopmentsystemcontainselementsforinputpinactivationandoutputpin monitoring.ThesimplestversionhaseverypinconnectedtoonepushbuttonandoneLEDaswell.AhighqualityversionhasLED displays,LCDdisplays,temperaturesensorsandallotherelementswhichthetargetdevicecanbesuppliedwith.Theseperipheralscould beconnectedtotheMCUviaminiaturejumpers.Inthisway,thewholeprogrammaybetestedinpractice,duringitsdevelopmentstage, becausethemicrocontrollerdoesnotknow,orcare,whetheritsinputisactivatedbyapushbuttonorasensorbuiltinarealmachine.

DevelopmentsystemEasyPIC5

previouschapter|tableofcontents

MikroElektronika Embedded Solutions


PIC Solution
PIC Development Boards PIC Compilers PIC Programmers/Debuggers PIC Kits PIC Books

Follow us on
Add-on boards
Click Boards mikromedia shields Communication boards Storage boards Real Time Clock boards Display boards Measurement boards Audio & Voice boards Power Supply boards

dsPIC Solution
dsPIC Development Boards dsPIC Compilers dsPIC Programmers/Debuggers dsPIC Kits dsPIC Books

PIC32 Solution
PIC32 Development Boards PIC32 Compilers PIC32 Programmers/Debuggers PIC32 Kits

Additional Software
Visual TFT Visual GLCD Package Manager GLCD Font Creator

8051 Solution
8051 Development Boards 8051 Compilers 8051 Programmers/Debuggers 8051 Books

AVR Solution
AVR Development Boards AVR Compilers AVR Programmers/Debuggers

ARM Solution
ARM Development Boards ARM Compilers ARM Programmers/Debuggers

www.mikroe.com/chapters/view/13/appendix-c-development-systems/

3/4

19/05/13
AVR Kits ARM Kits

Appendix C: Development Systems - Book: PIC Microcontrollers


8051 Kits GPS boards GSM/GPRS boards

Support

Forum

mikroBUS

Lets make

Press

Legal Information

Product Archive

About Us

Copyright 1998 - 2013. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.

www.mikroe.com/chapters/view/13/appendix-c-development-systems/

4/4