Vous êtes sur la page 1sur 20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika
Products

Solutions

Store

Distributors

Libstock

ContactUs

searchhere

Login|Cart(0)

Architectureandprogrammingof8051MCU's
TOC Chapter1 Chapter2 Chapter3 Chapter4 Chapter5 Chapter6 Chapter7

Chapter2:8051MicrocontrollerArchitecture

FeaturedDevelopmentTools
Easy8051v6Development
System

2.1Whatis8051Standard?
2.28051Microcontroller'spins
2.3Input/OutputPorts(I/OPorts)
2.48051MicrocontrollerMemoryOrganisation
2.5SFRs(SpecialFunctionRegisters)
2.6CountersandTimers
2.7UART(UniversalAsynchronousReceiverandTransmitter)
2.88051MicrocontrollerInterrupts
2.98051MicrocontrollerPowerConsumptionControl

2.1Whatis8051Standard?
Microcontrollermanufacturershavebeencompetingforalongtimeforattractingchoosycustomersandeverycoupleofdaysanewchip
withahigheroperatingfrequency,morememoryandupgradedA/Dconvertersappearedonthemarket.

TheEasy8051v6iscompatiblewith14,
16,20,28,40pinPLCC44and
PLCC32MCUs.Itcomeswithan
AT89S8253.TheboardhasaUSB2.0
programmerandmanyperipheralssuch
asCOG,portexpander,MENUand4x4
keypadsetc.[moreinfo]

mikroProgfor8051

However,mostofthemhadthesameoratleastverysimilararchitectureknownintheworldofmicrocontrollersas8051compatible.What
isallthisabout?
Thewholestoryhasitsbeginningsinthefar80swhenIntellaunchedthefirstseriesofmicrocontrollerscalledtheMCS051.Eventhough
thesemicrocontrollershadquitemodestfeaturesincomparisontothenewones,theyconqueredtheworldverysoonandbecamea
standardforwhatnowadaysiscalledthemicrocontroller.
Themainreasonfortheirgreatsuccessandpopularityisaskillfullychosenconfigurationwhichsatisfiesdifferentneedsofalargenumber
ofusersallowingatthesametimeconstantexpansions(referstothenewtypesofmicrocontrollers).Besides,thesoftwarehasbeen
developedingreatextendinthemeantime,anditsimplywasnotprofitabletochangeanythinginthemicrocontrollersbasiccore.Thisis
thereasonforhavingagreatnumberofvariousmicrocontrollerswhichbasicallyaresolelyupgradedversionsofthe8051family.What
makesthismicrocontrollersospecialanduniversalsothatalmostallmanufacturersallovertheworldmanufactureittodayunderdifferent
name?

mikroProgfor8051issupportedwith
mikroC,mikroBasicand
mikroPascalcompilersfor8051.You
mayalsousemikroProgfor8051asa
standaloneprogrammingtool.[moreinfo]

FeaturedCompilers
mikroBasicPROfor8051
The8051corecombinedwithmodern
modulesispopularinthepast.With
mikroBasicyoucanquicklydevelop
yourprojects.[moreinfo]

Asseeninfigureabove,the8051microcontrollerhasnothingimpressiveinappearance:

4KbofROMisnotmuchatall.
128bofRAM(includingSFRs)satisfiestheuser'sbasicneeds.
4portshavingintotalof32input/outputlinesareinmostcasessufficienttomakeallnecessaryconnectionsto
peripheralenvironment.
Thewholeconfigurationisobviouslythoughtofastosatisfytheneedsofmostprogrammersworkingondevelopmentofautomation
devices.Oneofitsadvantagesisthatnothingismissingandnothingistoomuch.Inotherwords,itiscreatedexactlyinaccordancetothe
averageuserstasteandneeds.AnotheradvantagesareRAMorganization,theoperationofCentralProcessorUnit(CPU)andportswhich
completelyuseallrecoursesandenablefurtherupgrade.

2.2PinoutDescription
Pins18:Port1 Eachofthesepinscanbeconfiguredasaninputoranoutput.
Pin9:RS Alogiconeonthispindisablesthemicrocontrollerandclearsthecontentsofmostregisters.Inotherwords,thepositivevoltage
onthispinresetsthemicrocontroller.Byapplyinglogiczerotothispin,theprogramstartsexecutionfromthebeginning.
Pins1017:Port3 Similartoport1,eachofthesepinscanserveasgeneralinputoroutput.Besides,allofthemhavealternative
functions:
Pin10:RXD SerialasynchronouscommunicationinputorSerialsynchronouscommunicationoutput.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

1/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Pin11:TXD SerialasynchronouscommunicationoutputorSerialsynchronouscommunicationclockoutput.
Pin12:INT0 Interrupt0input.
Pin13:INT1 Interrupt1input.
Pin14:T0 Counter0clockinput.
Pin15:T1 Counter1clockinput.
Pin16:WR Writetoexternal(additional)RAM.
Pin17:RD ReadfromexternalRAM.
Pin18,19:X2,X1 Internaloscillatorinputandoutput.Aquartzcrystalwhichspecifiesoperatingfrequencyisusuallyconnectedtothese
pins.Insteadofit,miniatureceramicsresonatorscanalsobeusedforfrequencystability.Laterversionsofmicrocontrollersoperateata
frequencyof0Hzuptoover50Hz.
Pin20:GND Ground.
Pin2128:Port2 Ifthereisnointentiontouseexternalmemorythentheseportpinsareconfiguredasgeneralinputs/outputs.Incase
externalmemoryisused,thehigheraddressbyte,i.e.addressesA8A15willappearonthisport.Eventhoughmemorywithcapacityof
64Kbisnotused,whichmeansthatnotalleightportbitsareusedforitsaddressing,therestofthemarenotavailableasinputs/outputs.
Pin29:PSEN IfexternalROMisusedforstoringprogramthenalogiczero(0)appearsoniteverytimethemicrocontrollerreadsabyte
frommemory.
Pin30:ALE Priortoreadingfromexternalmemory,themicrocontrollerputstheloweraddressbyte(A0A7)onP0andactivatestheALE
output.AfterreceivingsignalfromtheALEpin,theexternalregister(usually74HCT373or74HCT375addonchip)memorizesthestateof
P0andusesitasamemorychipaddress.Immediatelyafterthat,theALUpinisreturneditspreviouslogicstateandP0isnowusedasa
DataBus.Asseen,portdatamultiplexingisperformedbymeansofonlyoneadditional(andcheap)integratedcircuit.Inotherwords,this
portisusedforbothdataandaddresstransmission.
Pin31:EA Byapplyinglogiczerotothispin,P2andP3areusedfordataandaddresstransmissionwithnoregardtowhetherthereis
internalmemoryornot.Itmeansthateventhereisaprogramwrittentothemicrocontroller,itwillnotbeexecuted.Instead,theprogram
writtentoexternalROMwillbeexecuted.ByapplyinglogiconetotheEApin,themicrocontrollerwillusebothmemories,firstinternalthen
external(ifexists).
Pin3239:Port0 SimilartoP2,ifexternalmemoryisnotused,thesepinscanbeusedasgeneralinputs/outputs.Otherwise,P0is
configuredasaddressoutput(A0A7)whentheALEpinisdrivenhigh(1)orasdataoutput(DataBus)whentheALEpinisdrivenlow(0).
Pin40:VCC +5Vpowersupply.

2.3Input/OutputPorts(I/OPorts)
All8051microcontrollershave4I/Oportseachcomprising8bitswhichcanbeconfiguredasinputsoroutputs.Accordingly,intotalof32
input/outputpinsenablingthemicrocontrollertobeconnectedtoperipheraldevicesareavailableforuse.
Pinconfiguration,i.e.whetheritistobeconfiguredasaninput(1)oranoutput(0),dependsonitslogicstate.Inordertoconfigurea
microcontrollerpinasanoutput,itisnecessarytoapplyalogiczero(0)toappropriateI/Oportbit.Inthiscase,voltagelevelonappropriate
pinwillbe0.
Similarly,inordertoconfigureamicrocontrollerpinasaninput,itisnecessarytoapplyalogicone(1)toappropriateport.Inthiscase,
voltagelevelonappropriatepinwillbe5V(asisthecasewithanyTTLinput).Thismayseemconfusingbutdon'tlooseyourpatience.Itall
becomesclearafterstudyingsimpleelectroniccircuitsconnectedtoanI/Opin.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

