Sunteți pe pagina 1din 16

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

World of microcontrollers - Book: PIC Microcontrollers Products Solutions Store Distributors Libstock Contact
Products Solutions Store Distributors Libstock Contact Us search here Login | Cart (0)
Products
Solutions
Store
Distributors
Libstock
Contact Us
search here
Login | Cart (0)

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,Marcian’sideawonandthefirstmicroprocessorwasborn.Amajor helpwithturninganideaintoaready­to­useproductwasFedericoFaggin.Ninemonthsafterhiringhim,Intelsucceededindevelopingsucha

productfromitsoriginalconcept.In1971Intelobtainedtherighttosellthisintegratedcircuit.BeforethatIntelboughtthelicensefrom

BUSICOMwhichhadnoideawhatatreasureithad.Duringthatyear,amicroprocessorcalledthe4004appearedonthemarket.Thatwas

thefirst4­bitmicroprocessorwiththespeedof6000operationspersecond.Notlongafterthat,anAmericancompanyCTCrequestedfrom

IntelandTexasInstrumentstomanufacturean8­bitmicroprocessortobeappliedinterminals.EventhoughCTCgaveupthisproject,Intel

andTexasInstrumentskeptworkingonthemicroprocessorandinApril1972thefirst8­bitmicroprocessorcalledthe8008appearedonthe

market.Itwasabletoaddress16Kbofmemory,had45instructionsandthespeedof300000operationspersecond.Thatmicroprocessor

wasthepredecessorofalltoday’smicroprocessors.IntelkeptondevelopingitandinApril1974itlaunchedan8­bitprocessorcalledthe

8080.Itwasabletoaddress64Kbofmemory,had75instructionsandinitialpricewas$360.

AnotherAmericancompanycalledMotorola,quicklyrealizedwhatwasgoingon,sotheylaunched8­bitmicroprocessor6800.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.Itwasthe8­bitmicroprocessorwith56instructionsandabilitytodirectlyaddress64Kbofmemory.Dueto

lowprice,6502becameverypopularsoitwasinstalledintocomputerssuchasKIM­1,AppleI,AppleII,Atari,Commodore,Acorn,Oric,

Galeb,Orao,Ultraandmanyothers.Soonseveralcompaniesbeganmanufacturingthe6502(Rockwell,Sznertek,GTE,NCR,Ricoh,

CommodoretookoverMOSTechnology).Intheyearofitsprosperity1982,thisprocessorwasbeingsoldatarateof15millionprocessors

peryear!

FeaturedDevelopmentTools

EasyPICv7DevelopmentSystem EasyPICv7istopsellingPIC DevelopmentBoardfor250Microchip PICMCUsinDIPpackaging.Itfeatures

EasyPICv7istopsellingPIC

DevelopmentBoardfor250Microchip

PICMCUsinDIPpackaging.Itfeatures

USB2.0programmer/debuggerandover

17essentialmodulesnecessaryin

development.Boardcomeswith

PIC18F45K22.[moreinfo]

FreeOnlineBooks

Book:PICMicrocontrollers­ ProgramminginC Whataremicrocontrollers,anyway? Electroniccomponentsbuiltintoone

Whataremicrocontrollers,anyway?

Electroniccomponentsbuiltintoone

singlechipcapableofcontrollingasmall

submarine,acraneoranelevator…

anything.It’suptoyoutodecidewhat

youwantthemtodo.Youjusthaveto

writeaprogramanddumpitintothe

microcontroller.[moreinfo]

Othercompaniesdidnotwanttogiveupeither.FredericoFagginleftIntelandstartedhisowncompanyZilogInc.In1976Zilogannounced

theZ80.WhendesigningthismicroprocessorFagginmadeacrucialdecision.The8080hadalreadybeendevelopedandherealizedthat

manywouldremainloyaltothatprocessorbecauseofthegreatexpenditureswhichrewritingofalltheprogramswouldresultin.Accordingly

hedecidedthatanewprocessorhadtobecompatiblewiththe8080,i.e.ithadtobeabletoperformalltheprogramswrittenforthe8080.

Apartfromthat,manyotherfeatureshavebeenaddedsothattheZ80wasthemostpowerfulmicroprocessoratthattime.Itwasableto

directlyaddress64Kbofmemory,had176instructions,alargenumberofregisters,abuilt­inoptionforrefreshingdynamicRAMmemory,a

singlepowersupply,greateroperatingspeedetc.TheZ80wasagreatsuccessandeverybodyreplacedthe8080bytheZ80.Certainlythe

Z80wascommerciallythemostsuccessful8­bitmicroprocessoratthattime.BesidesZilog,othernewmanufacturerssuchasMostek,NEC,

SHARPandSGSappearedsoon.TheZ80wastheheartofmanycomputerssuchas:Spectrum,Partner,TRS703,Z­3andGalaxy.

In1976Intelcameupwithanupgradedversionofthe8­bitmicroprocessorcalledthe8085.However,theZ80wassomuchbetterthatIntel

lostthebattle.Eventhoughafewmoremicroprocessorsappearedlateronthemarket(6809,2650,SC/MPetc.),thediehadalreadybeen

cast.Therewerenosuchgreatimprovementswhichcouldmakemanufacturerstochangetheirmind,sothe6502andZ80alongwiththe

6800remainedchiefrepresentativesofthe8­bitmicroprocessorsofthattime.

MicrocontrollerversusMicroprocessor

Amicrocontrollerdiffersfromamicroprocessorinmanyways.Thefirstandmostimportantdifferenceisitsfunctionality.Inorderthatthe

microprocessormaybeused,othercomponentssuchasmemorymustbeaddedtoit.Eventhoughthemicroprocessorsareconsideredtobe

