Sunteți pe pagina 1din 16

8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers

http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 1/16
TOC Introduction Ch. 1 Ch. 2 Ch. 3 Ch 4. Ch. 5 Ch. 6 Ch. 7 Ch. 8 Ch. 9 App. A App. B App. C
Book:PICMicrocontrollers
Introduction:Worldofmicrocontrollers
Thesituationwefindourselvestodayinthefieldofmicrocontrollershaditsbeginningsinthedevelopmentoftechnologyofintegratedcircuits.
Thisdevelopmenthasenabledustostorehundredsofthousandsoftransistorsintoonechip.Thatwasapreconditionforthemanufactureof
microprocessors.Thefirstcomputersweremadebyaddingexternalperipheralssuchasmemory,input/outputlines,timersandotherstoit.
Furtherincreasingofpackagedensityresultedincreatinganintegratedcircuitwhichcontainedbothprocessorandperipherals.Thatishow
thefirstchipcontainingamicrocomputerlaterknownasamicrocontrollerhasdeveloped.
Thisishowitallgotstarted...
Intheyear1969,ateamofJapaneseengineersfromBUSICOMcametotheUSAwitharequestthatafewintegratedcircuitsforcalculators
weretobedesignedaccordingtotheirprojects.TherequestwassenttoINTELandMarcianHoffwasinchargeoftheprojectthere.Having
experienceworkingwithacomputer,thePDP8,hecameupwithanideatosuggestfundamentallydifferentsolutionsinsteadofthesuggested
design.Thissolutionpresumedthattheoperationofintegratedcircuitwastobedeterminedbytheprogramstoredinthecircuititself.Itmeant
thatconfigurationwouldbesimpler,butitwouldrequirefarmorememorythantheprojectproposedbyJapaneseengineers.Afterawhile,
eventhoughtheJapaneseengineersweretryingtofindaneasiersolution,Marciansideawonandthefirstmicroprocessorwasborn.Amajor
helpwithturninganideaintoareadytouseproductwasFedericoFaggin.Ninemonthsafterhiringhim,Intelsucceededindevelopingsucha
productfromitsoriginalconcept.In1971Intelobtainedtherighttosellthisintegratedcircuit.BeforethatIntelboughtthelicensefrom
BUSICOMwhichhadnoideawhatatreasureithad.Duringthatyear,amicroprocessorcalledthe4004appearedonthemarket.Thatwas
thefirst4bitmicroprocessorwiththespeedof6000operationspersecond.Notlongafterthat,anAmericancompanyCTCrequestedfrom
IntelandTexasInstrumentstomanufacturean8bitmicroprocessortobeappliedinterminals.EventhoughCTCgaveupthisproject,Intel
andTexasInstrumentskeptworkingonthemicroprocessorandinApril1972thefirst8bitmicroprocessorcalledthe8008appearedonthe
market.Itwasabletoaddress16Kbofmemory,had45instructionsandthespeedof300000operationspersecond.Thatmicroprocessor
wasthepredecessorofalltodaysmicroprocessors.IntelkeptondevelopingitandinApril1974itlaunchedan8bitprocessorcalledthe
8080.Itwasabletoaddress64Kbofmemory,had75instructionsandinitialpricewas$360.
AnotherAmericancompanycalledMotorola,quicklyrealizedwhatwasgoingon,sotheylaunched8bitmicroprocessor6800.Theirchief
constructorwasChuckPeddle.Apartfromtheprocessoritself,Motorolawasthefirstcompanythatalsomanufacturedotherperipheralssuch
asthe6820and6850.Atthattimemanycompaniesrecognizedthegreaterimportanceofmicroprocessorsandbegantheirown
development.ChuckPeddleleftMotorolatojoinMOSTechnologyandkeptworkingintensivelyondevelopingmicroprocessors.
AttheWESCONexhibitionintheUSAin1975,acrucialeventinthehistoryofthemicroprocessorstookplace.MOSTechnologyannounced
thatitwassellingprocessors6501and6502at$25each,thatinterestedcustomerscouldpurchaseimmediately.Itwassuchasensationthat
manythoughtitwasakindoffraud,consideringthatcompetingcompaniesweresellingthe8080and6800at$179each.Onthefirstdayof
theexhibit,inresponsetothecompetitor,bothMotorolaandIntelcutthepricesoftheirmicroprocessorsto$69.95.MotorolaaccusedMOS
TechnologyandChuckPeddleofplagiarizingtheprotected6800.Becauseofthat,MOSTechnologygaveupfurthermanufactureofthe6501,
butkeptmanufacturingthe6502.Itwasthe8bitmicroprocessorwith56instructionsandabilitytodirectlyaddress64Kbofmemory.Dueto
lowprice,6502becameverypopularsoitwasinstalledintocomputerssuchasKIM1,AppleI,AppleII,Atari,Commodore,Acorn,Oric,
Galeb,Orao,Ultraandmanyothers.Soonseveralcompaniesbeganmanufacturingthe6502(Rockwell,Sznertek,GTE,NCR,Ricoh,
CommodoretookoverMOSTechnology).Intheyearofitsprosperity1982,thisprocessorwasbeingsoldatarateof15millionprocessors
peryear!
Othercompaniesdidnotwanttogiveupeither.FredericoFagginleftIntelandstartedhisowncompanyZilogInc.In1976Zilogannounced
theZ80.WhendesigningthismicroprocessorFagginmadeacrucialdecision.The8080hadalreadybeendevelopedandherealizedthat
manywouldremainloyaltothatprocessorbecauseofthegreatexpenditureswhichrewritingofalltheprogramswouldresultin.Accordingly
hedecidedthatanewprocessorhadtobecompatiblewiththe8080,i.e.ithadtobeabletoperformalltheprogramswrittenforthe8080.
Apartfromthat,manyotherfeatureshavebeenaddedsothattheZ80wasthemostpowerfulmicroprocessoratthattime.Itwasableto
directlyaddress64Kbofmemory,had176instructions,alargenumberofregisters,abuiltinoptionforrefreshingdynamicRAMmemory,a
singlepowersupply,greateroperatingspeedetc.TheZ80wasagreatsuccessandeverybodyreplacedthe8080bytheZ80.Certainlythe
Z80wascommerciallythemostsuccessful8bitmicroprocessoratthattime.BesidesZilog,othernewmanufacturerssuchasMostek,NEC,
SHARPandSGSappearedsoon.TheZ80wastheheartofmanycomputerssuchas:Spectrum,Partner,TRS703,Z3andGalaxy.
In1976Intelcameupwithanupgradedversionofthe8bitmicroprocessorcalledthe8085.However,theZ80wassomuchbetterthatIntel
lostthebattle.Eventhoughafewmoremicroprocessorsappearedlateronthemarket(6809,2650,SC/MPetc.),thediehadalreadybeen
cast.Therewerenosuchgreatimprovementswhichcouldmakemanufacturerstochangetheirmind,sothe6502andZ80alongwiththe
6800remainedchiefrepresentativesofthe8bitmicroprocessorsofthattime.
MicrocontrollerversusMicroprocessor
Amicrocontrollerdiffersfromamicroprocessorinmanyways.Thefirstandmostimportantdifferenceisitsfunctionality.Inorderthatthe
microprocessormaybeused,othercomponentssuchasmemorymustbeaddedtoit.Eventhoughthemicroprocessorsareconsideredtobe
powerfulcomputingmachines,theirweakpointisthattheyarenotadjustedtocommunicatingtoperipheralequipment.
Simply,Inordertocommunicatewithperipheralenvironment,themicroprocessormustusespecializedcircuitsaddedasexternalchips.In
shortmicroprocessorsarethepureheartofthecomputers.Thisishowitwasinthebeginningandremainsthesametoday.
FeaturedDevelopmentTools
FreeOnlineBooks
EasyPICv7DevelopmentSystem
EasyPICv7istopsellingPIC
DevelopmentBoardfor250Microchip
PICMCUsinDIPpackaging.Itfeatures
USB2.0programmer/debuggerandover
17essentialmodulesnecessaryin
development.Boardcomeswith
PIC18F45K22.[moreinfo]
Book:PICMicrocontrollers
ProgramminginC
Whataremicrocontrollers,anyway?
Electroniccomponentsbuiltintoone
singlechipcapableofcontrollingasmall
submarine,acraneoranelevator
anything.Itsuptoyoutodecidewhat
youwantthemtodo.Youjusthaveto
writeaprogramanddumpitintothe
microcontroller.[moreinfo]
Login | Cart (0)
Products Solutions Store Distributors Libstock Contact Us search here
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 2/16
Fig.01MicrocontrollerversusMicroprocessor
Ontheotherhand,themicrocontrollerisdesignedtobeallofthatinone.Nootherspecializedexternalcomponentsareneededforits
applicationbecauseallnecessarycircuitswhichotherwisebelongtoperipheralsarealreadybuiltintoit.Itsavesthetimeandspaceneededto
designadevice.
BASICCONCEPT
Didyouknowthatallpeoplecanbeclassifiedintooneof10groupsthosewhoarefamiliarwithbinarynumbersystemandthosewhoarenot
familiarwithit.Youdontunderstand?Thatmeansthatyoustillbelongtothelatergroup.Ifyouwanttochangeyourstatusreadthefollowing
textdescribingbrieflysomeofthebasicconceptsusedfurtherinthisbook(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.Couldthisnumberlookabit
morescientific?Theanswerisyes:4*10^0+6*10^1+7*10^2.Whatdoesitactuallymean?Whydoweuseexactlythesenumbers:100,101
and102?Whyisitalwaysaboutthenumber10?Thatisbecauseweusetendifferentdigits(0,1,2,...8,9).Inotherwords,becauseweuse
base10numbersystem,i.e.decimalnumbersystem.
Fig.02Thenumber764representedinthreedifferentways
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 3/16
BinaryNumberSystem
Whatwouldhappenifonlytwodigitswouldbeused0and1?Orifwewouldnotknowtodeterminewhethersomethingis3or5timesgreater
thansomethingelse?Orifwewouldberestrictedwhencomparingtwosizes,i.e.ifwecouldonlystatethatsomethingexists(1)ordoesnot
exist(0)?Nothingspecialwouldhappen,wewouldkeeponusingnumbersinthesameway,buttheywouldlookabitdifferent.Forexample:
11011010.Howmanypagesofabookdoesthenumber11011010include?Inordertolearnthat,followthesamelogiclikeintheprevious
example,butinreverseorder.Bearinmindthatallthisisaboutmathematicswithonlytwodigits0and1,i.e.base2numbersystem(binary
numbersystem).
Fig.03Thenumber218representedinbinaryanddecimalsystem
Clearly,itisthesamenumberrepresentedintwodifferentways.Theonlydifferenceisinthenumberofdigitsnecessaryforwritingsome
number.Onedigit(2)isusedtowritethenumber2indecimalsystem,whereastwodigits(1and0)areusedtowritethatnumberinbinary
system.Doyounowagreethatthereare10groupsofpeople?Welcometotheworldofbinaryarithmetic!Doyouhaveanyideawhereitis
used?
Exceptingstrictlycontrolledlaboratoryconditions,themostcomplicatedelectroniccircuitscannotaccuratelydeterminethedifferencebetween
twosizes(twovoltagevalues,forexample)iftheyaretoosmall(lowerthanseveralvolts).Thereasonsareelectricalnoisesandsomething
calledtherealworkingenvironment(unpredictablechangesofpowersupplyvoltage,temperaturechanges,tolerancetovaluesofbuiltin
componentsetc.).Imagineacomputerwhichwouldoperateupondecimalnumbersbyrecognizing10digitsinthefollowingway:0=0V,1=5V,
2=10V,3=15V,4=20V...9=45V!?Didanybodysaybatteries?Afarsimplersolutionistheuseofbinarylogicwhere0indicatesthatthereis
novoltageand1indicatesthatthereisvoltage.Itiseasiertowrite0or1insteadofthereisnovoltageorthereisvoltage.Itiscalledlogic
zero(0)andlogicone(1)whichelectronicsperfectlyconformswithandeasilyperformsallthoseendlesslycomplexmathematicaloperations.
Itiselectronicswhichinrealityappliesmathematicsinwhichallnumbersarerepresentedbytwodigitsonlyandinwhichitisonlyimportantto
knowwhetherthereisvoltageornot.Ofcourse,wearetalkingaboutdigitalelectronics.
HexadecimalNumberSystem
Attheverybeginningofcomputerdevelopmentitwasrealizedthatpeoplehadmanydifficultiesinhandlingbinarynumbers.Becauseofthis,
anewnumberingsystemhadtobeestablished.Thistime,anumbersystemusing16differentdigits.Thefirsttendigitsarethesameasdigits
weareusedto(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.What
isthepurposeofthisseeminglybizarrecombination?Justlookhowperfectlyeverythingfitsthestoryaboutbinarynumbers.
Fig.04BinaryandHexadecimalnumber
Thelargestnumberthatcanberepresentedby4binarydigitsisthenumber1111.Itcorrespondstothenumber15indecimalsystem.That
numberisinhexadecimalsystemrepresentedbyonlyonedigitF.Itisthelargestonedigitnumberinhexadecimalsystem.Doyouseehow
skillfullyitisused?Thelargestnumberwrittenwitheightdigitsisatthesametimethelargesttwodigithexadecimalnumber.Bearinmindthat
thecomputeruses8digitbinarynumbers.
BCDCode
BCDcodeisactuallyabinarycodefordecimalnumbersonly.Itisusedtoenableelectroniccircuitstocommunicateinadecimalnumber
systemwithperipheralsandinabinarysystemwithintheirownworld.Itconsistsoffourdigitbinarynumberswhichrepresentthefirstten
digits(0,1,2,3...8,9).Eventhoughfourdigitscangiveatotalof16possiblecombinations,onlythefirsttenareused.
NumberSystemConversion
Thebinarynumberingsystemisthemostcommonlyused,thedecimalsystemisthemostunderstandablewhilethehexadecimalsystemis
somewherebetweenthem.Therefore,itisveryimportanttolearnhowtoconvertnumbersfromonenumberingsystemtoanother,i.e.howto
turnaseriesofzerosandunitsintovaluesunderstandabletous.
BinarytoDecimalNumberConversion
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 4/16
Comparativetablebelowcontainsthevaluesof
numbers0255inthreedifferentnumbering
systems.
MarkingNumbers
Thehexadecimalnumberingsystemisalongwithbinaryanddecimal
numbersystemsconsideredtobethemostimportantforus.Itiseasyto
makeconversionofanyhexadecimalnumbertobinaryanditisalsoeasy
torememberit.However,theseconversionsmaycauseconfusion.For
example,whatdoesthestatementItisnecessarytocountup110
productsonassemblylineactuallymean?Dependingonwhetheritis
aboutbinary,decimalorhexadecimal,theresultcouldbe6,110or272
products,respectively!Accordingly,inordertoavoidmisunderstanding,
differentprefixesandsuffixesaredirectlyaddedtothenumbers.The
prefix$or0xaswellasthesuffixhmarksthenumbersinhexadecimal
system.Forexample,hexadecimalnumber10AFmaylookasfollows
$10AF,0x10AFor10AFh.Similarly,binarynumbersusuallygetthesuffix
%or0b,whereasdecimalnumbersgetthesuffixD.
Digitsinabinarynumberhavedifferentvaluesdependingontheirpositioninthatnumber.Additionally,eachpositioncancontaineither1or0
anditsvaluemaybeeasilydeterminedbyitspositionfromtheright.Tomaketheconversionofabinarynumbertodecimalitisnecessaryto
multiplyvalueswiththecorrespondingdigits(0or1)andaddalltheresults.Themagicofbinarytodecimalnumberconversionworks...You
doubt?Lookattheexample:
110=1*2^2+1*2^1+0*2^0=6
Itshouldbenotedthatfordecimalnumbersfrom0to3youonlyneedtwobinarydigits.Forgreatervalues,extrabinarydigitsmustbeadded.
Thus,fornumbersfrom0to7youneedthreedigits,fornumbersfrom0to15fourdigitsetc.Simplyspeaking,thelargestbinarynumber
consistingofndigitsisobtainedwhenthebase2israisedbyn.Theresultshouldbethensubtractedby1.Forexample,ifn=4:
2^41=161=15
Accordingly,using4binarydigitsitispossibletorepresentdecimalnumbersfrom0to15,includingthesetwodigits,whichamountsto16
differentvaluesintotal.
HexadecimaltoDecimalNumberConversion
Inordertomakeconversionofahexadecimalnumbertodecimal,eachhexadecimaldigitshouldbemultipliedwiththenumber16raisedby
itspositionvalue.Forexample:
Fig.05Hexadecimaltodecimalnumberconversion
HexadecimaltoBinaryNumberConversion
Itisnotnecessarytoperformanycalculationinordertoconverthexadecimalnumberstobinarynumbers.Hexadecimaldigitsaresimply
replacedbytheappropriatefourbinarydigits.Sincethemaximumhexadecimaldigitisequivalenttodecimalnumber15,weneedtousefour
binarydigitstorepresentonehexadecimaldigit.Forexample:
Fig.06Hexadecimaltobinarynumberconversion
Bit
Theorysaysabitisthebasicunitofinformation...Letsforgetthisdryexplanationforamomentandtakealookatwhatitisinpractice.The
answerisnothingspecialabitisabinarydigit.Similartodecimalnumbersysteminwhichdigitsinanumberdonothavethesamevalue(for
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 5/16
exampledigitsinthenumber444arethesame,buthavedifferentvalues),thesignificanceofthebitdependsonthepositionithasinthe
binarynumber.Therefore,thereisnopointtalkingaboutunits,tensetc.Instead,hereitisaboutthezerobit(rightmostbit),firstbit(second
fromtheright)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
nothavethesamesignificance.Thelargestvaluehastheleftmostbitcalledthemostsignificantbit(MSB).Therightmostbithastheleast
valueandisthereforecalledtheleastsignificantbit(LSB).Sinceeightzerosandunitsofonebytecanbecombinedin256differentways,the
largestdecimalnumberwhichcanberepresentedbyonebyteis255(onecombinationrepresentszero).
Anibbleisreferredtoashalfabyte.Dependingonwhichhalfofthebytewearetalkingabout(leftorright),therearehighandlownibbles.
Fig.08HighandLownibbles
LogicCircuits
Haveyoueverwonderedwhatelectronicswithinsomedigitalintegratedcircuits,microcontrollersorprocessorslooklike?Whatdothecircuits
performingcomplicatedmathematicaloperationsandmakingdecisionslooklike?Doyouknowthattheirseeminglycomplicatedschematics
compriseonlyafewdifferentelementscalledlogiccircuitsorlogicgates?
TheoperationoftheseelementsisbasedontheprinciplesestablishedbyBritishmathematicianGeorgeBooleinthemiddleofthe19th
centuryevenbeforethefirstbulbwasinvented!Inbrief,themainideawastoexpresslogicalformsthroughalgebraicfunctions.Suchthinking
wassoontransformedintoapracticalproductwhichfarlaterevaluatedinwhattodayisknownasAND,ORandNOTlogiccircuits.The
principleoftheiroperationisknownasBooleanalgebra.Assomeprograminstructionsusedbythemicrocontrollerperformthesamewayas
logicgatesexceptintheformofcommands,theprincipleoftheiroperationwillbediscussedhere.
ANDGate
AlogicgateANDhastwoormoreinputsandoneoutput.Letuspresumethatthegateusedinthiscasehasonlytwoinputs.Alogicone(1)
willappearonitsoutputonlyincasebothinputs(AANDB)aredriventologicone(1).
Thetableshowsmutualdependencebetweeninputsandoutput.
Whenthegatehasmorethantwoinputs,theprincipleofoperationisthe
same:alogicone(1)willappearonitsoutputonlyifcaseallinputsare
driventologicone(1).Anyothercombinationofinputvoltageswillresultina
logiczero(0)atitsoutput.
Whenusedinaprogram,alogicANDoperationisperformedbytheprogram
instruction,whichwillbediscussedlater.Forthetimebeing,itisenoughtoremember
thatlogicANDinaprogramreferstothecorrespondingbitsoftworegisters.
ORGate
Similarlytothepreviouscase,ORgatesalsohavetwoormoreinputsand
oneoutput.Alogicone(1)willappearonitsoutputifeitherinput(AORB)is
driventologicone(1).Ifallinputsareatlogiczero(0),theoutputwillbe
driventologiczero(0).
Inaprogram,logicORoperationisperformedbetweenthecorrespondingregistersbitsthesameasinlogicANDoperation.
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 6/16
NOTGate
Thislogicgatehasonlyoneinputandonlyoneoutput.Itoperatesinan
extremelysimpleway.Whenlogiczero(0)appearsonitsinput,alogicone
(1)appearsonitsoutputandviceversa.Thismeansthatthisgateinvertsthe
signalbyitself.Itissometimescalledinverter.
Ifaprogram,logicNOToperationisperformedononebyte.Theresultisabytewith
invertedbits.Ifbyteisconsideredtobeanumber,theinvertedvalueisactuallya
complementofthatnumber,i.e.thecomplementofanumberiswhatisneededtoadd
toittomakeitreachthemaximal8bitvalue(255).
EXCLUSIVEORGate
TheEXCLUSIVEOR(XOR)gateisabitcomplicatedcomparingtoothergates.Itrepresentsacombinationof
allthepreviouslydescribedgates.Alogicone(1)appearsonitsoutputonlywhentheinputshavedifferent
logicstates.
Inaprogram,thisoperationiscommonlyusedtocomparetwobytes.Subtractionmay
beusedforthesamepurpose(iftheresultis0,bytesareequal).Theadvantageof
thislogicoperationisthatthereisnodangertosubtractlargernumberfromsmaller
one.
Register
Aregisteroramemorycellisanelectroniccircuitwhichcanmemorizethestateofonebyte.
Fig.017Register
SpecialFunctionRegister
Inadditiontotheregisterswhichdonothaveanyspecialandpredeterminedfunction,everymicrocontrollerhasanumberofregisterswhose
functionispredeterminedbythemanufacturer.Theirbitsareconnected(literally)tointernalcircuitssuchastimers,A/Dconverter,oscillators
andothers,whichmeansthattheyaredirectlyincommandoftheoperationofthemicrocontroller.Imagineeightswitcheswhicharein
commandofsomesmallercircuitswithinthemicrocontrolleryouareright!SpecialFunctionRegisters(SFRs)doexactlythat!
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 7/16
Fig.018SpecialFunctionRegister
Input/OutputPorts
Inordertomakethemicrocontrolleruseful,ithastobeconnectedtoadditionalelectronics,i.e.peripherals.Eachmicrocontrollerhasoneor
moreregisters(calledaport)connectedtothemicrocontrollerpins.Whyinput/output?Becauseyoucanchangethepinsfunctionasyou
wish.Forexample,supposeyouwantyourdevicetoturnthreesignalLEDsandsimultaneouslymonitorthelogicstateoffivesensorsorpush
buttons.Someofportsneedtobeconfiguredsothattherearethreeoutputs(connectedtotheLEDs)andfiveinputs(connectedtosensors).
Itissimplyperformedbysoftware,whichmeansthatthepinsfunctioncanbechangedduringoperation.
Fig.019Input/Outputports
Oneofthemoreimportantspecificationsofinput/output(I/O)pinsisthemaximumcurrenttheycanhandle.Formostmicrocontrollers,current
obtainedfromonepinissufficienttoactivateanLEDorothersimilarlowcurrentdevice(1020mA).IfthemicrocontrollerhasmanyI/Opins,
thenthemaximumcurrentofonepinislower.Simplyput,youcannotexpectallpinstogivemaximumcurrentiftherearemorethan80of
themononemicrocontroller.Anotherwayofputtingitisthatthemaximumcurrentstatedinthedataspecificationssheetforthe
microprocessorissharedacrossallI/Oports.
Anotherimportantpinfunctionisthatitcanhavepullupresistors.Theseresistorsconnectpinstothepositivepowersupplyvoltageandtheir
effectisvisiblewhenthepinisconfiguredasaninputconnectedtomechanicalswitchorpushbutton.Newerversionsofmicrocontrollers
havepullupresistorsconfigurablebysoftware.
Usually,eachI/OportisundercontrolofanotherSFR,whichmeansthateachbitofthatregisterdeterminesthestateofthecorresponding
microcontrollerpin.Forexample,bywritinglogicone(1)toonebitofthatcontrolregisterSFR,theappropriateportpinisautomatically
configuredasinput.Itmeansthatvoltagebroughttothatpincanbereadaslogic0or1.Otherwise,bywritingzerototheSFR,the
appropriateportpinisconfiguredasanoutput.Itsvoltage(0Vor5V)correspondstothestateoftheappropriatebitoftheportregister.
MemoryUnit
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 8/16
Memoryispartofthemicrocontrollerusedfordatastorage.Theeasiestwaytoexplainitistocompareitwithafilingcabinetwithmany
drawers.Suppose,thedrawersareclearlymarkedsothatitiseasytoaccessanyofthem.Itiseasyenoughtofindoutthecontentsofthe
drawerbyreadingthelabelonthefrontofthedrawer.
Eachmemoryaddresscorrespondstoonememorylocation.Thecontentof
anylocationbecomesknownbyitsaddressing.Memorycaneitherbewritten
toorreadfrom.Thereareseveraltypesofmemorywithinthe
microcontroller.
ReadOnlyMemory(ROM)
ROM(ReadOnlyMemory)isusedtopermanentlysavetheprogrambeingexecuted.Thesizeofaprogramthatcanbewrittendependson
thesizeofthismemory.Todaysmicrocontrollerscommonlyuse16bitaddressing,whichmeansthattheyareabletoaddressupto64Kbof
memory,i.e.65535locations.Asanovice,yourprogramwillrarelyexceedthelimitofseveralhundredinstructions.Thereareseveraltypesof
ROM.
MaskedROM.MicrocontrollerscontainingthisROMarereservedforthegreatmanufacturers.Programisloadedintothechipbythe
manufacturer.Incaseoflargescalemanufacture,thepriceisverylow.Forgetit...
OneTimeProgrammableROM(OTPROM).Ifthemicrocontrollercontainsthismemory,youcandownloadaprogramintothismemory,but
theprocessofprogramdownloadingisaonewayticket,meaningthatitcanbedoneonlyonce.Ifanerrorisdetectedafterdownloading,
theonlythingyoucandoistodownloadthecorrectedprogramtoanotherchip.
UVErasableProgrammableROM(UVEPROM).Boththemanufacturingprocessandcharacteristicsof
thismemoryarecompletelyidenticaltoOTPROM.However,thepackageofthismicrocontrollerhasa
recognizablewindowontheupperside.Itenablesthesurfaceofthesiliconchipinsidetobelitbyan
UVlamp,whicheffectivelyerasesandprogramfromtheROM.
Installationofthiswindowisverycomplicated,whichnormallyaffectstheprice.Fromourpointofview,
unfortunatelynegative...
Flashmemory.Thistypeofmemorywasinventedinthe80sinthelaboratoriesofINTELandwererepresentedasthesuccessortotheUV
EPROM.Sincethecontentsofthismemorycanbewrittenandclearedpracticallyanunlimitednumberoftimes,themicrocontrollerswith
FlashROMareidealforlearning,experimentationandsmallscalemanufacture.Becauseofitspopularity,themostmicrocontrollersare
manufacturedinflashversionstoday.So,ifyouaregoingtobuyamicrocontroller,thetypetolookforisdefinitelyFlash!
RandomAccessMemory(RAM)
OncethepowersupplyisoffthecontentsofRAM(RandomAccessMemory)iscleared.Itisusedfortemporarystoringdataandintermediate
resultscreatedandusedduringtheoperationofthemicrocontroller.Forexample,iftheprogramperformsanaddition(ofwhatever),itis
necessarytohavearegisterrepresentingwhatineverydaylifeiscalledthesum.Forthatpurpose,oneoftheregistersinRAMiscalledthe
sumandusedforstoringresultsofaddition.
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,whenyoupushabuttonona
remotecontroller,themicrocontrollerwillregisteritandrespondtotheorderbychangingachannel,turnthevolumeupordownetc.Ifthe
microcontrollerspentmostofitstimeendlesslyafewbuttonsforhoursordays...Itwouldnotbepractical.
Themicrocontrollerhaslearntduringitsevolutionatrick.Insteadofcheckingeachpinorbitconstantly,themicrocontrollerdelegatesthewait
issuetothespecialistwhichwillreactonlywhensomethingattentionworthyhappens.
ThesignalwhichinformsthecentralprocessoraboutsuchaneventiscalledanINTERRUPT.
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 9/16
CentralProcessorUnit(CPU)
Asitsnamesuggests,thisisaunitwhichmonitorsandcontrolsallprocessesinsidethemicrocontroller.Itconsistsofseveralsmallersubunits,
ofwhichthemostimportantare:
InstructionDecoderisapartoftheelectronicswhichrecognizesprograminstructionsandrunsothercircuitsonthe
basisofthat.Theinstructionsetwhichisdifferentforeachmicrocontrollerfamilyexpressestheabilitiesofthis
circuit.
ArithmeticalLogicalUnit(ALU)performsallmathematicalandlogicaloperationsupondata.
AccumulatorisaSFRcloselyrelatedtotheoperationoftheALU.Itisakindofworkingdeskusedforstoringalldata
uponwhichsomeoperationshouldbeperformed(addition,shift/moveetc.).Italsostorestheresultsreadyforusein
furtherprocessing.OneoftheSFRs,calledaStatusRegister(PSW),iscloselyrelatedtotheaccumulator.Itshows
atanygivenmomentthestatusofanumberstoredintheaccumulator(numberisgreaterorlessthanzeroetc.).
Fig.022CentralProcessorUnitCPU
Bus
Physically,thebusconsistsof8,16ormorewires.Therearetwotypesofbuses:theaddressbusandthedatabus.Theaddressbusconsists
ofasmanylinesasnecessaryformemoryaddressing.ItisusedtotransmittheaddressfromtheCPUtothememory.Thedatabusisas
wideasthedata,inourcaseitis8bitsorwireswide.Itisusedtoconnectallcircuitsinsidethemicrocontroller.
SerialCommunication
Parallelconnectionsbetweenthemicrocontrollerandperipheralsviainput/outputportsistheidealsolutionforshorterdistancesuptoseveral
meters.However,inothercaseswhenitisnecessarytoestablishcommunicationbetweentwodevicesonlongerdistancesitisnotpossible
touseaparallelconnectionsuchasimplesolutionisoutofquestion.Inthesesituations,serialcommunicationisthebestsolution.
Today,mostmicrocontrollershavebuiltinseveraldifferentsystemsforserialcommunicationasastandardequipment.Whichofthese
systemswillbeuseddependsonmanyfactorsofwhichthemostimportantare:
Howmanydevicesthemicrocontrollerhastoexchangedatawith?
Howfastthedataexchangehastobe?
Whatisthedistancebetweendevices?
Isitnecessarytosendandreceivedatasimultaneously?
OneofthemostimportantthingsconcerningserialcommunicationistheProtocolwhich
Fig.023Serialcommunication
shouldbestrictlyobserved.Itisasetofruleswhichmustbeappliedinorderthatthedevicescancorrectlyinterpretdatatheymutually
exchange.Fortunately,themicrocontrollersautomaticallytakecareofthis,sotheworkoftheprogrammer/userisreducedtosimplewrite
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 10/16
(datatobesent)andread(receiveddata).
BaudRate
ThetermBaudrateiscommonlyusedtodenotethenumberofbitstransferredpersecond[bps].
Itshouldbenotedthatitreferstobits,notbytes!Itisusuallyrequiredbytheprotocolthateachbyteistransferredalongwithseveralcontrol
bits.Itmeansthatonebyteinserialdatastreammayconsistof11bits.Forexample,ifthebaudrateis300bpsthenmaximum37and
minimum27bytesmaybetransferredpersecond,whichdependsontypeofconnectionandprotocolinuse.
Themostcommonlyusedserialcommunicationsystemsare:
I2C(InterIntegratedCircuit)isasystemusedwhenthedistance
betweenthemicrocontrollersisshortandspecializedintegrated
circuitsofofanewgeneration(receiverandtransmitterareusually
onthesameprintedcircuitboard).Connectionisestablishedvia
twoconductorsoneisusedfordatatransferwhereasanotheris
usedforsynchronization(clocksignal).Asseeninfigure,one
deviceisalwaysthemaster.Itperformsaddressingofoneslave
chip(subordinated)beforecommunicationstarts.Inthiswayone
microcontrollercancommunicatewith112differentdevices.Baud
rateisusually100Kb/sec(standardmode)or10Kb/sec(slowbaudratemode).Systemswiththebaudrateof3.4Mb/sechaverecently
appeared.Thedistancebetweendeviceswhichcommunicateviaaninterintegratedcircuitbusislimitedtoseveralmeters.
SPI(SerialPeripheralInterfaceBus)isasystemforserial
communicationwhichusesuptofourconductors(usuallythree)
onefordatareceiving,onefordatasending,onefor
synchronizationandone(alternatively)forselectingthedeviceto
communicatewith.Itisfullduplexconnection,whichmeansthat
dataissentandreceivedsimultaneously.Themaximumbaudrate
ishigherthaninI2Cconnection.
UART(UniversalAsynchronousReceiver/Transmitter)
Thisconnectionisasynchronous,whichmeansthataspeciallineforclocksignaltransmissionisnotused.Insomesituationsthisfeatureis
crucial(forexample,radioconnectionorinfraredwavesremotecontrol).Sinceonlyonecommunicationlineisused,bothreceiverand
transmitteroperateatthesamepredefinedrateinordertomaintainnecessarysynchronization.Thisisaverysimplewayoftransferringdata
sinceitbasicallyrepresentsconversionof8bitdatafromparalleltoserialformat.Baudrateisnothighupto1Mbit/sec.
Oscillator
Evenpulsescomingfromtheoscillatorenableharmonicand
synchronousoperationofallcircuitsofthemicrocontroller.The
oscillatormoduleisusuallyconfiguredtousequartzcrystalor
ceramicresonatorforfrequencystabilization.Furthermore,itcan
alsooperatewithoutelementsforfrequencystabilization(likeRC
oscillator).Itisimportanttosaythatinstructionsarenotexecutedat
therateimposedbytheoscillatoritself,butseveraltimesslower.It
happensbecauseeachinstructionisexecutedinseveralsteps.In
somemicrocontrollers,thesamenumberofcyclesisneededto
executeanyinstruction,whileinothers,theexecutiontimeisnot
thesameforallinstructions.Accordingly,ifthesystemusesquartz
crystalwithafrequencyof20Mhz,executiontimeofaninstruction
isnot50nS,but200,400or800nS,dependingonthetypeof
MicrocontrollerUnit(MCU)!
Powersupplycircuit
Therearetwothingsworthattentionconcerningthemicrocontrollerpowersupplycircuit:
Brownoutisapotentiallydangerousstatewhichoccursatthemomentthemicrocontrollerisbeingturnedofforinsituationswhenpower
supplyvoltagedropstothelimitduetoelectricnoise.Asthemicrocontrollerconsistsofseveralcircuitswhichhavedifferentoperatingvoltage
levels,thisstatecancauseitsoutofcontrolperformance.Inordertopreventit,themicrocontrollerusuallyhasbuiltincircuitforbrownout
reset.Thiscircuitimmediatelyresetsthewholeelectronicswhenthevoltageleveldropsbelowthelimit.
ResetpinisusuallymarkedasMCLR(MasterClearReset)andservesforexternalresetofthemicrocontrollerbyapplyinglogiczero(0)or
one(1),dependingontypeofthemicrocontroller.Incasethebrownoutcircuitisnotbuiltin,asimpleexternalcircuitforbrownoutresetcan
beconnectedtothispin.
Timers/Counters
Themicrocontrolleroscillatorusesquartzcrystalforitsoperation.Eventhoughitisnotthesimplestsolution,therearemanyreasonstouseit.
Namely,thefrequencyofsuchoscillatorispreciselydefinedandverystable,thepulsesitgeneratesarealwaysofthe
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 11/16
Fig.027Timers/Counters
samewidth,whichmakesthemidealfortimemeasurement.Suchoscillatorsareusedinquartzwatches.Ifitisnecessarytomeasuretime
betweentwoevents,itissufficienttocountpulsescomingfromthisoscillator.Thatisexactlywhatthetimerdoes.
Mostprogramsusetheseminiatureelectronicstopwatches.Thesearecommonly8or16bitSFRsandtheircontentisautomatically
incrementedbyeachcomingpulse.Oncearegisteriscompletelyloadedaninterruptisgenerated!
Ifthetimerregistersuseaninternalquartzoscillatorfortheiroperationthenitispossibletomeasuretimebetweentwoevents(iftheregister
valueisT1atthemomentmeasurementhasstarted,andT2atthemomentithasfinished,thentheelapsedtimeisequaltotheresultof
subtractionT2T1).Iftheregistersusepulsescomingfromexternalsourcethensuchatimeristurnedintoacounter.
Thisisonlyasimpleexplanationoftheoperationitself.
Howdoesatimeroperate?
Inpracticepulsescomingfromthequartzoscillatorareoncepereachmachinecycledirectlyorviaaprescalerbroughttothecircuitwhich
incrementsthenumberinthetimerregister.Ifoneinstruction(onemachinecycle)lastsforfourquartzoscillatorperiodsthen,byembedding
quartzwiththefrequencyof4MHz,thisnumberwillbechangedamilliontimespersecond(eachmicrosecond).
Fig.028TimerOperation
Itiseasytomeasureshorttimeintervals(upto256microseconds)inthewaydescribedabovebecauseitisthelargestnumberthatone
registercancontain.Thisobviousdisadvantagemaybeeasilyovercomeinseveralwaysbyusingasloweroscillator,registerswithmorebits,
aprescalerorinterrupts.Thefirsttwosolutionshavesomeweaknessessoitispreferabletouseprescalersorinterupts.
Usingprescalerintimeroperating
Aprescalerisanelectronicdeviceusedtoreduceafrequencybyapredeterminedfactor.Meaningthatinordertogenerateonepulseonits
output,itisnecessarytobring1,2,4ormorepulsestoitsinput.Onesuchcircuitisbuiltinthemicrocontrolleranditsdivisionratecanbe
changedfromwithintheprogram.Itisusedwhenitisnecessarytomeasurelongerperiodsoftime.
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 12/16
Oneprescalerisusuallysharedbytimerandwatchdogtimer,whichmeansthatitcannotbeusedbybothofthemsimultaneously.
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,then
theoperationofthewatchdogtimerwillnotaffectprogramexecution.Ifforanyreason(usuallyelectricalnoisesinindustry),theprogram
countergetsstuckonsomememorylocationfromwhichthereisnoreturn,thewatchdogwillnotbeclearedandtheregistersvaluebeing
constantlyincrementedwillreachthemaximumetvoila!Resetoccurs!
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 13/16
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.Asalldataareexchangedbyusingthese8lines,
thisbusisoverloadedandcommunicationitselfisveryslowandinefficient.TheCPUcaneitherreadaninstructionorread/writedatafrom/to
thememory.Bothcannotoccuratthesametimesincetheinstructionsanddatausethesamebussystem.Forexample,ifsomeprogramline
saysthatRAMmemoryregistercalledSUMshouldbeincrementedbyone(instruction:incfSUM),themicrocontrollerwilldothefollowing:
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 14/16
Thesamedatabusisusedforalltheseintermediateoperations.
HarvardArchitecture
Microcontrollersusingthisarchitecturehavetwodifferentdata
buses.Oneis8bitswideandconnectsCPUtoRAM.Another
consistsofseverallines(12,14or16)andconnectsCPUtoROM.
Accordingly,theCPUcanreadaninstructionandperformadata
memoryaccessatthesametime.SinceallRAMmemoryregisters
are8bitswide,alldatawithinthemicrocontrollerareexchangedin
thesamesuchformat.Additionally,duringprogramwriting,only8
bitsdataareconsidered.Inotherwords,allyoucaneverchange
fromwithintheprogramandallyoucanaffectwillbe8bitswide.A
programwrittenforsomeofthesemicrocontrollerswillbestoredin
themicrocontrollerinternalROMuponhavingbeingcompiledinto
machinelanguage.However,thesememorylocationsdonothave
8,but12,14or16bits.Therestofbits4,6or8representsthe
instructionitselfspecifyingtotheCPUwhattodowiththe8bit
data.
Theadvantagesofsuchdesignarethefollowing:
Alldatainaprogramisonebyte(8bit)wide.Asthedatabususedforprogramreadinghasseverallines(12,14or
16),bothinstructionsanddatacanbereadsimultaneouslybyusingthesesparebits.Therefore,allinstructionsare
executedinonlyoneinstructioncycle.Theonlyexceptionisjumpinstructionwhichisexecutedintwocycles.
Owingtothefactthataprogram(ROM)andtemporarydata(RAM)areseparate,theCPUcanexecutetwo
instructionssimultaneously.Simply,whileRAMreadorwriteisinprogress(theendofoneinstruction),thenext
programinstructionisbeingreadviaanotherbus.
WhenusingmicrocontrollerswithvonNeumannarchitectureoneneverknowshowmuchmemoryistobeoccupied
bysomeprogram.Basically,eachprograminstructionoccupiestwomemorylocations(onecontainsinformationon
WHATshouldbedone,whereasanothercontainsinformationuponWHICHdataitshouldbedone).However,itis
notahardandfastrule,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,themicrocontrollerisveryfastsothatitisnotpossibletosee
allthearithmeticacrobaticsitperforms.Theusercanonlyseethefinalresultofallthoseoperations.Atlast,itisnotsodifficulttoexplain
wheretheairportisifyouusetherightwords.Forexample:left,right,kilometersetc.
CISC(ComplexInstructionSetComputer)
1. ReadthepartoftheprograminstructionspecifyingWHATshouldbedone(inthisverycaseitistheincf
instructionforincrement).
2. ReadfurtherthesameinstructionspecifyinguponWHICHdataitshouldbeperformed(inthisverycaseitisthe
SUMregister).
3. Afterbeingincremented,thecontentsofthisregistershouldbewrittentotheregisterfromwhichitwasread
(SUMregisteraddress).
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 15/16
CISCistheoppositeofRISC!Microcontrollersdesignedtorecognizemorethan200differentinstructionscandomuchandareveryfast.
However,oneneedstounderstandhowtotakeallthatsucharichlanguageoffers,whichisnotatalleasy...
Howtomaketherightchoice
Ok,youarethebeginnerandyouhavemadeadecisiontogoonanadventureofworkingwiththemicrocontrollers.Congratulationsonyour
choice!However,itisnotaseasytochoosetherightmicrocontrollerasitmayseem.Theproblemisnotalimitedrangeofdevices,butthe
opposite!
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
themanufacturer,i.e.thefamilyofthemicrocontrollersyoucaneasilyobtain.Afterthat,studyoneparticularmodel.Learnasmuchasyou
need,donotgointodetails.Solveaspecificproblemandsomethingincrediblewillhappenyouwillbeabletohandleanymodelbelongingto
thatfamily.
Rememberlearningtorideabicycle:afterseveralunavoidablebruisesatthebeginning,youwillmanagetokeepbalanceandwillbeableto
easilyrideanyotherbicycle.Andofcourse,youwillneverforgettheskillinprogrammingjustasyouwillneverforgetridingbicycles!
PICmicrocontrollers
PICmicrocontrollersdesignedbyMicrochipTechnologyarelikelytherightchoiceforyouifyouarethebeginner.Hereiswhy...
TherealnameofthismicrocontrollerisPICmicro(PeripheralInterfaceController),butitisbetterknownasPIC.Itsfirstancestorwasdesigned
in1975byGeneralInstruments.ThischipcalledPIC1650wasmeantfortotallydifferentpurposes.Abouttenyearslater,byaddingEEPROM
memory,thiscircuitwastransformedintoarealPICmicrocontroller.Nowadays,MicrochipTechnologyannouncesamanufacturingofthe5
billionthsample...
Inorderthatyoucanbetterunderstandthereasonsforitspopularity,wewillbrieflydescribeseveralimportantthings.
Family
ROM
[Kbytes]
RAM
[bytes]
Pins
Clock
Freq.
[MHz]
A/D
Inputs
Resolution
of A/D
Converter
Compar-
ators
8/16
bit
Timers
Serial
Comm.
PWM
Outputs
Others
Base-Line 8 - bit architecture, 12-bit Instruction Word Length
PIC10FXXX
0.375 -
0.75
16 - 24 6 - 8 4 - 8 0 - 2 8 0 - 1 1 x 8 - - -
PIC12FXXX
0.75 -
1.5
25 - 38 8 4 - 8 0 - 3 8 0 - 1 1 x 8 - - EEPROM
PIC16FXXX 0.75 - 3
25 -
134
14 -
44
20 0 - 3 8 0 - 2 1 x 8 - - EEPROM
PIC16HVXXX 1.5 25
18 -
20
20 - - - 1 x 8 - -
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 - 2 x
8 1 x
16
- 0 - 1 EEPROM
PIC12HVXXX 1.75 64 8 20 0 - 4 10 1
1 - 2 x
8 1 x
16
- 0 - 1 -
PIC16FXXX 1.75 - 14
64 -
368
14 -
64
20 0 - 13 8 or 10 0 - 2
1 - 2 x
8 1 x
16
USART
I2C SPI
0 - 3 -
PIC16HVXXX
1.75 -
3.5
64 -
128
14 -
20
20 0 - 12 10 2
2 x 8 1
x 16
USART
I2C SPI
- -
High-End 8 - bit architecture, 16-bit Instruction Word Length
PIC18FXXX 4 - 128
256 -
3936
18 -
80
32 -
48
4 - 16 10 or 12 0 - 3
0 - 2 x
8 2 - 3
x 16
USB2.0
CAN2.0
USART
I2C SPI
0 - 5 -
PIC18FXXJXX 8 - 128
1024 -
3936
28 -
100
40 -
48
10 - 16 10 2
0 - 2 x
8 2 - 3
x 16
USB2.0
USART
Ethernet
I2C SPI
2 - 5 -
PIC18FXXKXX 8 - 64
768 -
3936
28 -
44
64 10 - 13 10 2
1 x 8 3
x 16
USART
I2C SPI
2 -
AllPICmicrocontrollersuseharvardarchitecture,whichmeansthattheirprogrammemoryisconnectedtoCPUviamorethan8lines.
Dependingonthebuswidth,thereare12,14and16bitmicrocontrollers.Thetableaboveshowsthemainfeaturesofthesethree
categories.
Asseeninthetableonthepreviouspage,excepting16bitmonstersPIC24FXXXandPIC24HXXXallPICmicrocontrollershave8bit
harvardarchitectureandbelongtooneoutofthreelargegroups.Therefore,dependingonthesizeofaprogramwordtherearefirst,second
andthirdcategory,i.e.12,14or16bitmicrocontrollers.Havingsimilar8bitcore,allofthemusethesameinstructionsetandthebasic
hardwareskeletonconnectedtomoreorlessperipheralunits.
8/27/2014 Introduction: World of microcontrollers - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/1/introduction-world-of-microcontrollers/ 16/16
tableofcontents|nextchapter
Inordertoavoidtediousexplanationsandendlessstoryabouttheusefulfeaturesofdifferentmicrocontrollers,thisbookdescribesthe
operationofoneparticularmodelbelongingtohighmiddleclass.ItisaboutPIC16F887powerfulenoughtobeworthattentionandsimple
enoughtobeeasilypresentedtoeverybody.
Copyright 1998 - 2014. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.
MikroElektronika Embedded Solutions
Follow us on
PIC Solution
PIC Development Boards
PIC Compilers
PIC Programmers/Debuggers
PIC Kits
PIC Books
PIC32 Solution
PIC32 Development Boards
PIC32 Compilers
PIC32 Programmers/Debuggers
PIC32 Kits
dsPIC Solution
dsPIC Development Boards
dsPIC Compilers
dsPIC Programmers/Debuggers
dsPIC Kits
dsPIC Books
AVR Solution
AVR Development Boards
AVR Compilers
AVR Programmers/Debuggers
AVR Kits
STM32 Solution
STM32 Development Boards
STM32 Compilers
STM32 Programmers/Debuggers
STM32 Kits
Tiva C Series Solution
Tiva C Development Boards
Tiva C Compilers
Tiva C Programmers/Debuggers
Tiva C Kits
8051 Solution
8051 Dev. Boards
8051 Compilers
8051 Programmers
8051 Books
8051 Kits
Additional Software
Visual TFT
Visual GLCD
Package Manager
GLCD Font Creator
Timer Calculator
Add-on boards
Click Boards
mikromedia shields
Communication
Storage
Real Time Clock
Display
Measurement
Audio & Voice
Power Supply
GPS
GSM/GPRS
Support Forum mikroBUS Lets make Press Legal Archive About Us Customization

S-ar putea să vă placă și