2/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Input/Output(I/O)pin
Figureaboveillustratesasimplifiedschematicofallcircuitswithin
themicrocontrolerconnectedtooneofitspins.Itreferstoallthe
pinsexceptthoseoftheP0portwhichdonothavepullup
resistorsbuiltin.

Outputpin
Alogiczero(0)isappliedtoabitofthePregister.TheoutputFE
transistoristurnedon,thusconnectingtheappropriatepinto
ground.

Inputpin
Alogicone(1)isappliedtoabitofthePregister.TheoutputFE
transistoristurnedoffandtheappropriatepinremainsconnected
tothepowersupplyvoltageoverapullupresistorofhigh
resistance.

Logicstate(voltage)ofanypincanbechangedorreadatanymoment.Alogiczero(0)andlogicone(1)arenotequal.Alogicone(0)
representsashortcircuittoground.Suchapinactsasanoutput.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

3/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Alogicone(1)islooselyconnectedtothepowersupplyvoltageoveraresistorofhighresistance.Sincethisvoltagecanbeeasily
reducedbyanexternalsignal,suchapinactsasaninput.

Port0
TheP0portischaracterizedbytwofunctions.Ifexternalmemoryisusedthentheloweraddressbyte(addressesA0A7)isappliedonit.
Otherwise,allbitsofthisportareconfiguredasinputs/outputs.
Theotherfunctionisexpressedwhenitisconfiguredasanoutput.Unlikeotherportsconsistingofpinswithbuiltinpullupresistor
connectedbyitsendto5Vpowersupply,pinsofthisporthavethisresistorleftout.Thisapparentlysmalldifferencehasitsconsequences:
Ifanypinofthisportisconfiguredasaninputthenitactsasifitfloats.
Suchaninputhasunlimitedinputresistanceandindeterminedpotential.

Whenthepinisconfiguredasanoutput,itactsasan
opendrain.Byapplyinglogic0toaportbit,the
appropriatepinwillbeconnectedtoground(0V).By
applyinglogic1,theexternaloutputwillkeepon
floating.Inordertoapplylogic1(5V)onthisoutputpin,
itisnecessarytobuiltinanexternalpullupresistor.

OnlyincaseP0isusedforaddressingexternalmemory,themicrocontrollerwillprovideinternalpowersupply
sourceinordertosupplyitspinswithlogicone.Thereisnoneedtoaddexternalpullupresistors.

Port1
P1isatrueI/Oport,becauseitdoesn'thaveanyalternativefunctionsasisthecasewithP0,butcanbecofiguredasgeneralI/Oonly.Ithas
apullupresistorbuiltinandiscompletelycompatiblewithTTLcircuits.

Port2
P2actssimilarlytoP0whenexternalmemoryisused.Pinsofthisportoccupyaddressesintendedforexternalmemorychip.Thistimeitis
aboutthehigheraddressbytewithaddressesA8A15.Whennomemoryisadded,thisportcanbeusedasageneralinput/outputport
showingfeaturessimilartoP1.

Port3
AllportpinscanbeusedasgeneralI/O,buttheyalsohaveanalternativefunction.Inordertousethesealternativefunctions,alogicone(1)
mustbeappliedtoappropriatebitoftheP3register.Intemsofhardware,thisportissimilartoP0,withthedifferencethatitspinshavea
pullupresistorbuiltin.

Pin'sCurrentlimitations
Whenconfiguredasoutputs(logiczero(0)),singleportpinscanreceiveacurrentof10mA.Ifall8bitsofaportareactive,atotalcurrent
mustbelimitedto15mA(portP0:26mA).Ifallports(32bits)areactive,totalmaximumcurrentmustbelimitedto71mA.Whenthesepins
areconfiguredasinputs(logic1),builtinpullupresistorsprovideveryweakcurrent,butstrongenoughtoactivateupto4TTLinputsofLS
series.

Asseenfromdescriptionofsomeports,eventhoughallofthemhavemoreorlesssimilararchitecture,itisnecessarytopayattentionto
whichofthemistobeusedforwhatandhow.
Forexample,iftheyshallbeusedasoutputswithhighvoltagelevel(5V),thenP0shouldbeavoidedbecauseitspinsdonothavepullup
resistors,thusgivinglowlogiclevelonly.Whenusingotherports,oneshouldhaveinmindthatpullupresistorshavearelativelyhigh
resistance,sothattheirpinscangiveacurrentofseveralhundredsmicroamperesonly.

2.4MemoryOrganization
The8051hastwotypesofmemoryandtheseareProgramMemoryandDataMemory.ProgramMemory(ROM)isusedtopermanently
savetheprogrambeingexecuted,whileDataMemory(RAM)isusedfortemporarilystoringdataandintermediateresultscreatedandused
duringtheoperationofthemicrocontroller.Dependingonthemodelinuse(wearestilltalkingaboutthe8051microcontrollerfamilyin
general)atmostafewKbofROMand128or256bytesofRAMisused.However
All8051microcontrollershavea16bitaddressingbusandarecapableofaddressing64kbmemory.Itisneitheramistakenorabig
ambitionofengineerswhowereworkingonbasiccoredevelopment.Itisamatterofsmartmemoryorganizationwhichmakesthese
microcontrollersarealprogrammersgoody.

ProgramMemory
Thefirstmodelsofthe8051microcontrollerfamilydidnothaveinternalprogrammemory.Itwasaddedasanexternalseparatechip.These
modelsarerecognizablebytheirlabelbeginningwith803(forexample8031or8032).AlllatermodelshaveafewKbyteROMembedded.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

4/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Eventhoughsuchanamountofmemoryissufficientforwritingmostoftheprograms,therearesituationswhenitisnecessarytouse
additionalmemoryaswell.Atypicalexamplearesocalledlookuptables.Theyareusedincaseswhenequationsdescribingsome
processesaretoocomplicatedorwhenthereisnotimeforsolvingthem.Insuchcasesallnecessaryestimatesandapproximatesare
executedinadvanceandthefinalresultsareputinthetables(similartologarithmictables).

HowdoesthemicrocontrollerhandleexternalmemorydependsontheEApinlogicstate:

EA=0Inthiscase,themicrocontrollercompletelyignoresinternalprogrammemoryandexecutesonlytheprogramstoredinexternal
memory.
EA=1Inthiscase,themicrocontrollerexecutesfirsttheprogramfrombuiltinROM,thentheprogramstoredinexternalmemory.
Inbothcases,P0andP2arenotavailableforusesincebeingusedfordataandaddresstransmission.Besides,theALEandPSENpins
arealsoused.

DataMemory
Asalreadymentioned,DataMemoryisusedfortemporarilystoringdataandintermediateresultscreatedandusedduringtheoperationof
themicrocontroller.Besides,RAMmemorybuiltinthe8051familyincludesmanyregisterssuchashardwarecountersandtimers,
input/outputports,serialdatabuffersetc.Thepreviousmodelshad256RAMlocations,whileforthelatermodelsthisnumberwas
incrementedbyadditional128registers.However,thefirst256memorylocations(addresses0FFh)aretheheartofmemorycommontoall
themodelsbelongingtothe8051family.Locationsavailabletotheuseroccupymemoryspacewithaddresses07Fh,i.e.first128registers.
ThispartofRAMisdividedinseveralblocks.
Thefirstblockconsistsof4bankseachincluding8registersdenotedbyR0R7.Priortoaccessinganyoftheseregisters,itisnecessaryto
selectthebankcontainingit.Thenextmemoryblock(address20h2Fh)isbitaddressable,whichmeansthateachbithasitsownaddress
(07Fh).Sincethereare16suchregisters,thisblockcontainsintotalof128bitswithseparateaddresses(addressofbit0ofthe20hbyteis
0,whileaddressofbit7ofthe2Fhbyteis7Fh).Thethirdgroupofregistersoccupyaddresses2Fh7Fh,i.e.80locations,anddoesnothave
anyspecialfunctionsorfeatures.