powerfulcomputingmachines,theirweakpointisthattheyarenotadjustedtocommunicatingtoperipheralequipment.

Simply,Inordertocommunicatewithperipheralenvironment,themicroprocessormustusespecializedcircuitsaddedasexternalchips.In

shortmicroprocessorsarethepureheartofthecomputers.Thisishowitwasinthebeginningandremainsthesametoday.

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Fig.0­1MicrocontrollerversusMicroprocessor

Fig.0­1MicrocontrollerversusMicroprocessor

Ontheotherhand,themicrocontrollerisdesignedtobeallofthatinone.Nootherspecializedexternalcomponentsareneededforits

applicationbecauseallnecessarycircuitswhichotherwisebelongtoperipheralsarealreadybuiltintoit.Itsavesthetimeandspaceneededto

designadevice.

BASICCONCEPT

Didyouknowthatallpeoplecanbeclassifiedintooneof10groups­thosewhoarefamiliarwithbinarynumbersystemandthosewhoarenot

familiarwithit.Youdon’tunderstand?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

8,9).Inotherwords,becauseweuse

base­10numbersystem,i.e.decimalnumbersystem.

and102?Whyisitalwaysaboutthenumber10?Thatisbecauseweusetendifferentdigits(0,1,2,

Fig.0­2Thenumber764representedinthreedifferentways

Fig.0­2Thenumber764representedinthreedifferentways

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

BinaryNumberSystem

Whatwouldhappenifonlytwodigitswouldbeused­0and1?Orifwewouldnotknowtodeterminewhethersomethingis3or5timesgreater

thansomethingelse?Orifwewouldberestrictedwhencomparingtwosizes,i.e.ifwecouldonlystatethatsomethingexists(1)ordoesnot

exist(0)?Nothingspecialwouldhappen,wewouldkeeponusingnumbersinthesameway,buttheywouldlookabitdifferent.Forexample:

11011010.Howmanypagesofabookdoesthenumber11011010include?Inordertolearnthat,followthesamelogiclikeintheprevious

example,butinreverseorder.Bearinmindthatallthisisaboutmathematicswithonlytwodigits­0and1,i.e.base­2numbersystem(binary

numbersystem).

numbersystem). Fig.0­3Thenumber218representedinbinaryanddecimalsystem

Fig.0­3Thenumber218representedinbinaryanddecimalsystem

Clearly,itisthesamenumberrepresentedintwodifferentways.Theonlydifferenceisinthenumberofdigitsnecessaryforwritingsome

number.Onedigit(2)isusedtowritethenumber2indecimalsystem,whereastwodigits(1and0)areusedtowritethatnumberinbinary

system.Doyounowagreethatthereare10groupsofpeople?Welcometotheworldofbinaryarithmetic!Doyouhaveanyideawhereitis

used?

Exceptingstrictlycontrolledlaboratoryconditions,themostcomplicatedelectroniccircuitscannotaccuratelydeterminethedifferencebetween twosizes(twovoltagevalues,forexample)iftheyaretoosmall(lowerthanseveralvolts).Thereasonsareelectricalnoisesandsomething calledthe“realworkingenvironment”(unpredictablechangesofpowersupplyvoltage,temperaturechanges,tolerancetovaluesofbuiltin

componentsetc.).Imagineacomputerwhichwouldoperateupondecimalnumbersbyrecognizing10digitsinthefollowingway:0=0V,1=5V,

2=10V,3=15V,4=20V 9=45V!?Didanybodysaybatteries?Afarsimplersolutionistheuseofbinarylogicwhere0indicatesthatthereis

novoltageand1indicatesthatthereisvoltage.Itiseasiertowrite0or1insteadof“thereisnovoltage”or“thereisvoltage”.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.0­4BinaryandHexadecimalnumber

Fig.0­4BinaryandHexadecimalnumber

Thelargestnumberthatcanberepresentedby4binarydigitsisthenumber1111.Itcorrespondstothenumber15indecimalsystem.That

numberisinhexadecimalsystemrepresentedbyonlyonedigitF.Itisthelargestonedigitnumberinhexadecimalsystem.Doyouseehow skillfullyitisused?Thelargestnumberwrittenwitheightdigitsisatthesametimethelargesttwodigithexadecimalnumber.Bearinmindthat

thecomputeruses8­digitbinarynumbers.

BCDCode

BCDcodeisactuallyabinarycodefordecimalnumbersonly.Itisusedtoenableelectroniccircuitstocommunicateinadecimalnumber

systemwithperipheralsandinabinarysystemwithin“theirownworld”.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

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,fornumbersfrom0to15­fourdigitsetc.Simplyspeaking,thelargestbinarynumber

consistingofndigitsisobtainedwhenthebase2israisedbyn.Theresultshouldbethensubtractedby1.Forexample,ifn=4:

2^4­1=16­1=15

Accordingly,using4binarydigitsitispossibletorepresentdecimalnumbersfrom0to15,includingthesetwodigits,whichamountsto16

differentvaluesintotal.

HexadecimaltoDecimalNumberConversion

Inordertomakeconversionofahexadecimalnumbertodecimal,eachhexadecimaldigitshouldbemultipliedwiththenumber16raisedby

itspositionvalue.Forexample:

itspositionvalue.Forexample: Fig.0­5Hexadecimaltodecimalnumberconversion

Fig.0­5Hexadecimaltodecimalnumberconversion

HexadecimaltoBinaryNumberConversion

Itisnotnecessarytoperformanycalculationinordertoconverthexadecimalnumberstobinarynumbers.Hexadecimaldigitsaresimply

replacedbytheappropriatefourbinarydigits.Sincethemaximumhexadecimaldigitisequivalenttodecimalnumber15,weneedtousefour

