Professional Documents
Culture Documents
search here
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.
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
Fig.01MicrocontrollerversusMicroprocessor
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
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
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
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.
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
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.
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
EXCLUSIVEORGate
TheEXCLUSIVEOR(XOR)gateisabitcomplicatedcomparingtoothergates.Itrepresentsacombination ofallthepreviouslydescribedgates.Alogicone(1)appearsonitsoutputonlywhentheinputshave differentlogicstates.
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
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
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:
www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/
8/16
19/05/13
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:
Fig.023Serialcommunication
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
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.
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
Fig.027Timers/Counters
Howdoesatimeroperate?
Inpracticepulsescomingfromthequartzoscillatorareoncepereachmachinecycledirectlyorviaaprescalerbroughttothecircuitwhich incrementsthenumberinthetimerregister.Ifoneinstruction(onemachinecycle)lastsforfourquartzoscillatorperiodsthen,byembedding quartzwiththefrequencyof4MHz,thisnumberwillbechangedamilliontimespersecond(eachmicrosecond).
Fig.028TimerOperation
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
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
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
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
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
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
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
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
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
search here
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)
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
Fig.12PIC16F887QFN44Microcontroller
Fig.13PIC16F887BlockDiagram
PinDescription
AsseeninFig.11above,themostpinsaremultifunctional.Forexample,designatorRA3/AN3/Vref+/C1IN+forthefifthpinspecifiesthe followingfunctions:
www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/
2/12
19/05/13
Table11PinAssignment
www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/
3/12
19/05/13
Table11cont.PinAssignment
www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/
4/12
19/05/13
Table11cont.PinAssignment
CentralProcessorUnit(CPU)
ImnotgoingtoboreyouwiththeoperationoftheCPUatthisstage,howeveritisimportanttostatethattheCPUismanufacturedwithin RISCtechnologyanimportantfactorwhendecidingwhichmicroprocessortouse. RISCReducedInstructionSetComputer,givesthePIC16F887twogreatadvantages:
www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/
5/12
19/05/13
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
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
Table12AddressBanks
www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/
8/12
19/05/13
Table13SFRBank0
www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/
9/12
19/05/13
Table14SFRBank1
Table15SFRBank2
www.mikroe.com/chapters/view/2/chapter-1-pic16f887-microcontroller-device-overview/
10/12
19/05/13
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
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
search here
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:
STATUSRegister
Fig.21STATUSRegister
IRP Bitselectsregisterbank.Itisusedforindirectaddressing.
1Banks0and1areactive(memorylocation00hFFh) 0Banks2and3areactive(memorylocation100h1FFh)
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
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
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
Asseen,everythingisbasedonasimpleandefficientidea.Whenaninterruptrequestarrives,theflagbitistobesetfirst.
Fig.28InterruptSystemRegisters
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.
T0IETMR0OverflowInterruptEnablebitcontrolsinterruptenabledbyTMR0overflow.
1EnablestheTMR0interrupt. 0DisablestheTMR0interrupt.
INTERB0/INTExternalInterruptEnablebitcontrolsinterruptcausedbychanginglogicstateonpinRB0/IN (externalinterrupt).
1EnablestheINTexternalinterrupt. 0DisablestheINTexternalinterrupt.
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
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
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
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
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
Fig.218DirectandIndirectaddressing
previouschapter|tableofcontents|nextchapter
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
search here
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:
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
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
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:
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
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
Fig.48TMR1intimermode
Themicrocontrollersclockoscillatordoesnotrunduringsleepmodesothetimerregisteroverflowcannotcauseanyinterrupt.
TimerTMR1Oscillator
ThepowerconsumptionofthemicrocontrollerisreducedtothelowestlevelinSleepmode.Thepointistostoptheoscillator.Anyway,itis easytosetthetimerinthismodebywritingaSLEEPinstructiontotheprogram.Aproblemoccurswhenitisnecessarytowakeupthe microcontrollerbecauseonlyaninterruptcandothat.Sincethemicrocontrollersleeps,aninterruptmustbetriggeredbyexternal electronics.Itcanallgetincrediblycomplicatedifitisnecessarythewakeupoccursatregulartimeintervals...
Fig.49TimerTMR1Oscillator
www.mikroe.com/chapters/view/5/chapter-4-timers/
5/8
19/05/13
Fig.411CounterMode
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
1Donotsynchronizeexternalclockinputand 0Synchronizeexternalclockinput.
TMR1CSTimerTMR1ClockSourceSelectbit
1CountspulsesontheT1CKIpin(ontherisingedge01)and 0Countspulsesoftheinternalclockofmicrocontroller.
TMR1ONTimer1Onbit
1EnablesTimerTMR1and
www.mikroe.com/chapters/view/5/chapter-4-timers/
6/8
19/05/13
0StopsTimerTMR1.
InordertousethetimerTMR1properly,itisnecessarytoperformthefollowing:
TimerTMR2
TimerTMR2moduleisan8bittimerwhichoperatesinaveryspecificway.
Fig.413TimerTMR2
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
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:
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
search here
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]
CCP1Module
Acentralpartofthiscircuitisa16bitregisterCCPR1,whichconsistsoftheCCPR1LandCCPR1Hregisters.Itisusedforcapturingor comparingwithbinarynumberstoredinthetimerregisterTMR1(TMR1HandTMR1L).
Fig.51CCP1Module
CCP1inCapturemode
Inthismode,thetimerregisterTMR1(consistingofTMR1HandTMR1L)iscopiedtotheCCP1register(consistingofCCPR1Hand CCPR1L)inthefollowingsituations:
RC2/CCP1pinmustbeconfiguredasinputand TMR1modulemustoperateastimerorsynchronouscounter.
www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/
1/11
19/05/13
Fig.52CCP1inCapturemode
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
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
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:
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
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
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 16th rising edge on the CCP1 pin Compare mode
www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/
5/11
19/05/13
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
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
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:
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
Fig.511SingleOutputPWMMode
HalfBridgeMode
Inthismode,thePWMsignalisoutputontheP1Apin,whileatthesametimethecomplementaryPWMsignalisoutputontheP1Bpin. SuchpulsesactivateMOSFETdriversinHalfBridgemodewhichenable/disablecurrentflowthroughdevice.
Fig.512HalfBridgeMode
Fig.513HalfBridgeMode
Asshowninfigure514,thesamemodecanbeusedtoactivateMOSFETdriversinFullBridge:
www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/
8/11
19/05/13
Fig.514ActivateMOSFETdrivers
FullBridgeMode
InFullBridgemode,allfourpinsareusedasoutputs.Inpractice,thismodeiscommonlyusedtorunmotors,whichprovidessimpleand completecontrolofspeedandrotationdirection.Therearetwosuchconfigurations:FullBridgeForwardandFullBridgeReverse.
Fig.515FullBridgeMode
FullBridgeForwardConfiguration
InForwardmodethefollowingoccurs:
Fig.516ForwardMode
FullBridgeReverseConfiguration
ThesameoccursinReversemode,exceptofthepinsfunctions:
www.mikroe.com/chapters/view/6/chapter-5-ccp-modules/
9/11
19/05/13
Fig.517ReverseMode
PWM1CONRegisterSTRCPWMRestartEnablebit
Fig.518PWM1CONRegister
PSTRCONRegister
STRSYNCSteeringSyncbitdeterminesthemomentofPWMpulsesteering:
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.
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
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
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
search here
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]
TheEUSARTsystemintegratedintothePIC16F887microcontrollerhasthefollowingfeatures:
Fig.62EUSARTAsynchronousMode
Briefly,eachdataistransferredinthefollowingway:
EUSARTAsynchronousTransmitter
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
1/18
19/05/13
Fig.63EUSARTAsynchronousTransmitter
EUSARTAsynchronousReceiver
Fig.64EUSARTAsynchronousReceiver
SimilartotheactivationofEUSARTtransmitter,inordertoenablethereceiveritisnecessarytodefinethefollowingbits:
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
2/18
19/05/13
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:
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
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
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
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
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
6/18
19/05/13
Table62DeterminingBaudRate
BAUDCTLRegister
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
7/18
19/05/13
Fig.611BAUDCTLRegister
ABDOVFAutoBaudDetectOverflowbitisonlyusedinasynchronousmodeduringbaudratedetection.
1Autobaudtimeroverflowedand 0Autobaudtimerdidnotoverflow.
RCIDLReceiveIdleFlagbitisonlyusedinasynchronousmode.
1Receiverisidleand 0STARTbithasbeenreceivedandreceivingisinprogress.
SCKPSynchronousClockPolaritySelectbitactsdifferentlydependingonEUSARTmode. Asynchronousmode:
1TransmitinverteddatatotheRC6/TX/CKpinand 0Transmitnoninverteddatatothesamepin.
Synchronousmode:
1Synchronizationonrisingedgeoftheclockand 0Synchronizationonfallingedgeoftheclock.
WUEWakeupEnablebit
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:
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
8/18
19/05/13
enableserialport
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:
SSPSTATstatusregister
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
9/18
19/05/13
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:
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).
throughinputpin.InMastermode,themicrocontrolleritselfgeneratesclock,whiletheSlavemode
Fig.617Step3
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
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
11/18
19/05/13
Fig.621DataTransfer
FigurebelowshowstheblockdiagramoftheMSSPmoduleinICmode.
Fig.622MSSPBlockDiagraminICMode
TheMSSPmoduleusessixregistersforICoperation.Someofthemareshowninfigureabove:
www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/
12/18
19/05/13
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
Fig.624SSPCONRegister
WCOLWriteCollisionDetectbit
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
Fig.625SSPCON2Register
GCENGeneralCallEnablebit InICslavemodeonly
1Enablesinterruptwhenageneralcalladdress(0000h)isreceivedintheSSPSRand 0Generalcalladdressdisabled.
ACKSTATAcknowledgeStatusbit InICMasterTransmitmodeonly
1Acknowledgewasnotreceivedfromslaveand 0Acknowledgewasreceivedfromslave.
ACKDTAcknowledgedatabit InICMasterReceivemodeonly
1NotAcknowledgeand 0Acknowledge.
ACKENAcknowledgeconditionEnablebit InICMasterReceivemode
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
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
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
Fig.632OpenDrainOutputResistors
InShort:
InordertoestablishserialcommunicationinICmode,thefollowingshouldbedone:
SettingModuleandSendingAddress:
ValuetodeterminebaudrateshouldbewrittentotheSSPADDregister SlewRatecontrolshouldbeturnedoffbysettingtheSMPbitoftheSSPSTATregister InordertoselectMastermode,binaryvalue1000shouldbewrittentotheSSPM3SSPM0bitsoftheSSPCON1 register TheSENbitoftheSSPCON2registershouldbeset(STARTcondition) TheSSPIFbitisautomaticallysetattheendofSTARTconditionwhenthemoduleisreadytooperate.Itshouldbe cleared SlaveaddressshouldbewrittentotheSSPBUFregisterand Whenthebyteissent,theSSPIFbit(interrupt)isautomaticallysetwhentheacknowledgebithasbeenreceivedfrom theSlavedevice.
DataTransmit:
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
search here
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:
ADCModeandRegisters
EventhoughtheuseofA/Dconverterseemstobeverycomplicated,itisbasicallyverysimple,simplerthanusingtimersandserial communicationmodule,anyway.
Fig.71ADCModeandRegisters
Themoduleisunderthecontrolofthebitsoffourregisters:
www.mikroe.com/chapters/view/8/chapter-7-analog-modules/
1/9
19/05/13
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
ADCS1
ADCS0
Table71ADCClockPeriod
AnychangeinthesystemclockfrequencywillaffecttheADCclockfrequency,whichmayadverselyaffecttheADCresult.Devicefrequency characteristicsareshowninthetableabove.Thevaluesintheshadedcellsareoutsideofrecommendedrange.
HowtoUseA/DConverter?
InordertoenabletheA/Dconvertertorunwithoutproblemsaswellastoavoidunexpectedresults,itisnecessarytoconsiderthefollowing:
Fig.73HowtoUseTheA/DConverter
www.mikroe.com/chapters/view/8/chapter-7-analog-modules/
2/9
19/05/13
ADCON0Register
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
0Conversionresultleftjustified.SixleastsignificantbitsoftheADRESLarenotused.
VCFG1VoltageReferencebitselectsnegativevoltagereferencesourceneededforA/Dconverteroperating.
1NegativevoltagereferenceisappliedontheVrefpinand 0VoltagepowersupplyVssisusedasnegativevoltagereferencesource.
VCFG0VoltageReferencebitselectspositivevoltagereferencesourceneededforA/Dconverteroperating.
1PositivevoltagereferenceisappliedontheVref+pinand 0VoltagepowersupplyVddisusedaspositivevoltagereferencesource.
InShort:
InordertomeasurevoltageonaninputpinbyA/Dconverterthefollowingshouldbedone: Step1Configuringport:
Writelogicone(1)tothecorrespondingbitoftheTRISregistertoconfigureitasinputand Writelogicone(1)tothecorrespondingbitoftheANSELregistertoconfigureitasanaloginput.
Step2ConfiguringADCmodule:
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
www.mikroe.com/chapters/view/8/chapter-7-analog-modules/
4/9
19/05/13
VoltageReferenceInternalSource
Fig.77VREF
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
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
Table74ComparatorC1
CM2CON0Register
Fig.710CM2CON0Regsiter
BitsofthisregisterareincontrolofcomparatorC2.Similartothepreviouscase,thefigure711showsasimplifiedschematicofthecircuit affectedbythebitsofthisregister.
www.mikroe.com/chapters/view/8/chapter-7-analog-modules/
6/9
19/05/13
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
Table75ComparatorC2ChannelSelectBit
CM2CON1Register
Fig.712CM2CON1Register
MC1OUTMirrorCopyofC1OUTbit
www.mikroe.com/chapters/view/8/chapter-7-analog-modules/
7/9
19/05/13
MC2OUTMirrorCopyofC2OUTbit C1RSELComparatorC1ReferenceSelectbit
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:
www.mikroe.com/chapters/view/8/chapter-7-analog-modules/
8/9
19/05/13
Vladder=Vddor([Vref+][Vref])orVref+ Step3Startingoperation:
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
search here
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.
Fig.81Twobuiltinoscillators
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
Table81InternalOscillatorFrequencySelectBits
OSTSOscillatorStartupTimeoutStatusbitindicateswhichclocksourceiscurrentlyinuse.Thisbitisreadableonly.
1Externalclockoscillatorisinuseand 0Oneofinternalclockoscillatorsisinuse(HFINTOSCorLFINTOSC).
HTSHFINTOSCStatusbit(8MHz125kHz)indicateswhetherhighfrequencyinternaloscillatoroperatesinastableway.
1HFINTOSCisstableand 0HFINTOSCisnotstable.
LTSLFINTOSCStablebit(31kHz)indicateswhetherlowfrequencyinternaloscillatoroperatesinastableway.
1LFINTOSCisstableand 0LFINTOSCisnotstable.
SCSSystemClockSelectbitdetermineswhichoscillatoristobeusedasaclocksource.
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).
Fig.84ExternalOscillator
Thismodehasthefollowingadvantages:
Fig.85ExternalOscillatorinECMode
ExternaloscillatorinLP,XTorHSmode
Fig.86TwoTypesofExternalOscillators
www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/
3/10
19/05/13
Fig.87SchematicofExternalOscillatorandAdditionalExternalComponents
CeramicresonatorsinXTorHSmode
Fig.88CeramicResonator
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
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
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
Fig.814EnableIntExtSwitchover
Fig.815FailSafeClockMonitor
www.mikroe.com/chapters/view/9/chapter-8-other-mcu-s-circuits/
6/10
19/05/13
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
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
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
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
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
search here
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 *
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
Table9116FxxInstructionSet
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
[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
www.mikroe.com/chapters/view/10/chapter-9-instruction-set/
3/18
19/05/13
. . . . [ 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:
. . . . [ 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
. . . . [ 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
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:
. . . . 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 .
. . . . 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
. . . . [ 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
. . . . [ 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
. . . . [ 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
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
. . . . [ 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
. . . . [ 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
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
. . . . 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
. . . . 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
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
. . . . 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
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:
. . . . [ 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:
. . . . [ 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
. . . . [ 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
www.mikroe.com/chapters/view/10/chapter-9-instruction-set/
12/18
19/05/13
EXAMPLE:
. . . . [ 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
. . . . [ 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
. . . . [ 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
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
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
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
Fig.92fRegister
www.mikroe.com/chapters/view/10/chapter-9-instruction-set/
14/18
19/05/13
EXAMPLE1:
. . . . [ 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
. . . . [ 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
. . . . [ 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
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
. . . . [ 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
. . . . [ 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
www.mikroe.com/chapters/view/10/chapter-9-instruction-set/
16/18
19/05/13
Statusaffected:Z Numberofcycles:1 EXAMPLE1:
. . . . [ 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
. . . . [ 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 )
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
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
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
search here
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.
ELEMENTSOFASSEMBLYLANGUAGE
Aprogramwritteninassemblylanguageconsistsofseveralelementsbeingdifferentlyinterpretedwhilecompilingtheprogramintoan executabledatafile.Theuseoftheseelementsrequiresstrictrulesanditisnecessarytopayspecialattentiontothemduringprogram writinginordertoavoiderrors.
ASSEMBLYLANGUAGESYNTAX
Asmentioned,itisnecessarytoobservesomespecificrulesinordertoenabletheprocessofcompilingintoexecutiveHEXcodetorun withouterrors.Compulsoryrulesexplaininghowsequencesofexpressionsareputtogethertoformthestatementsthatmakeupan assemblylanguageprogramarecalledsyntax.Thereareonlyseveralofthem:
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
1/16
19/05/13
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
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
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:
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
3/16
19/05/13
Example1:
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 . . .
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
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:
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
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
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
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
SUBROUTINES
Asubroutinecontainsasequenceofinstructions,beginswithalabel(subroutine_name)andendswithcommandreturnorretlw.Themain differencecomparingtomacroisthatsubroutineisnotreplacedbyitscodeintheprogram,butprogramjumpstosubroutinetoexecuteit.It happenseverytimetheassemblerencounterscommandcallSubroutine_nameintheprogram.Onthecommandreturn,itleavesa subroutineandcontinuesexecutionfromwhereitleftoffthemainprogram.Subroutinemaybedefinedbothpriortooruponthecall.
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
7/16
19/05/13
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:
Clickonthisicontostartuptheprocess...
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
8/16
19/05/13
Doyouwanttoinstalltheentiresoftware?Yes.Next...
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
9/16
19/05/13
ClicktheMPLABdesktopiconinordertostarttheprogramandlearnaboutit.
PROJECTMAKING
Followthesestepstoprepareprogramforloadingintothemicrocontroller:
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
10/16
19/05/13
1. Makeaproject 2. Writeaprogramand 3. Compileit.
Inordertomakeaproject,itisnecessarytoclicktheoption"PROJECT"andthen"PROJECTWIZARD".Awelcomewindowappears.
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
ClickFINISHtocompletetheproject.Thewindowitselfcontainsprojectparameters.
WRITINGANEWPROGRAM
Whentheprojectiscreated,awindowshowninfigurebelowappears.
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
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
12/16
19/05/13
ClickonthatoptionopensanotherwindowcontainingthefolderPICalongwiththedocumentBlink.asm.Seefigurebelow.
Click"Blink"toincludethedocumentBlink.asmintotheproject.
Programwritingexample
Theprogramwritingprocedurecannotstartuntilallpreviousoperationshavebeenperformed.Programwrittenbelowisasimpleillustration ofprojectmaking.
www.mikroe.com/chapters/view/11/appendix-a-programming-a-microcontroller/
13/16
19/05/13
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
clickingreseticon.Astheconsequenceofthis,agreenlineispositionedatthebeginningoftheprogramandprogramcounterPCLis clearedtozero.RefertothewindowSpecialFunctionRegistersshownbelow.
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
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
search here
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:
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:
www.mikroe.com/chapters/view/12/appendix-b-examples/
1/43
19/05/13
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
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
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.
LEDDIODES
YouprobablyknowallyouneedtoknowaboutLEDdiodes,butweshouldalsothinkoftheyoungergenerations...HowtodestroyaLED?! Well...Verysimple.
www.mikroe.com/chapters/view/12/appendix-b-examples/
4/43
19/05/13
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
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
OPTOCOUPLER
www.mikroe.com/chapters/view/12/appendix-b-examples/
6/43
19/05/13
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
LCDscreen
TheLCDscreenconsistsoftwolineswith16characterseach.Everycharacterconsistsof5x8or5x11dotmatrix.Thisbookcoversthe5x8 characterdisplay,whichisindeedthemostcommonlyused.
LCDMemory
LCDdisplaycontainsthreememoryblocks:
Ifthecursorison,itappearsatthelocationwhichiscurrentlyaddressed.Inotherwords,whenacharacterappearsatthecursorposition,it willautomaticallymovetothenextaddressedlocation.
www.mikroe.com/chapters/view/12/appendix-b-examples/
8/43
19/05/13
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
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.
LCDInitialization
TheLCDisautomaticallyclearedwhenpoweredup.Itlastsforapproximately15mS.Afterthis,displayisreadyforoperation.Themodeof operationissetbydefault.Itmeansthat:
www.mikroe.com/chapters/view/12/appendix-b-examples/
10/43
19/05/13
N=0Messagesaredisplayedinoneline F=0Characterfont5x8dots
Itisnotamistake!Inthisalgorithm,thesamevalueistransferredthreetimesinarow. Incaseof4bitinitialization,theprocedureisasfollows:
www.mikroe.com/chapters/view/12/appendix-b-examples/
11/43
19/05/13
EXAMPLE1
WritingheaderandconfiguringI/Opins
TheonlypurposeofthisprogramistoturnonafewLEDdiodesonportB.Itisnothingspecial.Anyway,usethisexampletostudywhata realprogramlookslike.Thefigurebelowshowsaconnectionscheme,whiletheprogramisonthenextpage.
www.mikroe.com/chapters/view/12/appendix-b-examples/
12/43
19/05/13
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
Thisdirectivedefinesprocessortoexecuteaprogram.
# i n c l u d e < p 1 6 f 8 8 7 . i n c >
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
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
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
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
Payattentiontoafewdetails:
* * * * * * * * * * * * * * * * * * * * * * 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
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.
www.mikroe.com/chapters/view/12/appendix-b-examples/
18/43
19/05/13
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
SourceCode
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
SourceCode
www.mikroe.com/chapters/view/12/appendix-b-examples/
21/43
19/05/13
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
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
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
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.
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
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
SourceCode
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
SourceCode
www.mikroe.com/chapters/view/12/appendix-b-examples/
29/43
19/05/13
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
SourceCode
www.mikroe.com/chapters/view/12/appendix-b-examples/
31/43
19/05/13
www.mikroe.com/chapters/view/12/appendix-b-examples/
32/43
19/05/13
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.
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
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":
EXAMPLE15
www.mikroe.com/chapters/view/12/appendix-b-examples/
35/43
19/05/13
UsingLCDdisplay
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
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
www.mikroe.com/chapters/view/12/appendix-b-examples/
37/43
19/05/13
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
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
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
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
previouschapter|tableofcontents|nextchapter
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
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
search here
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.
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]
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
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...
www.mikroe.com/chapters/view/13/appendix-c-development-systems/
2/4
19/05/13
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
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
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