AdditionalRAM
InordertosatisfytheprogrammersconstanthungerforDataMemory,themanufacturersdecidedtoembedanadditionalmemoryblockof
128locationsintothelatestversionsofthe8051microcontrollers.However,itsnotassimpleasitseemstobeTheproblemisthat
electronicsperformingaddressinghas1byte(8bits)ondisposalandiscapableofreachingonlythefirst256locations,therefore.Inorder
tokeepalreadyexisting8bitarchitectureandcompatibilitywithotherexistingmodelsasmalltrickwasdone.
Whatdoesitmean?ItmeansthatadditionalmemoryblocksharesthesameaddresseswithlocationsintendedfortheSFRs(80hFFh).In
ordertodifferentiatebetweenthesetwophysicallyseparatedmemoryspaces,differentwaysofaddressingareused.TheSFRsmemory
locationsareaccessedbydirectaddressing,whileadditionalRAMmemorylocationsareaccessedbyindirectaddressing.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

5/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Memoryexpansion
Incasememory(RAMorROM)builtinthemicrocontrollerisnotsufficient,itispossibletoaddtwoexternalmemorychipswithcapacityof
64Kbeach.P2andP3I/Oportsareusedfortheiraddressinganddatatransmission.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

6/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Fromtheuserspointofview,everythingworksquitesimplywhenproperlyconnectedbecausemostoperationsareperformedbythe
microcontrolleritself.The8051microcontrollerhastwopinsfordatareadRD#(P3.7)andPSEN#.Thefirstoneisusedforreadingdatafrom
externaldatamemory(RAM),whiletheotherisusedforreadingdatafromexternalprogrammemory(ROM).Bothpinsareactivelow.A
typicalexampleofmemoryexpansionbyaddingRAMandROMchips(Hardwardarchitecture),isshowninfigureabove.
Eventhoughadditionalmemoryisrarelyusedwiththelatestversionsofthemicrocontrollers,wewilldescribeinshortwhathappenswhen
memorychipsareconnectedaccordingtothepreviousschematic.Thewholeprocessdescribedbelowisperformedautomatically.

Whentheprogramduringexecutionencountersaninstructionwhichresidesinexternalmemory(ROM),the
microcontrollerwillactivateitscontroloutputALEandsetthefirst8bitsofaddress(A0A7)onP0.ICcircuit
74HCT573passesthefirst8bitstomemoryaddresspins.
AsignalontheALEpinlatchestheICcircuit74HCT573andimmediatelyafterwards8higherbitsofaddress(A8
A15)appearontheport.Inthisway,adesiredlocationofadditionalprogrammemoryisaddressed.Itisleftoverto
readitscontent.
PortP0pinsareconfiguredasinputs,thePSENpinisactivatedandthemicrocontrollerreadsfrommemorychip.
SimilaroccurswhenitisnecessarytoreadlocationfromexternalRAM.Addressingisperformedinthesameway,whilereadandwriteare
performedviasignalsappearingonthecontroloutputsRD(isshortforread)orWR(isshortforwrite).

Addressing
Whileoperating,theprocessorprocessesdataasperprograminstructions.Eachinstructionconsistsoftwoparts.OnepartdescribesWHAT
shouldbedone,whiletheotherexplainsHOWtodoit.Thelatterpartcanbeadata(binarynumber)ortheaddressatwhichthedatais
stored.Twowaysofaddressingareusedforall8051microcontrollersdependingonwhichpartofmemoryshouldbeaccessed:

DirectAddressing
Ondirectaddressing,theaddressofmemorylocationcontainingdatatobereadisspecifiedininstruction.Theaddressmaycontaina
numberbeingchangedduringoperation(variable).Forexample:
Sincetheaddressisonlyonebyteinsize(thelargestnumberis255),onlythefirst255locationsofRAMcanbeaccessedthisway.Thefirst
halfofRAMisavailableforuse,whileanotherhalfisreservedforSFRs.

MOVA,33hMeans:moveanumberfromaddress33hex.toaccumulator

IndirectAddressing
Onindirectaddressing,aregistercontainingtheaddressofanotherregisterisspecifiedininstruction.Datatobeusedintheprogramis
storedintheletterregister.Forexample:
IndirectaddressingisonlyusedforaccessingRAMlocationsavailableforuse(neverforaccessingSFRs).Thisistheonlywayofaccessing
allthelatestversionsofthemicrocontrollerswithadditionalmemoryblock(128locationsofRAM).Simplyput,whentheprogram
encountersinstructionincluding@signandifthespecifiedaddressishigherthan128(7Fhex.),theprocessorknowsthatindirect
addressingisusedandskipsmemoryspacereservedforSFRs.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

7/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

MOVA,@R0Means:StorethevaluefromtheregisterwhoseaddressisintheR0register
intoaccumulator

Onindirectaddressing,registersR0,R1orStackPointerareusedforspecifying8bitaddresses.Sinceonly8bitsareavilable,itispossible
toaccessonlyregistersofinternalRAMthisway(128locationswhenspeakingofpreviousmodelsor256locationswhenspeakingoflatest
modelsofmicrocontrollers).Ifanextramemorychipisaddedthenthe16bitDPTRRegister(consistingoftheregistersDPTRLand
DPTRH)isusedforspecifyingaddress.Inthiswayitispossibletoaccessanylocationintherangeof64K.

2.5SpecialFunctionRegisters(SFRs)
SpecialFunctionRegisters(SFRs)areasortofcontroltableusedforrunningandmonitoringtheoperationofthemicrocontroller.Eachof
theseregistersaswellaseachbittheyinclude,hasitsname,addressinthescopeofRAMandpreciselydefinedpurposesuchastimer
control,interruptcontrol,serialcommunicationcontroletc.Eventhoughthereare128memorylocationsintendedtobeoccupiedbythem,
thebasiccore,sharedbyalltypesof8051microcontrollers,hasonly21suchregisters.Restoflocationsareintensionallyleftunoccupiedin
ordertoenablethemanufacturerstofurtherdevelopmicrocontrollerskeepingthemcompatiblewiththepreviousversions.Italsoenables
programswrittenalongtimeagoformicrocontrollerswhichareoutofproductionnowtobeusedtoday.

ARegister(Accumulator)

Aregisterisageneralpurposeregisterusedforstoringintermediateresultsobtainedduringoperation.Priortoexecutinganinstruction
uponanynumberoroperanditisnecessarytostoreitintheaccumulatorfirst.Allresultsobtainedfromarithmeticaloperationsperformedby
theALUarestoredintheaccumulator.Datatobemovedfromoneregistertoanothermustgothroughtheaccumulator.Inotherwords,the
Aregisteristhemostcommonlyusedregisteranditisimpossibletoimagineamicrocontrollerwithoutit.Morethanhalfinstructionsusedby
the8051microcontrollerusesomehowtheaccumulator.

BRegister
MultiplicationanddivisioncanbeperformedonlyuponnumbersstoredintheAandBregisters.Allotherinstructionsintheprogramcan
usethisregisterasaspareaccumulator(A).

Duringtheprocessofwritingaprogram,eachregisteriscalledbyitsnamesothattheirexactaddressesarenot
ofimportancefortheuser.Duringcompilation,theirnameswillbeautomaticallyreplacedbyappropriate
addresses.

RRegisters(R0R7)
Thisisacommonnamefor8generalpurposeregisters(R0,R1,R2...R7).EventhoughtheyarenottrueSFRs,theydeservetobe
discussedherebecauseoftheirpurpose.Theyoccupy4bankswithinRAM.Similartotheaccumulator,theyareusedfortemporarystoring
variablesandintermediateresultsduringoperation.WhichoneofthesebanksistobeactivedependsontwobitsofthePSWRegister.
Activebankisabanktheregistersofwhicharecurrentlyused.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