binarydigitstorepresentonehexadecimaldigit.Forexample:

binarydigitstorepresentonehexadecimaldigit.Forexample: Fig.0­6Hexadecimaltobinarynumberconversion

Fig.0­6Hexadecimaltobinarynumberconversion

Fig.0­6Hexadecimaltobinarynumberconversion Comparativetablebelowcontainsthevaluesof

Comparativetablebelowcontainsthevaluesof

numbers0­255inthreedifferentnumbering

systems.

MarkingNumbers

Thehexadecimalnumberingsystemisalongwithbinaryanddecimal numbersystemsconsideredtobethemostimportantforus.Itiseasyto makeconversionofanyhexadecimalnumbertobinaryanditisalsoeasy torememberit.However,theseconversionsmaycauseconfusion.For

example,whatdoesthestatement“Itisnecessarytocountup110

productsonassemblyline”actuallymean?Dependingonwhetheritis

aboutbinary,decimalorhexadecimal,theresultcouldbe6,110or272

products,respectively!Accordingly,inordertoavoidmisunderstanding, differentprefixesandsuffixesaredirectlyaddedtothenumbers.The

prefix$or0xaswellasthesuffixhmarksthenumbersinhexadecimal

system.Forexample,hexadecimalnumber10AFmaylookasfollows

$10AF,0x10AFor10AFh.Similarly,binarynumbersusuallygetthesuffix

%or0b,whereasdecimalnumbersgetthesuffixD.

Bit

Theorysaysabitisthebasicunitofinformation Let’sforgetthisdryexplanationforamomentandtakealookatwhatitisinpractice.The answerisnothingspecialabitisabinarydigit.Similartodecimalnumbersysteminwhichdigitsinanumberdonothavethesamevalue(for

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

exampledigitsinthenumber444arethesame,buthavedifferentvalues),the“significance”ofthebitdependsonthepositionithasinthe

binarynumber.Therefore,thereisnopointtalkingaboutunits,tensetc.Instead,hereitisaboutthezerobit(rightmostbit),firstbit(second

fromtheright)etc.Inaddition,sincethebinarysystemusestwodigitsonly(0and1),thevalueofonebitcanbe0or1.

Don’tbeconfusedifyoufindsomebithasvalue4,16or64.Itmeansthatbit’svaluesarerepresentedindecimalsystem.Simply,wehave

gotsomuchaccustomedtotheusageofdecimalnumbersthattheseexpressionsbecamecommon.Itwouldbecorrecttosayforexample, “thevalueofsixthbitinbinarynumberisequivalenttodecimalnumber64”.Butwearehumanandhabitsdiehard Besides,howwouldit ”

sound“number:one­onezero­one­zero

Byte

Abyteoraprogramwordconsistsofeightbitsgroupedtogether.Ifabitisadigit,itislogicalthatbytesrepresentnumbers.Allmathematical operationscanbeperformeduponthem,likeuponcommondecimalnumbers.Asisthecasewithdigitsofanyothernumber,bytedigitsdo nothavethesamesignificance.Thelargestvaluehastheleftmostbitcalledthemostsignificantbit(MSB).Therightmostbithastheleast

valueandisthereforecalledtheleastsignificantbit(LSB).Sinceeightzerosandunitsofonebytecanbecombinedin256differentways,the

largestdecimalnumberwhichcanberepresentedbyonebyteis255(onecombinationrepresentszero).

Anibbleisreferredtoashalfabyte.Dependingonwhichhalfofthebytewearetalkingabout(leftorright),thereare“high”and“low”nibbles.

LogicCircuits Fig.0­8HighandLownibbles

LogicCircuits

Fig.0­8HighandLownibbles

Haveyoueverwonderedwhatelectronicswithinsomedigitalintegratedcircuits,microcontrollersorprocessorslooklike?Whatdothecircuits

performingcomplicatedmathematicaloperationsandmakingdecisionslooklike?Doyouknowthattheirseeminglycomplicatedschematics

compriseonlyafewdifferentelementscalled“logiccircuits”or“logicgates”?

TheoperationoftheseelementsisbasedontheprinciplesestablishedbyBritishmathematicianGeorgeBooleinthemiddleofthe19th

century­evenbeforethefirstbulbwasinvented!Inbrief,themainideawastoexpresslogicalformsthroughalgebraicfunctions.Suchthinking

wassoontransformedintoapracticalproductwhichfarlaterevaluatedinwhattodayisknownasAND,ORandNOTlogiccircuits.The

principleoftheiroperationisknownasBooleanalgebra.Assomeprograminstructionsusedbythemicrocontrollerperformthesamewayas

logicgatesexceptintheformofcommands,theprincipleoftheiroperationwillbediscussedhere.

ANDGate

Alogicgate“AND”hastwoormoreinputsandoneoutput.Letuspresumethatthegateusedinthiscasehasonlytwoinputs.Alogicone(1)

willappearonitsoutputonlyincasebothinputs(AANDB)aredriventologicone(1).

Thetableshowsmutualdependencebetweeninputsandoutput.

Whenthegatehasmorethantwoinputs,theprincipleofoperationisthe

same:alogicone(1)willappearonitsoutputonlyifcaseallinputsare

driventologicone(1).Anyothercombinationofinputvoltageswillresultina

logiczero(0)atitsoutput.

logiczero(0)atitsoutput. ORGate
logiczero(0)atitsoutput. ORGate

ORGate

Whenusedinaprogram,alogicANDoperationisperformedbytheprogram

instruction,whichwillbediscussedlater.Forthetimebeing,itisenoughtoremember