8/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Thefollowingexamplebestillustratesthepurposeoftheseregisters.Supposeitisnecessarytoperformsomearithmeticaloperationsupon
numberspreviouslystoredintheRregisters:(R1+R2)(R3+R4).Obviously,aregisterfortemporarystoringresultsofadditionisneeded.
Thisishowitlooksintheprogram:

MOVA,R3Means:movenumberfromR3intoaccumulator
ADDA,R4Means:addnumberfromR4toaccumulator(resultremainsinaccumulator)
MOVR5,AMeans:temporarilymovetheresultfromaccumulatorintoR5
MOVA,R1Means:movenumberfromR1toaccumulator
ADDA,R2Means:addnumberfromR2toaccumulator
SUBBA,R5Means:subtractnumberfromR5(thereareR3+R4)

ProgramStatusWord(PSW)Register

PSWregisterisoneofthemostimportantSFRs.ItcontainsseveralstatusbitsthatreflectthecurrentstateoftheCPU.Besides,thisregister
containsCarrybit,AuxiliaryCarry,tworegisterbankselectbits,Overflowflag,paritybitanduserdefinablestatusflag.
PParitybit.Ifanumberstoredintheaccumulatoriseventhenthisbitwillbeautomaticallyset(1),otherwiseitwillbecleared(0).Itis
mainlyusedduringdatatransmitandreceiveviaserialcommunication.
Bit1.Thisbitisintendedtobeusedinthefutureversionsofmicrocontrollers.
OVOverflowoccurswhentheresultofanarithmeticaloperationislargerthan255andcannotbestoredinoneregister.Overflowcondition
causestheOVbittobeset(1).Otherwise,itwillbecleared(0).
RS0,RS1Registerbankselectbits.ThesetwobitsareusedtoselectoneoffourregisterbanksofRAM.Bysettingandclearingthese
bits,registersR0R7arestoredinoneoffourbanksofRAM.
RS1

RS2

SPACEINRAM

Bank000h07h

Bank108h0Fh

Bank210h17h

Bank318h1Fh

F0Flag0.Thisisageneralpurposebitavailableforuse.
ACAuxiliaryCarryFlagisusedforBCDoperationsonly.
CYCarryFlagisthe(ninth)auxiliarybitusedforallarithmeticaloperationsandshiftinstructions.

DataPointerRegister(DPTR)
DPTRregisterisnotatrueonebecauseitdoesn'tphysicallyexist.Itconsistsoftwoseparateregisters:DPH(DataPointerHigh)and(Data
PointerLow).Forthisreasonitmaybetreatedasa16bitregisterorastwoindependent8bitregisters.Their16bitsareprimarlyusedfor
externalmemoryaddressing.Besides,theDPTRRegisterisusuallyusedforstoringdataandintermediateresults.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

9/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

StackPointer(SP)Register

AvaluestoredintheStackPointerpointstothefirstfreestackaddressandpermitsstackavailability.Stackpushesincrementthevaluein
theStackPointerby1.Likewise,stackpopsdecrementitsvalueby1.Uponanyresetandpoweron,thevalue7isstoredintheStack
Pointer,whichmeansthatthespaceofRAMreservedforthestackstartsatthislocation.Ifanothervalueiswrittentothisregister,theentire
Stackismovedtothenewmemorylocation.

P0,P1,P2,P3Input/OutputRegisters

Ifneitherexternalmemorynorserialcommunicationsystemareusedthen4portswithintotalof32input/outputpinsareavailablefor
connectiontoperipheralenvironment.Eachbitwithintheseportsaffectsthestateandperformanceofappropriatepinofthemicrocontroller.
Thus,bitlogicstateisreflectedonappropriatepinasavoltage(0or5V)andviceversa,voltageonapinreflectsthestateofappropriate
portbit.
Asmentioned,portbitstateaffectsperformanceofportpins,i.e.whethertheywillbeconfiguredasinputsoroutputs.Ifabitiscleared(0),
theappropriatepinwillbeconfiguredasanoutput,whileifitisset(1),theappropriatepinwillbeconfiguredasaninput.Uponresetand
poweron,allportbitsareset(1),whichmeansthatallappropriatepinswillbeconfiguredasinputs.

I/Oportsaredirectlyconnectedtothemicrocontrollerpins.Accordingly,logicstateoftheseregisterscanbecheckedbyvoltmeterand
viceversa,voltageonthepinscanbecheckedbyinspectingtheirbits!

2.6CountersandTimers
Asyoualreadyknow,themicrocontrolleroscillatorusesquartzcrystalforitsoperation.Asthefrequencyofthisoscillatorispreciselydefined
andverystable,pulsesitgeneratesarealwaysofthesamewidth,whichmakesthemidealfortimemeasurement.Suchcrystalsarealso
usedinquartzwatches.Inordertomeasuretimebetweentwoeventsitissufficienttocountuppulsescomingfromthisoscillator.Thatis
exactlywhatthetimerdoes.Ifthetimerisproperlyprogrammed,thevaluestoredinitsregisterwillbeincremented(ordecremented)with
eachcomingpulse,i.e.oncepereachmachinecycle.Asinglemachinecycleinstructionlastsfor12quartzoscillatorperiods,whichmeans
thatbyembeddingquartzwithoscillatorfrequencyof12MHz,anumberstoredinthetimerregisterwillbechangedmilliontimesper
second,i.e.eachmicrosecond.
The8051microcontrollerhas2timers/counterscalledT0andT1.Astheirnamessuggest,theirmainpurposeistomeasuretimeandcount
externalevents.Besides,theycanbeusedforgeneratingclockpulsestobeusedinserialcommunication,socalledBaudRate.

TimerT0
Asseeninfigurebelow,thetimerT0consistsoftworegistersTH0andTL0representingalowandahighbyteofone16digitbinary
number.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

10/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Accordingly,ifthecontentofthetimerT0isequalto0(T0=0)thenbothregistersitconsistsofwillcontain0.Ifthetimercontainsforexample
number1000(decimal),thentheTH0register(highbyte)willcontainthenumber3,whiletheTL0register(lowbyte)willcontaindecimal
number232.

Formulausedtocalculatevaluesinthesetworegistersisverysimple:
TH0256+TL0=T
Matchingthepreviousexampleitwouldbeasfollows:
3256+232=1000

SincethetimerT0isvirtually16bitregister,thelargestvalueitcanstoreis65535.Incaseofexceedingthisvalue,thetimerwillbe
automaticallyclearedandcountingstartsfrom0.Thisconditioniscalledanoverflow.TworegistersTMODandTCONarecloselyconnected
tothistimerandcontrolitsoperation.

TMODRegister(TimerMode)
TheTMODregisterselectstheoperationalmodeofthetimersT0andT1.Asseeninfigurebelow,thelow4bits(bit0bit3)refertothetimer
0,whilethehigh4bits(bit4bit7)refertothetimer1.Thereare4operationalmodesandeachofthemisdescribedherein.

Bitsofthisregisterhavethefollowingfunction:

GATE1enablesanddisablesTimer1bymeansofasignalbroughttotheINT1pin(P3.3):
1Timer1operatesonlyiftheINT1bitisset.
0Timer1operatesregardlessofthelogicstateoftheINT1bit.

C/T1selectspulsestobecountedupbythetimer/counter1:
1TimercountspulsesbroughttotheT1pin(P3.5).
0Timercountspulsesfrominternaloscillator.

T1M1,T1M0ThesetwobitsselecttheoperationalmodeoftheTimer1.
T1M1

T1M0

MO DE

DESCRIPT IO N

13bittimer

16bittimer

8bitautoreload

Splitmode

GATE0enablesanddisablesTimer1usingasignalbroughttotheINT0pin(P3.2):
1Timer0operatesonlyiftheINT0bitisset.
0Timer0operatesregardlessofthelogicstateoftheINT0bit.

C/T0selectspulsestobecountedupbythetimer/counter0:
1TimercountspulsesbroughttotheT0pin(P3.4).
0Timercountspulsesfrominternaloscillator.

T0M1,T0M0ThesetwobitsselecttheoprtaionalmodeoftheTimer0.
T0M1

T0M0

MO DE

DESCRIPT IO N

13bittimer

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

11/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika
0

16bittimer

8bitautoreload

Splitmode

Timer0inmode0(13bittimer)
Thisisoneoftheraritiesbeingkeptonlyforthepurposeofcompatibilitywiththepreviuosversionsofmicrocontrollers.Thismode
configurestimer0asa13bittimerwhichconsistsofall8bitsofTH0andthelower5bitsofTL0.Asaresult,theTimer0usesonly13of16
bits.Howdoesitoperate?Eachcomingpulsecausesthelowerregisterbitstochangetheirstates.Afterreceiving32pulses,thisregisteris
loadedandautomaticallycleared,whilethehigherbyte(TH0)isincrementedby1.Thisprocessisrepeateduntilregisterscountup8192
pulses.Afterthat,bothregistersareclearedandcountingstartsfrom0.

Timer0inmode1(16bittimer)
Mode1configurestimer0asa16bittimercomprisingallthebitsofbothregistersTH0andTL0.That'swhythisisoneofthemost
commonlyusedmodes.Timeroperatesinthesamewayasinmode0,withdifferencethattheregisterscountupto65536asallowableby
the16bits.

Timer0inmode2(AutoReloadTimer)
Mode2configurestimer0asan8bittimer.Actually,timer0usesonlyone8bitregisterforcountingandnevercountsfrom0,butfroman
arbitraryvalue(0255)storedinanother(TH0)register.
Thefollowingexampleshowstheadvantagesofthismode.Supposeitisnecessarytoconstantlycountup55pulsesgeneratedbythe
clock.
Ifmode1ormode0isused,Itisnecessarytowritethenumber200tothetimerregistersandconstantlycheckwhetheranoverflowhas
occured,i.e.whethertheyreachedthevalue255.Whenithappens,itisnecessarytorewritethenumber200andrepeatthewhole
procedure.Thesameprocedureisautomaticallyperformedbythemicrocontrollerifsetinmode2.Infact,onlytheTL0registeroperatesas
atimer,whileanother(TH0)registerstoresthevaluefromwhichthecountingstarts.WhentheTL0registerisloaded,insteadofbeing
cleared,thecontentsofTH0willbereloadedtoit.Referringtothepreviousexample,inordertoregistereach55thpulse,thebestsolution
istowritethenumber200totheTH0registerandconfigurethetimertooperateinmode2.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

12/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Timer0inMode3(SplitTimer)
Mode3configurestimer0sothatregistersTL0andTH0operateasseparate8bittimers.Inotherwords,the16bittimerconsistingoftwo
registersTH0andTL0issplitintotwoindependent8bittimers.Thismodeisprovidedforapplicationsrequiringanadditional8bittimeror
counter.TheTL0timerturnsintotimer0,whiletheTH0timerturnsintotimer1.Inaddition,allthecontrolbitsof16bitTimer1(consistingof
theTH1andTL1register),nowcontrolthe8bitTimer1.Eventhoughthe16bitTimer1canstillbeconfiguredtooperateinanyofmodes
(mode1,2or3),itisnolongerpossibletodisableitasthereisnocontrolbittodoit.Thus,itsoperationisrestrictedwhentimer0isinmode
3.

Theonlyapplicationofthismodeiswhentwotimersareusedandthe16bitTimer1theoperationofwhichisoutofcontrolisusedasa
baudrategenerator.

TimerControl(TCON)Register
TCONregisterisalsooneoftheregisterswhosebitsaredirectlyincontroloftimeroperation.
Only4bitsofthisregisterareusedforthispurpose,whilerestofthemisusedforinterruptcontroltobediscussedlater.

TF1bitisautomaticallysetontheTimer1overflow.
TR1bitenablestheTimer1.
1Timer1isenabled.
0Timer1isdisabled.

TF0bitisautomaticallysetontheTimer0overflow.
TR0bitenablesthetimer0.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

13/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

1Timer0isenabled.
0Timer0isdisabled.

HowtousetheTimer0?
Inordertousetimer0,itisfirstnecessarytoselectitandconfigurethemodeofitsoperation.BitsoftheTMODregisterareincontrolofit:

Referringtofigureabove,thetimer0operatesinmode1andcountspulsesgeneratedbyinternalclockthefrequencyofwhichisequalto
1/12thequartzfrequency.
Turnonthetimer:

TheTR0bitissetandthetimerstartsoperation.Ifthequartzcrystalwithfrequencyof12MHzisembeddedthenitscontentswillbe
incrementedeverymicrosecond.After65.536microseconds,thebothregistersthetimerconsistsofwillbeloaded.Themicrocontroller
automaticallyclearsthemandthetimerkeepsonrepeatingprocedurefromthebeginninguntiltheTR0bitvalueislogiczero(0).

Howto'read'atimer?
Dependingonapplication,itisnecessaryeithertoreadanumberstoredinthetimerregistersortoregisterthemomenttheyhavebeen
cleared.
Itisextremelysimpletoreadatimerbyusingonlyoneregisterconfiguredinmode2or3.Itissufficienttoreaditsstateatanymoment.
That'sall!
Itissomehowcomplicatedtoreadatimerconfiguredtooperateinmode2.Supposethelowerbyteisreadfirst(TL0),thenthehigherbyte
(TH0).Theresultis:
TH0=15TL0=255
Everythingseemstobeok,butthecurrentstateoftheregisteratthemomentofreadingwas:
TH0=14TL0=255
Incaseofnegligence,suchanerrorincounting(255pulses)mayoccurfornotsoobviousbutquitelogicalreason.Thelowerbyteis
correctlyread(255),butatthemomenttheprogramcounterwasabouttoreadthehigherbyteTH0,anoverflowoccurredandthecontents
ofbothregistershavebeenchanged(TH0:1415,TL0:2550).Thisproblemhasasimplesolution.Thehigherbyteshouldbereadfirst,
thenthelowerbyteandonceagainthehigherbyte.Ifthenumberstoredinthehigherbyteisdifferentthenthissequenceshouldbe
repeated.It'saboutashortloopconsistingofonly3instructionsintheprogram.
Thereisanothersolutionaswell.Itissufficienttosimplyturnthetimeroffwhilereadingisgoingon(theTR0bitoftheTCONregistershould
becleared),andturnitonagainafterreadingisfinished.

Timer0OverflowDetection
Usually,thereisnoneedtoconstantlyreadtimerregisters.Itissufficienttoregisterthemomenttheyarecleared,i.e.whencountingstarts
from0.Thisconditioniscalledanoverflow.Whenitoccurrs,theTF0bitoftheTCONregisterwillbeautomaticallyset.Thestateofthisbit
canbeconstantlycheckedfromwithintheprogramorbyenablinganinterruptwhichwillstopthemainprogramexecutionwhenthisbitis
set.Supposeitisnecessarytoprovideaprogramdelayof0.05seconds(50000machinecycles),i.e.timewhentheprogramseemstobe
stopped:

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

14/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Firstanumbertobewrittentothetimerregistersshouldbecalculated:

ThenitshouldbewrittentothetimerregistersTH0andTL0:

Whenenabled,thetimerwillresumecountingfromthisnumber.ThestateoftheTF0bit,i.e.whetheritisset,ischeckedfromwithinthe
program.Ithappensatthemomentofoverflow,i.e.afterexactly50.000machinecyclesor0.05seconds.

Howtomeasurepulseduration?
Supposeitisnecessarytomeasurethedurationofanoperation,forexamplehowlongadevicehasbeenturnedon?Lookagainatthe
figureillustratingthetimerandpayattentiontothefunctionoftheGATE0bitoftheTMODregister.IfitisclearedthenthestateoftheP3.2
pindoesn'taffecttimeroperation.IfGATE0=1thetimerwilloperateuntilthepinP3.2iscleared.Accordingly,ifthispinissuppliedwith5V
throughsomeexternalswitchatthemomentthedeviceisbeingturnedon,thetimerwillmeasuredurationofitsoperation,whichactually
wastheobjective.