thatlogicANDinaprogramreferstothecorrespondingbitsoftworegisters.

Similarlytothepreviouscase,ORgatesalsohavetwoormoreinputsand

oneoutput.Alogicone(1)willappearonitsoutputifeitherinput(AORB)is

driventologicone(1).Ifallinputsareatlogiczero(0),theoutputwillbe

driventologiczero(0).

driventologiczero(0).

Inaprogram,logicORoperationisperformedbetweenthecorrespondingregisters’bits­thesameasinlogicANDoperation.

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

NOTGate Thislogicgatehasonlyoneinputandonlyoneoutput.Itoperatesinan

NOTGate

Thislogicgatehasonlyoneinputandonlyoneoutput.Itoperatesinan

extremelysimpleway.Whenlogiczero(0)appearsonitsinput,alogicone

(1)appearsonitsoutputandviceversa.Thismeansthatthisgateinvertsthe

signalbyitself.Itissometimescalledinverter.

signalbyitself.Itissometimescalledinverter. EXCLUSIVEORGate
signalbyitself.Itissometimescalledinverter. EXCLUSIVEORGate

EXCLUSIVEORGate

Ifaprogram,logicNOToperationisperformedononebyte.Theresultisabytewith invertedbits.Ifbyteisconsideredtobeanumber,theinvertedvalueisactuallya complementofthatnumber,i.e.thecomplementofanumberiswhatisneededtoadd

toittomakeitreachthemaximal8bitvalue(255).

TheEXCLUSIVEOR(XOR)gateisabitcomplicatedcomparingtoothergates.Itrepresentsacombinationof

allthepreviouslydescribedgates.Alogicone(1)appearsonitsoutputonlywhentheinputshavedifferent

logicstates.

logicstates. Register
logicstates. Register

Register

Inaprogram,thisoperationiscommonlyusedtocomparetwobytes.Subtractionmay

beusedforthesamepurpose(iftheresultis0,bytesareequal).Theadvantageof

thislogicoperationisthatthereisnodangertosubtractlargernumberfromsmaller

one.

Aregisteroramemorycellisanelectroniccircuitwhichcanmemorizethestateofonebyte.

SpecialFunctionRegister Fig.0­17Register

SpecialFunctionRegister

Fig.0­17Register

Inadditiontotheregisterswhichdonothaveanyspecialandpredeterminedfunction,everymicrocontrollerhasanumberofregisterswhose

functionispredeterminedbythemanufacturer.Theirbitsareconnected(literally)tointernalcircuitssuchastimers,A/Dconverter,oscillators

andothers,whichmeansthattheyaredirectlyincommandoftheoperationofthemicrocontroller.Imagineeightswitcheswhicharein

commandofsomesmallercircuitswithinthemicrocontroller­youareright!SpecialFunctionRegisters(SFRs)doexactlythat!

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Input/OutputPorts Fig.0­18SpecialFunctionRegister

Input/OutputPorts

Fig.0­18SpecialFunctionRegister

Inordertomakethemicrocontrolleruseful,ithastobeconnectedtoadditionalelectronics,i.e.peripherals.Eachmicrocontrollerhasoneor

moreregisters(calleda“port”)connectedtothemicrocontrollerpins.Whyinput/output?Becauseyoucanchangethepin’sfunctionasyou

wish.Forexample,supposeyouwantyourdevicetoturnthreesignalLEDsandsimultaneouslymonitorthelogicstateoffivesensorsorpush

buttons.Someofportsneedtobeconfiguredsothattherearethreeoutputs(connectedtotheLEDs)andfiveinputs(connectedtosensors).

Itissimplyperformedbysoftware,whichmeansthatthepin’sfunctioncanbechangedduringoperation.

Fig.0­19Input/Outputports

Fig.0­19Input/Outputports

Oneofthemoreimportantspecificationsofinput/output(I/O)pinsisthemaximumcurrenttheycanhandle.Formostmicrocontrollers,current

obtainedfromonepinissufficienttoactivateanLEDorothersimilarlow­currentdevice(10­20mA).IfthemicrocontrollerhasmanyI/Opins,

thenthemaximumcurrentofonepinislower.Simplyput,youcannotexpectallpinstogivemaximumcurrentiftherearemorethan80of

themononemicrocontroller.Anotherwayofputtingitisthatthemaximumcurrentstatedinthedataspecificationssheetforthe

microprocessorissharedacrossallI/Oports.

Anotherimportantpinfunctionisthatitcanhavepull­upresistors.Theseresistorsconnectpinstothepositivepowersupplyvoltageandtheir

effectisvisiblewhenthepinisconfiguredasaninputconnectedtomechanicalswitchorpushbutton.Newerversionsofmicrocontrollers

havepull­upresistorsconfigurablebysoftware.

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

Memoryispartofthemicrocontrollerusedfordatastorage.Theeasiestwaytoexplainitistocompareitwithafilingcabinetwithmany

drawers.Suppose,thedrawersareclearlymarkedsothatitiseasytoaccessanyofthem.Itiseasyenoughtofindoutthecontentsofthe

drawerbyreadingthelabelonthefrontofthedrawer.

drawerbyreadingthelabelonthefrontofthedrawer. ReadOnlyMemory(ROM)

ReadOnlyMemory(ROM)

Eachmemoryaddresscorrespondstoonememorylocation.Thecontentof

anylocationbecomesknownbyitsaddressing.Memorycaneitherbewritten

toorreadfrom.Thereareseveraltypesofmemorywithinthe

microcontroller.

ROM(ReadOnlyMemory)isusedtopermanentlysavetheprogrambeingexecuted.Thesizeofaprogramthatcanbewrittendependson