Howtocountuppulses?
Similarlytothepreviousexample,theanswertothisquestionagainliesintheTCONregister.Thistimeit'sabouttheC/T0bit.Ifthebitis
clearedthetimercountspulsesgeneratedbytheinternaloscillator,i.e.measuresthetimepassed.Ifthebitisset,thetimerinputisprovided
withpulsesfromtheP3.4pin(T0).Sincethesepulsesarenotalwaysofthesamewidth,thetimercannotbeusedfortimemeasurementand
isturnedintoacounter,therefore.Thehighestfrequencythatcouldbemeasuredbysuchacounteris1/24frequencyofusedquartzcrystal.

Timer1
Timer1isidenticaltotimer0,exceptformode3whichisaholdcountmode.Itmeansthattheyhavethesamefunction,theiroperationis
controlledbythesameregistersTMODandTCONandbothofthemcanoperateinoneoutof4differentmodes.

2.7UART(UniversalAsynchronousReceiverandTransmitter)
OneofthemicrocontrollerfeaturesmakingitsopowerfulisanintegratedUART,betterknownasaserialport.Itisafullduplexport,thus
beingabletotransmitandreceivedatasimultaneouslyandatdifferentbaudrates.Withoutit,serialdatasendandreceivewouldbean
enormouslycomplicatedpartoftheprograminwhichthepinstateisconstantlychangedandcheckedatregularintervals.Whenusing
UART,alltheprogrammerhastodoistosimplyselectserialportmodeandbaudrate.Whenit'sdone,serialdatatransmitisnothingbut
writingtotheSBUFregister,whiledatareceiverepresentsreadingthesameregister.Themicrocontrollertakescareofnotmakinganyerror
duringdatatransmission.

Serialportmustbeconfiguredpriortobeingused.Inotherwords,itisnecessarytodeterminehowmanybitsiscontainedinoneserial
word,baudrateandsynchronizationclocksource.ThewholeprocessisincontrolofthebitsoftheSCONregister(SerialControl).

SerialPortControl(SCON)Register

SM0Serialportmodebit0isusedforserialportmodeselection.
SM1Serialportmodebit1.
SM2Serialportmode2bit,alsoknownasmultiprocessorcommunicationenablebit.Whenset,itenables
multiprocessorcommunicationinmode2and3,andeventuallymode1.Itshouldbeclearedinmode0.
RENReceptionEnablebitenablesserialreceptionwhenset.Whencleared,serialreceptionisdisabled.
TB8Transmitterbit8.Sinceallregistersare8bitwide,thisbitsolvestheproblemoftransmitingthe9thbitin
modes2and3.Itissettotransmitalogic1inthe9thbit.
RB8Receiverbit8orthe9thbitreceivedinmodes2and3.Clearedbyhardwareif9thbitreceivedisalogic0.Set
byhardwareif9thbitreceivedisalogic1.
TITransmitInterruptflagisautomaticallysetatthemomentthelastbitofonebyteissent.It'sasignaltothe
processorthatthelineisavailableforanewbytetransmite.Itmustbeclearedfromwithinthesoftware.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

15/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

RIReceiveInterruptflagisautomaticallysetupononebytereceive.Itsignalsthatbyteisreceivedandshouldbe
readquicklypriortobeingreplacedbyanewdata.Thisbitisalsoclearedfromwithinthesoftware.
Asseen,serialportmodeisselectedbycombiningtheSM0andSM2bits:
SM0

SM1

MO DE

DESCRIPT IO N

BAUDRATE

8bitShiftRegister

1/12thequartzfrequency

8bitUART

Determinedbythetimer1

9bitUART

1/32thequartzfrequency(1/64thequartzfrequency)

9bitUART

Determinedbythetimer1

Inmode0,serialdataaretransmittedandreceivedthroughtheRXDpin,whiletheTXDpinoutputclocks.Theboutrateisfixedat1/12the
oscillatorfrequency.Ontransmit,theleastsignificantbit(LSBbit)issent/receivedfirst.
TRANSMITDatatransmitisinitiatedbywritingdatatotheSBUFregister.Infact,thisprocessstartsafteranyinstructionbeingperformed
uponthisregister.Whenall8bitshavebeensent,theTIbitoftheSCONregisterisautomaticallyset.

RECEIVEDatareceivethroughtheRXDpinstartsuponthetwofollowingconditionsaremet:bitREN=1andRI=0(bothofthemarestored
intheSCONregister).Whenall8bitshavebeenreceived,theRIbitoftheSCONregisterisautomaticallysetindicatingthatonebyte
receiveiscomplete.

SincetherearenoSTARTandSTOPbitsoranyotherbitexceptdatasentfromtheSBUFregisterinthepulsesequence,thismodeis
mainlyusedwhenthedistancebetweendevicesisshort,noiseisminimizedandoperatingspeedisofimportance.AtypicalexampleisI/O
portexpansionbyaddingacheapIC(shiftregisters74HC595,74HC597andsimilar).

Mode1
Inmode1,10bitsaretransmittedthroughtheTXDpinorreceivedthroughtheRXDpininthefollowingmanner:aSTARTbit(always0),8
databits(LSBfirst)andaSTOPbit(always1).TheSTARTbitisonlyusedtoinitiatedatareceive,whiletheSTOPbitisautomaticallywritten
totheRB8bitoftheSCONregister.
TRANSMITDatatransmitisinitiatedbywritingdatatotheSBUFregister.EndofdatatransmissionisindicatedbysettingtheTIbitofthe
SCONregister.

RECEIVETheSTARTbit(logiczero(0))ontheRXDpininitiatesdatareceive.Thefollowingtwoconditionsmustbemet:bitREN=1and
bitRI=0.BothofthemarestoredintheSCONregister.TheRIbitisautomaticallysetupondatareceptioniscomplete.

TheBaudrateinthismodeisdeterminedbythetimer1overflow.

Mode2
Inmode2,11bitsaretransmittedthroughtheTXDpinorreceivedthroughtheRXDpin:aSTARTbit(always0),8databits(LSBfirst),a
programmable9thdatabitandaSTOPbit(always1).Ontransmit,the9thdatabitisactuallytheTB8bitoftheSCONregister.Thisbit
usuallyhasafunctionofparitybit.Onreceive,the9thdatabitgoesintotheRB8bitofthesameregister(SCON).Thebaudrateiseither1/32
or1/64theoscillatorfrequency.
TRANSMITDatatransmitisinitiatedbywritingdatatotheSBUFregister.EndofdatatransmissionisindicatedbysettingtheTIbitofthe
SCONregister.

RECEIVETheSTARTbit(logiczero(0))ontheRXDpininitiatesdatareceive.Thefollowingtwoconditionsmustbemet:bitREN=1and
bitRI=0.BothofthemarestoredintheSCONregister.TheRIbitisautomaticallysetupondatareceptioniscomplete.

Mode3
Mode3isthesameasMode2inallrespectsexceptthebaudrate.ThebaudrateinMode3isvariable.

TheparitybitisthePbitofthePSWregister.Thesimplestwaytocheckcorrectnessofthereceivedbyteistoaddaparitybittoit.Simply,
beforeinitiatingdatatransmit,thebytetotransmitisstoredintheaccumulatorandthePbitgoesintotheTB8bitinordertobeapartof
themessage.Theprocedureisoppositeonreceive,receivedbyteisstoredintheaccumulatorandthePbitiscomparedwiththeRB8
bit.IftheyarethesameeverythingisOK!

BaudRate
BaudRateisanumberofsent/receivedbitspersecond.IncasetheUARTisused,baudratedependson:selectedmode,oscillator
frequencyandinsomecasesonthestateoftheSMODbitoftheSCONregister.Allthenecessaryformulasarespecifiedinthetable:
BAUDRATE

BIT SMO D