thesizeofthismemory.Today’smicrocontrollerscommonlyuse16­bitaddressing,whichmeansthattheyareabletoaddressupto64Kbof

memory,i.e.65535locations.Asanovice,yourprogramwillrarelyexceedthelimitofseveralhundredinstructions.Thereareseveraltypesof

ROM.

MaskedROM.MicrocontrollerscontainingthisROMarereservedforthegreatmanufacturers.Programisloadedintothechipbythe

manufacturer.Incaseoflargescalemanufacture,thepriceisverylow.Forgetit

OneTimeProgrammableROM(OTPROM).Ifthemicrocontrollercontainsthismemory,youcandownloadaprogramintothismemory,but

theprocessofprogramdownloadingisa“one­wayticket”,meaningthatitcanbedoneonlyonce.Ifanerrorisdetectedafterdownloading,

theonlythingyoucandoistodownloadthecorrectedprogramtoanotherchip.

UVErasableProgrammableROM(UVEPROM).Boththemanufacturingprocessandcharacteristicsof

thismemoryarecompletelyidenticaltoOTPROM.However,thepackageofthismicrocontrollerhasa

recognizable“window”ontheupperside.Itenablesthesurfaceofthesiliconchipinsidetobelitbyan

UVlamp,whicheffectivelyerasesandprogramfromtheROM.

Installationofthiswindowisverycomplicated,whichnormallyaffectstheprice.Fromourpointofview,

unfortunately­negative

unfortunately­negative Flashmemory

Flashmemory.Thistypeofmemorywasinventedinthe80sinthelaboratoriesofINTELandwererepresentedasthesuccessortotheUV

EPROM.Sincethecontentsofthismemorycanbewrittenandclearedpracticallyanunlimitednumberoftimes,themicrocontrollerswith

FlashROMareidealforlearning,experimentationandsmall­scalemanufacture.Becauseofitspopularity,themostmicrocontrollersare

manufacturedinflashversionstoday.So,ifyouaregoingtobuyamicrocontroller,thetypetolookforisdefinitelyFlash!

RandomAccessMemory(RAM)

OncethepowersupplyisoffthecontentsofRAM(RandomAccessMemory)iscleared.Itisusedfortemporarystoringdataandintermediate

resultscreatedandusedduringtheoperationofthemicrocontroller.Forexample,iftheprogramperformsanaddition(ofwhatever),itis

necessarytohavearegisterrepresentingwhatineverydaylifeiscalledthe“sum”.Forthatpurpose,oneoftheregistersinRAMiscalledthe

“sum”andusedforstoringresultsofaddition.

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,themicrocontrollerdelegatesthe“wait

issue”tothe“specialist”whichwillreactonlywhensomethingattentionworthyhappens.

ThesignalwhichinformsthecentralprocessoraboutsuchaneventiscalledanINTERRUPT.

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

CentralProcessorUnit(CPU)

Asitsnamesuggests,thisisaunitwhichmonitorsandcontrolsallprocessesinsidethemicrocontroller.Itconsistsofseveralsmallersubunits,

ofwhichthemostimportantare:

InstructionDecoderisapartoftheelectronicswhichrecognizesprograminstructionsandrunsothercircuitsonthe

basisofthat.The“instructionset”whichisdifferentforeachmicrocontrollerfamilyexpressestheabilitiesofthis

circuit.

ArithmeticalLogicalUnit(ALU)performsallmathematicalandlogicaloperationsupondata.

AccumulatorisaSFRcloselyrelatedtotheoperationoftheALU.Itisakindofworkingdeskusedforstoringalldata

uponwhichsomeoperationshouldbeperformed(addition,shift/moveetc.).Italsostorestheresultsreadyforusein

furtherprocessing.OneoftheSFRs,calledaStatusRegister(PSW),iscloselyrelatedtotheaccumulator.Itshows

atanygivenmomentthe“status”ofanumberstoredintheaccumulator(numberisgreaterorlessthanzeroetc.).

Bus Fig.0­22CentralProcessorUnit­CPU

Bus

Fig.0­22CentralProcessorUnit­CPU

Physically,thebusconsistsof8,16ormorewires.Therearetwotypesofbuses:theaddressbusandthedatabus.Theaddressbusconsists

ofasmanylinesasnecessaryformemoryaddressing.ItisusedtotransmittheaddressfromtheCPUtothememory.Thedatabusisas

wideasthedata,inourcaseitis8bitsorwireswide.Itisusedtoconnectallcircuitsinsidethemicrocontroller.

SerialCommunication

Parallelconnectionsbetweenthemicrocontrollerandperipheralsviainput/outputportsistheidealsolutionforshorterdistances­uptoseveral

meters.However,inothercases­whenitisnecessarytoestablishcommunicationbetweentwodevicesonlongerdistancesitisnotpossible

touseaparallelconnection­suchasimplesolutionisoutofquestion.Inthesesituations,serialcommunicationisthebestsolution.

Today,mostmicrocontrollershavebuiltinseveraldifferentsystemsforserialcommunicationasastandardequipment.Whichofthese

systemswillbeuseddependsonmanyfactorsofwhichthemostimportantare:

Howmanydevicesthemicrocontrollerhastoexchangedatawith?

Howfastthedataexchangehastobe?

Whatisthedistancebetweendevices?

Isitnecessarytosendandreceivedatasimultaneously?

OneofthemostimportantthingsconcerningserialcommunicationistheProtocolwhich

Protocol which Fig.0­23Serialcommunication

Fig.0­23Serialcommunication

shouldbestrictlyobserved.Itisasetofruleswhichmustbeappliedinorderthatthedevicescancorrectlyinterpretdatatheymutually

exchange.Fortunately,themicrocontrollersautomaticallytakecareofthis,sotheworkoftheprogrammer/userisreducedtosimplewrite

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

(datatobesent)andread(receiveddata).

BaudRate

ThetermBaudrateiscommonlyusedtodenotethenumberofbitstransferredpersecond[bps].

Itshouldbenotedthatitreferstobits,notbytes!Itisusuallyrequiredbytheprotocolthateachbyteistransferredalongwithseveralcontrol

bits.Itmeansthatonebyteinserialdatastreammayconsistof11bits.Forexample,ifthebaudrateis300bpsthenmaximum37and

minimum27bytesmaybetransferredpersecond,whichdependsontypeofconnectionandprotocolinuse.

Themostcommonlyusedserialcommunicationsystemsare:

I2C(InterIntegratedCircuit)isasystemusedwhenthedistance

betweenthemicrocontrollersisshortandspecializedintegrated circuitsofofanewgeneration(receiverandtransmitterareusually onthesameprintedcircuitboard).Connectionisestablishedvia twoconductors­oneisusedfordatatransferwhereasanotheris usedforsynchronization(clocksignal).Asseeninfigure,one deviceisalwaysthemaster.Itperformsaddressingofoneslave chip(subordinated)beforecommunicationstarts.Inthiswayone

microcontrollercancommunicatewith112differentdevices.Baud

rateisusually100Kb/sec(standardmode)or10Kb/sec(slowbaudratemode).Systemswiththebaudrateof3.4Mb/sechaverecently

appeared.Thedistancebetweendeviceswhichcommunicateviaaninter­integratedcircuitbusislimitedtoseveralmeters.

SPI (SerialPeripheralInterfaceBus)isasystemforserial

SPI(SerialPeripheralInterfaceBus)isasystemforserial communicationwhichusesuptofourconductors(usuallythree)­ onefordatareceiving,onefordatasending,onefor synchronizationandone(alternatively)forselectingthedeviceto communicatewith.Itisfullduplexconnection,whichmeansthat dataissentandreceivedsimultaneously.Themaximumbaudrate

ishigherthaninI2Cconnection.

ishigherthaninI2Cconnection. UART (UniversalAsynchronousReceiver/Transmitter)

UART(UniversalAsynchronousReceiver/Transmitter) Thisconnectionisasynchronous,whichmeansthataspeciallineforclocksignaltransmissionisnotused.Insomesituationsthisfeatureis crucial(forexample,radioconnectionorinfraredwavesremotecontrol).Sinceonlyonecommunicationlineisused,bothreceiverand transmitteroperateatthesamepredefinedrateinordertomaintainnecessarysynchronization.Thisisaverysimplewayoftransferringdata

sinceitbasicallyrepresentsconversionof8­bitdatafromparalleltoserialformat.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

MicrocontrollerUnit(MCU)! Powersupplycircuit

Therearetwothingsworthattentionconcerningthemicrocontrollerpowersupplycircuit:

Brown­outisapotentiallydangerousstatewhichoccursatthemomentthemicrocontrollerisbeingturnedofforinsituationswhenpower

supplyvoltagedropstothelimitduetoelectricnoise.Asthemicrocontrollerconsistsofseveralcircuitswhichhavedifferentoperatingvoltage

levels,thisstatecancauseitsout­of­controlperformance.Inordertopreventit,themicrocontrollerusuallyhasbuilt­incircuitforbrownout

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

Fig.0­27Timers/Counters

Fig.0­27Timers/Counters

samewidth,whichmakesthemidealfortimemeasurement.Suchoscillatorsareusedinquartzwatches.Ifitisnecessarytomeasuretime

betweentwoevents,itissufficienttocountpulsescomingfromthisoscillator.Thatisexactlywhatthetimerdoes.

Mostprogramsusetheseminiatureelectronic“stopwatches”.Thesearecommonly8­or16­bitSFRsandtheircontentisautomatically

incrementedbyeachcomingpulse.Oncearegisteriscompletelyloaded­aninterruptisgenerated!

Ifthetimerregistersuseaninternalquartzoscillatorfortheiroperationthenitispossibletomeasuretimebetweentwoevents(iftheregister

valueisT1atthemomentmeasurementhasstarted,andT2atthemomentithasfinished,thentheelapsedtimeisequaltotheresultof

subtractionT2­T1).Iftheregistersusepulsescomingfromexternalsourcethensuchatimeristurnedintoacounter.

Thisisonlyasimpleexplanationoftheoperationitself.

Howdoesatimeroperate?

Inpracticepulsescomingfromthequartzoscillatorareoncepereachmachinecycledirectlyorviaaprescalerbroughttothecircuitwhich incrementsthenumberinthetimerregister.Ifoneinstruction(onemachinecycle)lastsforfourquartzoscillatorperiodsthen,byembedding

quartzwiththefrequencyof4MHz,thisnumberwillbechangedamilliontimespersecond(eachmicrosecond).

Fig.0­28TimerOperation

Fig.0­28TimerOperation

Itiseasytomeasureshorttimeintervals(upto256microseconds)inthewaydescribedabovebecauseitisthelargestnumberthatone

registercancontain.Thisobviousdisadvantagemaybeeasilyovercomeinseveralwaysbyusingasloweroscillator,registerswithmorebits,

aprescalerorinterrupts.Thefirsttwosolutionshavesomeweaknessessoitispreferabletouseprescalersorinterupts.

Usingprescalerintimeroperating

Aprescalerisanelectronicdeviceusedtoreduceafrequencybyapre­determinedfactor.Meaningthatinordertogenerateonepulseonits

output,itisnecessarytobring1,2,4ormorepulsestoitsinput.Onesuchcircuitisbuiltinthemicrocontrolleranditsdivisionratecanbe