Mode0

Fosc./12

Mode1

1Fosc.
1612(256TH1)

BitSMOD

Mode2

Fosc./32
Fosc./64

1
0

Mode3

1Fosc.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

16/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika
1612(256TH1)

Timer1asaclockgenerator
Timer1isusuallyusedasaclockgeneratorasitenablesvariousbaudratestobeeasilyset.Thewholeprocedureissimpleandisas
follows:

First,enableTimer1overflowinterrupt.
ConfigureTimerT1tooperateinautoreloadmode.
Dependingonneeds,selectoneofthestandardvaluesfromthetableandwriteittotheTH1register.That'sall.
F O SC.( MHZ )

BAUDRATE
11.0592

12

14.7456

150

40h

30h

00h

300

A0h

98h

600

D0h

1200
2400

BIT SMO D
16

20

80h

75h

52h

CCh

C0h

BBh

A9h

E8h

E6h

E0h

DEh

D5h

F4h

F3h

F0h

EFh

EAh

F3h

EFh

EFh

4800
4800

FAh

F8h

9600

FDh

FCh

9600
19200

1
F5h

0
F5h

FDh

FCh

38400

FEh

76800

FFh

MultiprocessorCommunication
Asyoumayknow,additional9thdatabitisapartofmessageinmode2and3.Itcanbeusedforcheckingdataviaparitybit.Anotheruseful
applicationofthisbitisincommunicationbetweentwoormoremicrocontrollers,i.e.multiprocessorcommunication.Thisfeatureisenabled
bysettingtheSM2bitoftheSCONregister.Asaresult,afterreceivingtheSTOPbit,indicatingendofthemessage,theserialportinterrupt
willbegeneratedonlyifthebitRB8=1(the9thbit).
Thisishowitlookslikeinpractice:
Supposethereareseveralmicrocontrollerssharingthesameinterface.Eachofthemhasitsownaddress.Anaddressbytediffersfroma
databytebecauseithasthe9thbitset(1),whilethisbitiscleared(0)inadatabyte.WhenthemicrocontrollerA(master)wantstotransmita
blockofdatatooneofseveralslaves,itfirstsendsoutanaddressbytewhichidentifiesthetargetslave.Anaddressbytewillgeneratean
interruptinallslavessothattheycanexaminethereceivedbyteandcheckwhetheritmatchestheiraddress.

Ofcourse,onlyoneofthemwillmatchtheaddressandimmediatelycleartheSM2bitoftheSCONregisterandpreparetoreceivethedata
bytetocome.OtherslavesnotbeingaddressedleavetheirSM2bitsetignoringthecomingdatabytes.

2.88051MicrocontrollerInterrupts
Therearefiveinterruptsourcesforthe8051,whichmeansthattheycanrecognize5differenteventsthatcaninterruptregularprogram
execution.EachinterruptcanbeenabledordisabledbysettingbitsoftheIEregister.Likewise,thewholeinterruptsystemcanbedisabled
byclearingtheEAbitofthesameregister.Refertofigurebelow.
Now,itisnecessarytoexplainafewdetailsreferringtoexternalinterruptsINT0andINT1.IftheIT0andIT1bitsoftheTCONregisterare
set,aninterruptwillbegeneratedonhightolowtransition,i.e.onthefallingpulseedge(onlyinthatmoment).Ifthesebitsarecleared,an
interruptwillbecontinuouslyexecutedasfarasthepinsareheldlow.

IE Register (Interrupt Enable)


EAglobalinterruptenable/disable:
0disablesallinterruptrequests.
1enablesallindividualinterruptrequests.

ESenablesordisablesserialinterrupt:
0UARTsystemcannotgenerateaninterrupt.
1UARTsystemenablesaninterrupt.

ET1bitenablesordisablesTimer1interrupt:
0Timer1cannotgenerateaninterrupt.
1Timer1enablesaninterrupt.

EX1bitenablesordisablesexternal1interrupt:
0changeofthepinINT0logicstatecannotgenerateaninterrupt.
1enablesanexternalinterruptonthepinINT0statechange.

ET0bitenablesordisablestimer0interrupt:
0Timer0cannotgenerateaninterrupt.
1enablestimer0interrupt.

EX0bitenablesordisablesexternal0interrupt:
0changeoftheINT1pinlogicstatecannotgenerateaninterrupt.
1enablesanexternalinterruptonthepinINT1statechange.

InterruptPriorities
Itisnotpossibletoforseenwhenaninterruptrequestwillarrive.Ifseveralinterruptsareenabled,itmayhappenthatwhileoneofthemisin
progress,anotheroneisrequested.Inorderthatthemicrocontrollerknowswhethertocontinueoperationormeetanewinterruptrequest,
thereisaprioritylistinstructingitwhattodo.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

17/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

Theprioritylistoffers3levelsofinterruptpriority:

1. Reset!Theapsolutemaster.Whenaresetrequestarrives,everythingisstoppedandthemicrocontrollerrestarts.
2. Interruptpriority1canbedisabledbyResetonly.
3. Interruptpriority0canbedisabledbybothResetandinterruptpriority1.
TheIPRegister(InterruptPriorityRegister)specifieswhichoneofexistinginterruptsourceshavehigherandwhichonehaslowerpriority.
Interruptpriorityisusuallyspecifiedatthebeginningoftheprogram.Accordingtothat,thereareseveralpossibilities:

Ifaninterruptofhigherpriorityarriveswhileaninterruptisinprogress,itwillbeimmediatelystoppedandthehigher
priorityinterruptwillbeexecutedfirst.
Iftwointerruptrequests,atdifferentprioritylevels,arriveatthesametimethenthehigherpriorityinterruptisserviced
first.
Ifthebothinterruptrequests,atthesameprioritylevel,occuroneafteranother,theonewhichcamelaterhastowait
untilroutinebeinginprogressends.
Iftwointerruptrequestsofequalpriorityarriveatthesametimethentheinterrupttobeservicedisselectedaccording
tothefollowingprioritylist:
1. ExternalinterruptINT0
2. Timer0interrupt
3. ExternalInterruptINT1
4. Timer1interrupt
5. SerialCommunicationInterrupt
IPRegister(InterruptPriority)
TheIPregisterbitsspecifytheprioritylevelofeachinterrupt(highorlowpriority).

PSSerialPortInterruptprioritybit
Priority0
Priority1

PT1Timer1interruptpriority
Priority0
Priority1

PX1ExternalInterruptINT1priority
Priority0
Priority1

PT0Timer0InterruptPriority
Priority0
Priority1

PX0ExternalInterruptINT0Priority
Priority0
Priority1

HandlingInterrupt
Whenaninterruptrequestarrivesthefollowingoccurs:

1. Instructioninprogressisended.
2. Theaddressofthenextinstructiontoexecuteispushedonthestack.
3. Dependingonwhichinterruptisrequested,oneof5vectors(addresses)iswrittentotheprogramcounterin
accordancetothetablebelow:
4.
INT ERRUPT SO URCE

VECT O R( ADDRESS)

IE0

3h

TF0

Bh

TF1

1Bh

RI,TI

23h
Alladdressesareinhexadecimalformat

Theseaddressesstoreappropriatesubroutinesprocessinginterrupts.Insteadofthem,thereareusuallyjump
instructionsspecifyinglocationsonwhichthesesubroutinesreside.
5. Whenaninterruptroutineisexecuted,theaddressofthenextinstructiontoexecuteispopedfromthestackto
theprogramcounterandinterruptedprogramresumesoperationfromwhereitleftoff.

Fromthemomentaninterruptisenabled,themicrocontrollerisonalertallthetime.Whenaninterruptrequestarrives,theprogram
executionisstopped,electronicsrecognizesthesourceandtheprogramjumpstotheappropriateaddress(seethetableabove).This
addressusuallystoresajumpinstructionspecifyingthestartofappropriatesubroutine.Uponitsexecution,theprogramresumes
operationfromwhereitleftoff.