changedfromwithintheprogram.Itisusedwhenitisnecessarytomeasurelongerperiodsoftime.

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Oneprescalerisusuallysharedbytimerandwatch­dogtimer,whichmeansthatitcannotbeusedbybothofthemsimultaneously.

Usingtheinterruptintimeroperation

Usingtheinterruptintimeroperation

Fig.0­29Usingprescalerintimeroperating

Ifthetimerregisterconsistsof8bits,thelargestnumberthatcanbewrittentoitis255(for16­bitregistersitisthenumber65.535).Ifthis

numberisexceeded,thetimerwillbeautomaticallyresetandcountingwillstartfromzeroagain.Thisconditioniscalledoverflow.Ifenabled

fromwithintheprogram,suchoverflowcancauseaninterrupt,whichgivescompletelynewpossibilities.Forexample,thestateofregisters

usedforcountingseconds,minutesordayscanbechangedinaninterruptroutine.Thewholeprocess(exceptinterruptroutine)is

automaticallyperformed“inthebackground”,whichenablesthemaincircuitsofthemicrocontrollertoperformotheroperations.

Fig.0­30Usingtheinterruptintimeroperation

Fig.0­30Usingtheinterruptintimeroperation

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

counter“getsstuck”onsomememorylocationfromwhichthereisnoreturn,thewatchdogwillnotbeclearedandtheregister’svaluebeing

constantlyincrementedwillreachthemaximumetvoila!Resetoccurs!

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

A/DConverter Fig.0­31WatchdogTimer

A/DConverter

Fig.0­31WatchdogTimer

Externalsignalsareusuallyfundamentallydifferentfromthosethemicrocontrollerunderstands(OnesandZeros),sothattheyhavetobe

convertedinorderforthemicrocontrollertounderstandthem.Ananaloguetodigitalconverterisanelectroniccircuitwhichconverts

continuoussignalstodiscretedigitalnumbers.Thismoduleisthereforeusedtoconvertsomeanaloguevalueintobinarynumberand

forwardsittotheCPUforfurtherprocessing.Inotherwords,thismoduleisusedforinputpinvoltagemeasurement(analoguevalue).The

resultofmeasurementisanumber(digitalvalue)usedandprocessedlaterintheprogram.

InternalArchitecture Fig.0­32A/DConverter

InternalArchitecture

Fig.0­32A/DConverter

AllupgradedmicrocontrollersuseoneoftwobasicdesignmodelscalledHarvardandvon­Neumannarchitecture.

Briefly,theyaretwodifferentwaysofdataexchangebetweenCPUandmemory.

von­NeumannArchitecture

Microcontrollersusingthisarchitecturehaveonlyonememoryblockandone8­bitdatabus.Asalldataareexchangedbyusingthese8lines,

thisbusisoverloadedandcommunicationitselfisveryslowandinefficient.TheCPUcaneitherreadaninstructionorread/writedatafrom/to

thememory.Bothcannotoccuratthesametimesincetheinstructionsanddatausethesamebussystem.Forexample,ifsomeprogramline

saysthatRAMmemoryregistercalled“SUM”shouldbeincrementedbyone(instruction:incfSUM),themicrocontrollerwilldothefollowing:

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

1. ReadthepartoftheprograminstructionspecifyingWHATshouldbedone(inthisverycaseitisthe“incf” instructionforincrement).

1. ReadthepartoftheprograminstructionspecifyingWHATshouldbedone(inthisverycaseitisthe“incf”

instructionforincrement).

2. ReadfurtherthesameinstructionspecifyinguponWHICHdataitshouldbeperformed(inthisverycaseitisthe

“SUM”register).

3. Afterbeingincremented,thecontentsofthisregistershouldbewrittentotheregisterfromwhichitwasread

(“SUM”registeraddress).

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.Therestofbits­4,6or8­representsthe

instructionitselfspecifyingtotheCPUwhattodowiththe8­bit

data.

Theadvantagesofsuchdesignarethefollowing:

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.

Whenusingmicrocontrollerswithvon­Neumannarchitectureoneneverknowshowmuchmemoryistobeoccupied

bysomeprogram.Basically,eachprograminstructionoccupiestwomemorylocations(onecontainsinformationon

WHATshouldbedone,whereasanothercontainsinformationuponWHICHdataitshouldbedone).However,itis

notahardandfastrule,butthemostcommoncase.InmicrocontrollerswithHarvardarchitecture,theprogrambusis

widerthanonebyte,whichallowseachprogramwordtoconsistofinstructionanddata.Inotherwords:oneprogram

word­oneinstruction.

INSTRUCTIONSET

Instructionsthatcanbeunderstoodbythemicrocontrollerareknownasaninstructionset.Whenyouwritea

programinassemblylanguage,youactually“tellastory”byspecifyinginstructionsintheordertheyshouldbe

executed.Themainrestrictioninthisprocessisthenumberofavailableinstructions.Themanufacturersstickto

oneofthetwofollowingstrategies:

RISC(ReducedInstructionSetComputer)

RISC (ReducedInstructionSetComputer)

Inthiscase,themicrocontrollerrecognizesandexecutesonlybasicoperations(addition,subtraction,copyingetc.).Allothermore

complicatedoperationsareperformedbycombiningthese(forexample,multiplicationisperformedbyperformingsuccessiveaddition).The

constrainsareobvious(trybyusingonlyafewwords,toexplaintosomeonehowtoreachtheairportinsomeothercity).However,thereare

alsosomegreatadvantages.Firstofall,thislanguageiseasytolearn.Besides,themicrocontrollerisveryfastsothatitisnotpossibletosee

allthearithmetic“acrobatics”itperforms.Theusercanonlyseethefinalresultofallthoseoperations.Atlast,itisnotsodifficulttoexplain

wheretheairportisifyouusetherightwords.Forexample:left,right,kilometersetc.

CISC(ComplexInstructionSetComputer)

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

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.Solveaspecificproblemandsomethingincrediblewillhappen­youwillbeabletohandleanymodelbelongingto

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.

A/D

Inputs

Resolution

of A/D

Compar-

ators

8/16 –

bit

Serial

Comm.

PWM

Outputs

Others

[MHz]

Converter

Timers

 

Base-Line 8 - bit architecture, 12-bit Instruction Word Length

 
 

0.375

-

                   

PIC10FXXX

0.75

16

- 24

6 - 8

4

- 8

0

- 2

 

8

0

- 1

 

1 x 8

-

 

-

-

0.75

-

                   

PIC12FXXX

1.5

25

- 38

8

4

- 8

0

- 3

 

8

0

- 1

 

1 x 8

-

 

-

EEPROM

 

25

-

14

-

               

PIC16FXXX

0.75

- 3

134

 

44

 

20

0

- 3

 

8

0

- 2

 

1 x 8

-

 

-

EEPROM

   

18

-

             

Vdd =

PIC16HVXXX

1.5

25

20

 

20

 

-

 

-

 

-

 

1 x 8

-

 

-

15V

 

Mid-Range 8 - bit architecture, 14-bit Instruction World Length

 
 

1.75

-

64

-

         

1

- 2 x

     

PIC12FXXX

3.5

128

 

8

 

20

0

- 4

 

10

 

1

8

1 x

-

0

- 1

EEPROM

         

16

 
             

1

- 2 x

     

PIC12HVXXX

1.75

64

8

 

20

0

- 4

 

10

 

1

8

1 x

-

0

- 1

-

       

16

 
             

1

- 2 x

     
 

-

 

-

 

PIC16FXXX

1.75

- 14

64

368

 

14

64

 

20

0

- 13

8

or 10

0

- 2

 

8

1 x

16

USART

I2C SPI

0

- 3

-

1.75

-

64

-

14

-

       

2

x

8 1

USART

   

PIC16HVXXX

3.5

128

 

20

 

20

0

- 12

 

10

 

2

x

16

I2C SPI

 

-

-

 

High-End 8 - bit architecture, 16-bit Instruction Word Length

 
   

256

18

32

       

0

- 2 x

USB2.0

CAN2.0

   
 

-

 

-

-

 

PIC18FXXX

4

- 128

3936

80

48

4

- 16

10

or 12

0

- 3

8

2 - 3

16

x

USART

I2C SPI

0

- 5

-

 

1024 -

28

40

       

0

- 2 x

USB2.0

USART

   
 

-

-

 

PIC18FXXJXX

8

- 128

3936

100

48

10

- 16

 

10

 

2

8 2 - 3

x

16

Ethernet

I2C SPI

2

- 5

-

PIC18FXXKXX

8 - 64

 

768

-

28

-

 

64

10

- 13

 

10

 

2

1 8 3

x

USART

 

2

-

 

3936

44

         

x

16

I2C SPI

 

AllPICmicrocontrollersuseharvardarchitecture,whichmeansthattheirprogrammemoryisconnectedtoCPUviamorethan8lines.

 

Dependingonthebuswidth,thereare12­,14­and16­bitmicrocontrollers.Thetableaboveshowsthemainfeaturesofthesethree

categories.

Asseeninthetableonthepreviouspage,excepting“16­bitmonsters”­PIC24FXXXandPIC24HXXX­allPICmicrocontrollershave8­bit

harvardarchitectureandbelongtooneoutofthreelargegroups.Therefore,dependingonthesizeofaprogramwordtherearefirst,second

andthirdcategory,i.e.12­,14­or16­bitmicrocontrollers.Havingsimilar8­bitcore,allofthemusethesameinstructionsetandthebasic

hardware‘skeleton’connectedtomoreorlessperipheralunits.

 

8/27/2014

Introduction: World of microcontrollers - Book: PIC Microcontrollers

Inordertoavoidtediousexplanationsandendlessstoryabouttheusefulfeaturesofdifferentmicrocontrollers,thisbookdescribesthe

operationofoneparticularmodelbelongingto“highmiddleclass”.ItisaboutPIC16F887­powerfulenoughtobeworthattentionandsimple

enoughtobeeasilypresentedtoeverybody.

MikroElektronika Embedded Solutions Follow us on PIC Solution dsPIC Solution STM32 Solution 8051 Solution Add-on
MikroElektronika Embedded Solutions
Follow us on
PIC Solution
dsPIC Solution
STM32 Solution
8051 Solution
Add-on boards
PIC Development Boards
PIC Compilers
PIC Programmers/Debuggers
PIC Kits
PIC Books
dsPIC Development Boards
dsPIC Compilers
dsPIC Programmers/Debuggers
dsPIC Kits
dsPIC Books
STM32 Development Boards
STM32 Compilers
STM32 Programmers/Debuggers
STM32 Kits
8051
Dev. Boards
8051
Compilers
8051
Programmers
8051
Books
8051
Kits
Tiva C Series Solution
PIC32 Solution
AVR Solution
PIC32 Development Boards
PIC32 Compilers
PIC32 Programmers/Debuggers
PIC32 Kits
AVR Development Boards
AVR Compilers
AVR Programmers/Debuggers
AVR Kits
Tiva C Development Boards
Tiva C Compilers
Tiva C Programmers/Debuggers
Tiva C Kits
Additional Software
Visual TFT
Visual GLCD
Package Manager
GLCD Font Creator
Timer Calculator
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

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