Reset
ResetoccurswhentheRSpinissuppliedwithapositivepulseindurationofatleast2machinecycles(24clockcyclesofcrystaloscillator).
Afterthat,themicrocontrollergeneratesaninternalresetsignalwhichclearsallSFRs,exceptSBUFregisters,StackPointerandports(the

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

18/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

stateofthefirsttwoportsisnotdefined,whileFFvalueiswrittentotheportsconfiguringalltheirpinsasinputs).Dependingonsurrounding
andpurposeofdevice,theRSpinisusuallyconnectedtoapoweronresetpushbuttonorcircuitortobothofthem.Figurebelowillustrates
oneofthesimplestcircuitprovidingsafepoweronreset.
Basically,everythingisverysimple:afterturningthepoweron,electricalcapacitorisbeingchargedforseveralmillisecondsthrogha
resistorconnectedtotheground.Thepinisdrivenhighduringthisprocess.Whenthecapacitorischarged,powersupplyvoltageisalready
stableandthepinremainsconnectedtotheground,thusprovidingnormaloperationofthemicrocontroller.Pressingtheresetbutton
causesthecapacitortobetemporarilydischargedandthemicrocontrollerisreset.Whenreleased,thewholeprocessisrepeated

Throughtheprogramstepbystep...
Microcontrollersnormallyoperateatveryhighspeed.Theuseof12Mhzquartzcrystalenables1.000.000instructionstobeexecutedper
second.Basically,thereisnoneedforhigheroperatingrate.Incaseitisneeded,itiseasytobuiltinacrystalforhighfrequency.The
problemariseswhenitisnecessarytoslowdowntheoperationofthemicrocontroller.Forexampleduringtestinginrealenvironmentwhen
itisnecessarytoexecuteseveralinstructionsstepbystepinordertocheckI/Opins'logicstate.
Interruptsystemofthe8051microcontrollerpracticallystopsoperationofthemicrocontrollerandenablesinstructionstobeexecutedone
afteranotherbypressingthebutton.Twointerruptfeaturesenablethat:

Interruptrequestisignoredifaninterruptofthesameprioritylevelisinprogress.
Uponinterruptroutineexecution,anewinterruptisnotexecuteduntilatleastoneinstructionfromthemainprogramis
executed.
Inordertousethisinpractice,thefollowingstepsshouldbedone:

1. Externalinterruptsensitivetothesignallevelshouldbeenabled(forexampleINT0).
2. Threefollowinginstructionsshouldbeinsertedintotheprogram(atthe03hex.address):

Whatisgoingon?AssoonastheP3.2piniscleared(forexample,bypressingthebutton),themicrocontrollerwillstopprogramexecution
andjumptothe03hexaddresswillbeexecuted.Thisaddressstoresashortinterruptroutineconsistingof3instructions.
Thefirstinstructionisexecuteduntilthepushbuttonisrealised(logicone(1)ontheP3.2pin).Thesecondinstructionisexecuteduntilthe
pushbuttonispressedagain.Immediatelyafterthat,theRETIinstructionisexecutedandtheprocessorresumesoperationofthemain
program.Uponexecutionofanyprograminstruction,theinterruptINT0isgeneratedandthewholeprocedureisrepeated(pushbuttonis
stillpressed).Inotherwords,onebuttonpressoneinstruction.

2.98051MicrocontrollerPowerConsumptionControl
Generallyspeaking,themicrocontrollerisinactiveforthemostpartandjustwaitsforsomeexternalsignalinordertotakesitsroleina
show.Thiscancausesomeproblemsincasebatteriesareusedforpowersupply.Inextremecases,theonlysolutionistosetthewhole
electronicsinsleepmodeinordertominimizeconsumption.AtypicalexampleisaTVremotecontroller:itcanbeoutofuseformonthsbut
whenusedagainittakeslessthanasecondtosendacommandtoTVreceiver.TheAT89S53usesapproximately25mAforregular
operation,whichdoesn'tmakeitapoversavingmicrocontroller.Anyway,itdoesnthavetobealwayslikethat,itcaneasilyswitchthe
operatingmodeinordertoreduceitstotalconsumptiontoapproximately40uA.Actually,therearetwopowersavingmodesofoperation:
IdleandPowerDown.

Idlemode
UpontheIDLbitofthePCONregisterisset,themicrocontrollerturnsoffthegreatestpowerconsumerCPUunitwhileperipheralunitssuch
asserialport,timersandinterruptsystemcontinueoperatingnormallyconsuming6.5mA.InIdlemode,thestateofallregistersandI/Oports
remainsunchanged.
InordertoexittheIdlemodeandmakethemicrocontrolleroperatenormally,itisnecessarytoenableandexecuteanyinterruptorreset.It
willcausetheIDLbittobeautomaticallyclearedandtheprogramresumesoperationfrominstructionhavingsettheIDLbit.Itis
recommendedthatfirstthreeinstructionstoexecutenowareNOPinstructions.Theydon'tperformanyoperationbutprovidesometimefor
themicrocontrollertostabilizeandpreventsundesiredchangesontheI/Oports.

PowerDownmode
BysettingthePDbitofthePCONregisterfromwithintheprogram,themicrocontrollerissettoPowerdownmode,thusturningoffits
internaloscillatorandreducespowerconsumptionenormously.Themicrocontrollercanoperateusingonly2Vpowersupplyinpower
downmode,whileatotalpowerconsumptionislessthan40uA.Theonlywaytogetthemicrocontrollerbacktonormalmodeisbyreset.
WhilethemicrocontrollerisinPowerDownmode,thestateofallSFRregistersandI/Oportsremainsunchanged.Bysettingitbackintothe
normalmode,thecontentsoftheSFRregisterislost,butthecontentofinternalRAMissaved.Resetsignalmustbelongenough,
approximately10mS,toenablestableoperationofthequartzoscillator.

PCONregister

ThepurposeoftheRegisterPCONbitsis:

SMODBaudrateistwiceasmuchhigherbysettingthisbit.
GF1Generalpurposebit(availableforuse).
GF1Generalpurposebit(availableforuse).
GF0Generalpurposebit(availableforuse).
PDBysettingthisbitthemicrocontrollerentersthePowerDownmode.
IDLBysettingthisbitthemicrocontrollerenterstheIdlemode.
previouschapter|tableofcontents|nextchapter

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

19/20

28/06/2015

Chapter2:8051MicrocontrollerArchitectureArchitectureandProgrammingof8051MCUmikroElektronika

MikroElektronika Embedded Solutions


PICSolution

dsPICSolution

STM32Solution

8051Solution

AdditionalSoftware

Storage

PICDev.Boards

dsPICDev.Boards

STM32Dev.Boards

8051Dev.Boards

VisualTFT

RealTimeClock

PICCompilers

dsPICCompilers

STM32Compilers

8051Compilers

VisualGLCD

Display

PICProgrammers

dsPICProgrammers

STM32Programmers

8051Programmers

PackageManager

Measurement

PICKits

dsPICKits

STM32Kits

8051Books

GLCDFontCreator

Audio&Voice

PICBooks

dsPICBooks

8051Kits

TimerCalculator

PowerSupply

PIC32Solution

AVRSolution

TivaCSeriesSolution

FT90xSolution

TivaCDev.Boards

Addonboards

PIC32Dev.Boards

AVRDev.Boards

TivaCCompilers

FT90xDev.Boards

ClickBoards

PIC32Compilers

AVRCompilers

TivaCProgrammers

FT90xCompilers

ClickPacks

PIC32Programmers

AVRProgrammers

TivaCKits

FT90xProgrammers

mikromediashields

PIC32Kits

AVRKits

FT90xKits

Communication

Support

Forum

mikroBUS

Letsmake

Press

Legal

Archive

AboutUs

GPS
GSM/GPRS

Customization

Copyright19982015.MikroElektronika.Allrightsreserved.Alltradeand/orservicesmarksmentionedarethepropertyoftheirrespectiveowners.

http://www.mikroe.com/chapters/view/65/chapter28051microcontrollerarchitecture/

20/20

Vous aimerez peut-être aussi