TableofContentsCHAPTERONE
WHYMICROPROCESSORS?
CHAPTERTWO
BINARY
CHAPTERTHREE
VOLTAGEANDCURRENT
CHAPTERFOUR
THEFAUCETANALOGY
CHAPTERFIVE
SWITCHES
CHAPTERSIX
TRANSISTORS
CHAPTERSEVEN
LATCHES
CHAPTEREIGHT
AMICROPROCESSORINACTION
CHAPTERNINE
BINARYNUMBERS
CHAPTERTEN
THEADDRESSBUSANDDECODER
CHAPTERELEVEN
THECONTROLBUS
CHAPTERTWELVE
THESYSTEMCLOCK
CHAPTERTHIRTEEN
CAPACITORS
CHAPTERFOURTEEN
THECRYSTALCLOCK
CHAPTERFIFTEEN
THEFLIP-FLOP
CHAPTERSIXTEEN
COUNTERS
CHAPTERSEVENTEEN
SEQUENCERS
CHAPTEREIGHTEEN
INSTRUCTIONDECODING
CHAPTERNINETEEN
THEBINARYADDER
CHAPTERTWENTY
THESTACKANDSTACKPOINTER
CHAPTERTWENTY-ONE
INTERRUPTS
APPENDIXA
CODE
MachineLanguage(AppendixA-1)
AssemblyLanguage(AppendixA-2)
High-levelLanguages(AppendixA-3)
Small-systemCodevs.ApplicationCode(AppendixA-4)
WriteOnce,RunAnywhere(AppendixA-5)
APPENDIXB
D/ACONVERSION
APPENDIXC
A/DCONVERSION
CHAPTERONEWHYMICROPROCESSORS?
Arguablythemostimportantinventionofthemodernworldisthemicroprocessor.Armclaimstohavesold30billionoftheirmicroprocessors.Microchipsells1billionoftheirmicroprocessorsperyear.Yes,that’s“billion”witha“b.”Whereintheworldareallthesethings?Thenumberstellustheymustbeinmanymoreplacesthanjustourcomputers.
Microprocessorsrunsmartphones,networks,websites,cars,laptops,appliances,factories,etc.Weareoftenunawarethat,attheheartofdevicesweuseeveryday,ahidden,or“embedded,”microprocessorcontrolsthedevice.Itmightbeinatoyorinacoffeemaker.Yourcarmayhave12,or50,or100microprocessors.Forexample,onemaybededicatedtocollectingtheairpressureineachtire.Andyet,eventhoughweuseallthesedevices,wedon’tunderstandhowthey
work.Theyseemlikemagic.That’sbecausewedon’tunderstandhowmicroprocessorswork.Wedon’tunderstanddigitalelectronics.It’stimetostopbeingignorant.Thisbookpurportstolifttheveilofsecrecy,the
cloudsofignorancehidingthiswonderfuldevice.Ihaveeveryconfidencethat,whenyoulearnhowthesemicroprocessorswork,youwillfindthemtobeevenmorewonderfulthanbefore.Whenyoulearnthesecretofhowamagictrickworks,itoftenbecomesmundane,asin,“isthatallthereistoit?”Whenyoulearnhowmicroprocessorswork,Ibelieveyouwillbeevenmoreinaweofthem.Thefirstconfusionweneedtoaddressisthedistinctionbetweentheterms
“microprocessor”and“computer.”Whenwetalkaboutacomputer,weusuallymeanadevicedesignedinsuchawaythatitcandomultipletasksforus.Wecanchangethattaskbysimplygivingthedeviceanewsetofinstructions:anewprogram.Ourearlycomputerswerelargedevices.Theywerebuiltfromvacuumtubes
andfrommanydiscretecomponents.Thesewerebuiltintosub-circuits,andthesub-circuitsintocircuits,andthecircuitsintocircuitboards,andthemanycircuitboardsworkedtogethertofunctionasthecomputerdescribedinthepreviousparagraph.Inthelate1940’stinytransistorswereinvented,asreplacementsforvacuum
tubes.Transistorswerefirstmadeofgermanium,thenlaterofsilicon.Then,engineersthought,whynotcreatemorethanonetransistoronawaferofsilicon?Whynotconnectthetransistorsandothercomponentsonthewaferofsilicon?Around1960,theysucceeded,callingthisdevicean“integratedcircuit,”
becauseanentirefunctioningelectroniccircuitcouldbefabricated,andintegratedintoonesmalldevice.Calleda“chip”or“IC,”anintegratedcircuitwasapieceofsiliconenclosedinplastic,withlegsor“pins”thatconnectedtheinternalcircuitrytotheoutsideworld.Whatyoucouldholdinthecupofyourhandorbalanceonthetipofyourfingerreplacedentirecircuitboardsfullofmanycomponents.
Atthetime,manypeopleknewwhatwascomingnext:puttingthe“brains”ofacomputer,thecentralprocessingunit(CPU),intooneintegratedcircuit.SteveWozniakcouldn’twait.Why,ifhecouldgetoneoftheseCPU’s,hecouldaddsomememoryandinput/outputdevicestoit.Hecouldbuildahomecomputeraroundit,andcallittheAppleComputer.TheycalledthisnewCPUonachipa“microprocessor.”CompanieslikeIntel
andMotorolamadethemicroprocessorsthatbroughtthisdreamtofruition.So,amicroprocessoristhebrains,theessence,theCPU(centralprocessingunit)ofacomputer,madereallysmall.Amicroprocessoristheheart,thecomputingpartofacomputer.Ihaddifficultychoosinganameforthisbook.Wasthisgoingtobeabook
abouthowcomputerswork,orabouthowmicroprocessorswork?Irealizeditshouldbeabouthowmicroprocessorswork,becausecomputersarenowasubsetofallmicroprocessor-baseddevices.Here’swhywehavemoremicroprocessorsthancomputers.Historically,
computerscamefirst.Computers—digitalelectronicmultipurposedevicesthatcanrundifferentprograms—werelargedevices.Next,engineersputtheprocessingpartofthecomputerintoasmallintegratedcircuit,andcalleditthemicroprocessor.Wenowcouldhaveapersonal,homecomputer.Atthispointinhistory—andfromhereon—weallknowwhatwemeanwhenwesaytheword,computer.Butnext,somethingstrangehappened.Engineersstartedusing—andstilluse
—thissamemicroprocessorforotherdesignsthatdonotfitourdefinitionofacomputer.Theyuseitindesignsthatdon’tevenrequireamicroprocessor:thatcouldbedesignedusingsolelyanalogordigitalelectronicscomponentsandtechniques.Thefuelinjectionsystemsofcarsexistedforyearsusingmechanicaltiming,beforeanyoneinventedmicroprocessors.Now,fuelinjectionsystemsaremicroprocessor-based.Newgenerationsofmicroprocessorsweredesignedthatweremorethanjust
theCPUpartofthecomputer.Theyincludedthememoryandinput/outputpartsofacomputer,inadditiontotheCPU.Now,thesenewermicroprocessorsweremorelikea“computeronachip”thana“CPUonachip.”Sometimes,wecallthese“computersonachip”microcontrollers,whilecalling“CPU’sonachip”microprocessors.Ifyoutoldanengineerfromthe1950’sthatonedayaclockoratoasteroven
designwouldbeimplementedusinga“computeronachip,”theywouldhavelaughed.Tothem,itwouldhavebeenlikeusingasledgehammertopoundatackinthewall.So,thiscreatessomeconfusioninterminology.Wehavegottentothepoint
whereengineersareusinga“computer”—amicrocontroller—tocreatethingsthatarenotcomputers!Weknowwhatacomputeris,andweknowwhataclockis,andweknowthataclockisnotacomputer.Andyet,wefindoutthat,today,aclockhasa“computer”init.Wefindthateverydaythingsthatarenotcomputershavelittlecomputers-likedevices—microcontrollers—controllingthem.
Inshort,computersbecamemicroprocessors,thenmicroprocessorsbecame—almosteverything.Ithinkthebestwaytoavoidconfusionistodefineacomputerasadigitalelectronicmultipurposedevicethatcanrundifferentprograms.Single-purposedevicesrunningoneprogramwecancallmicroprocessor-basedsystems.Remember,though,thatacomputer,too,isamicroprocessor-basedsystem.Itjustrunsmoreprograms,moretasks.Doyouseenowwhyitissoimportanttounderstandmicroprocessors?Theyareeverywhere.Whydidengineersstartusingmicroprocessorstodesignthingsthataren’t
computers?Itjustbecameeasier.Ifyouspentyearslearningtoplaytheguitarwell,doyoureallywanttolearntoplaythepianoinordertoplayyoursong?Ifyouknowhowtodesignwithmicroprocessorswell,doyoureallywanttodesignyournextprojectwithauniqueanalogordigitaldesign?Aunique,non-microprocessordesignmightbemoreefficient,andthemicroprocessormightbeoverkill.Still,youknowhowtodesignwiththemicroprocessorquickly,itflexiblyadaptstoalmostanyproject,itefficientlyreplacesalotofcircuitrywithsoftware,componentsareavailableandcompatiblewitheachother,andthecostandpowerconsumptionhasfallensomuchthatoverkillisnolongeranissue.Thisbookisaimedfortheaverage,non-technical,person.However,Ihave
foundthatevencomputerprogrammersdonotreallyknowhowthedevicestheywritetheirprogramsfor,reallywork.Infact,theydon’tneedtoknow.Youmayhaveheardoftheterm,“higherlevellanguages,”inreferencetoprogramminglanguageslikeC++andJava.Thistermactuallymeansthatthelanguageisastepabovemachine’slanguage,sothatpeoplecanprogramthemachinewithouthavingtounderstandthemachine.Themicroprocessoristhemachine.So,thisbookisfortheprogrammer,too.And,it’sfortheITpeople,andthe
networkingpeople.Ihavefoundthatthepeoplewiththedeepestunderstandingofprogramming,IT,andnetworkingarepeoplewhocomefromabackgroundofelectronics.Theyseethebigpicture,fromthegroundup.Themicroprocessoranddigitalelectronicsaretheground,thefoundation.
CHAPTERTWOBINARY
Lookattheword,“microprocessor.”“Micro,”ofcourse,meanssmall,really
small,asinmicroscopic.Whatisbeing“processed,”though?Theansweris:information,asindataornumbers.Theinformationisrepresentedinbinaryformat.Iamsureyouhaveheardthateverythinginmodern,digitalcomputersisin
binary:onesandzeroes.Youshouldwonder,whataretheseonesandzeroes?Aretheyphysicalthings?Whyonesandzeroes?Let’sforgetaboutmicroprocessorsforamoment.“Binary”meansasystemof
twostates.Atwo-statesystemisabsolutelythesimplestinformationsystemimaginable.Aone-statesystemcontainsnoinformation;itisundifferentiated.Atwo-statesystemseems,atfirstglance,barelybetterthanaone-state
system.But,lookingdeeper,weseethevarietyofinformationwecanrepresentorencodeinatwostatesystem.Thetwostatescanstandfor:oneorzero,trueorfalse,highorlow,oddoreven,goorstop,leftorright,lightordark,blackorwhite,goodorevil,yinoryang,andsoon.Wecancontrolasimplemachinelikeamotorwithabinary,two-statesystem:motoronormotoroff.Lookingevendeeper,thesecondthingweseeisthatthissystemgrows
enormouslyinitscapabilitywhenweexpandit.Intheaboveparagraph,Idescribedasimpletwo-statesystemofoneitem.Wecallthisoneitema“bit.”Onebitcanbeintwostates.Definingtheinformationintermsofblackandwhite,aonebitsystemcanholdtwostateconditions:blackorwhite.However,ifweexpandthesystembygroupingtwoofthesebitstogether,we
doubletheamountofinformationoursystemholds.Atwo-bitsystemholdsfourstateconditions:black-black,orblack-white,orwhite-black,orwhite-white.Ifweexpandagainbygroupingthreeofthesebitstogether,wequadruplethe
amountofinformationouronebitsystemholds.Athree-bitsystemholdseightstateconditions:black-black-black,orblack-black-white,orblack-white-black,orblack-white-white,orwhite-black-black,orwhite-black-white,orwhite-white-black,orwhite-white-white.Ifyouwanttocalculatethenumberofuniquepiecesofinformationthatabinary
systemisabletorepresent,countthenumberofbitsyouhavegroupedtogether,thentake2tothatpower.Forexample,youprobablyhaveheardoftheterm,“byte.”Abyteisagroupingtogetherofeightbinarybits.Ifyoutake2tothe8thpower,writtenas28,youget2x2x2x2x2x2x2x2whichequals256.Younowhaveasystemthatcanrepresent256uniqueinformationalstates.Anyoneofthesestatesisdifferentfromtheother255states.Black-black-black-black-black-black-black-blackisdifferentfromblack-white-black-white-black-white-black-white.Thegrowthinpowerovertheyearsofpersonalcomputersisreflectedinthe
constantgrowthofthenumberofbitsgroupedtogether.TheearliestIntel
microprocessorswere4-bitsystems,then8-bit,then16-bit,then32-bit,then64-bit.Onegroupof64bitscanuniquelyrepresent264or18,446,744,073,709,551,616informationalstates.Oneofthesestatesmightlooklike:black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black-black.So,abinarysystemstartsoutbeingridiculouslysimple:a1-bitsystemcapable
ofonly2states.Yet,ifweclumptogetherjust64ofthesebits,wenowhavearidiculouslypowerfulgroupcapableof18,446,744,073,709,551,616differentstates!Onecanimplementaone-bit,two-statebinarysysteminmanyways.For
example,acoinisaone-bit,two-statebinarysystem.Thetwostatesare:headsortails.Anotherisalight:onoroff.Amatchislitornotlit.Atrue-falsequestionisbinary.Apianokeyispressedornot.Thequestionbecomes,whatisthebestwaytoimplementaone-bit,two-state
binarysystem?Inthehistoryofcomputers,severalimplementationshavebeenused.Inearlymainframecomputers,individualmemorybitswereringmagnets.Eachonecouldbemagnetizedeitherclockwiseorcounter-clockwise(binary)byforcingcurrentforwardsorbackwardsthroughawirecoiledaroundthering.Harddrivesarealsomagneticstoragemedia.Theirdisksaremadeof
ferromagneticmaterial.Apredefinedspotonadiskactsasbinarybit.Thespotismagnetizedintheforward(northpole-to-south)orreverse(southpole-to-north)directionbyanelectromagnetmovedbyamotor.Thissamespotcanbereadbyawirecoilasthespotmovespast,inducingeitherforwardorreversecurrentflow.CompactdiscsandDVDdiscsuselighttoimplementaone-bit,two-statebinary
system.Apredeterminedspotonthediscactsasabinarybit.Alaserlightisusedtochangeornotchangethereflectivepropertiesofthespot.Thelaserisalsoinvolvedinretrievingthebinarystateofthatspot.Whenthereadinglaserlightisaimedatthespot,itreflectsdifferently,dependingonwhetherthewritinglaserhadpreviouslymodifieditornot.So,whatisthebestwaytoimplementaone-bit,two-statebinarysystem?The
answerisasurprisingone.Theansweris,“PRESSURE.”Ofcourse,wearetalkingaboutaspecialkindofpressure.Let’spauseforamomentandthinkofhowwecouldcommunicateusing
pressure.Hereisathoughtexperiment.Ifyouweretolieonyourstomachandcloseyoureyes,howcouldpeoplecommunicatewithyouinbinary,usingonlypressure?Hereishowtheycoulddoit.Designatedifferentspotsonyourbody,saythe
backofeachknee,andthebackofeachelbow,aspressurepoints,actingasbinarybits.Then,fourpeoplecouldcommunicatewithyoubyeitherpressingornotpressingthosefourdesignatedspots.24or16differentmessagescouldbe
communicatedtoyouinthisway.Forexample,onedistinctmessagecouldbe:leftelbowpressed,rightelbownotpressed,rightkneepressed,leftkneenotpressed.Whatwouldthese16messagesstandfor?Whateveryouchoose.Inthe
morningtheycouldstandforwhatbreakfastwillbeserved.Intheeveningtheycouldstandforhowmanyrunsthehomebaseballteamscored.Binarysystems,includingcomputers,usegroupingofbitsatdifferenttimes,indifferentsubsystems,fordifferentpurposes.Ofcoursethisisnotthekindofpressurethatmicroprocessorsuse.Let’sgeta
littleclosertothatbyimaginingabinarysystemencodedbysomethingwearefamiliarwith:waterpressure.Waterpressurecomesfromadistantwaterpump,withapropellerinsidethatpushesonthewater.Thepressurealsomaycomefromgravity,viaawatertowerorreservoirhigherthanyourhouse.Let’slookathowawaterfaucetworks.Whenthecontrolvalveisturnedoff,nowaterflows,butthereispressureatthe
faucet.Thewaterispressingontheclosedvalve.Whenthecontrolvalveisturnedon,waterflows,butthereisnopressureatthe
faucet.Thevalveisoutoftheway,sothereisnowaterpressingonthevalve.So,inourone-bitbinarysystem,thewatervalve,wehavetwostates:water
flowing,orwaternotflowing.But,wecouldalsolookatitastwostates:pressureofforpressureon.Infact,thestatesareinvertedoroppositefromeachother:flowisoffwhenvalvepressureison,andflowisonwhenvalvepressureisoff.Figure2-1,below,summarizesthisconcept.
FIGURE2-1Inourmicroprocessor-basedsystem—infactinalldigitalelectronics—wewill
findthatthemeaningisencodedinthepressure,ratherthanintheflow.But,thatisgettingaheadofourselves.Imaginenowafour-bitbinarycommunicationsystembasedonwaterpressure.
Weputfourwaterfaucetsinarow.Anyonefaucetcanbeindependentlyturned
offoron.Justaswiththepressure-on-the-knees-and-elbowssystem,wecanencode24or16differentmessages.Let’slooknowatasubtle,butimportantdifference.Namethevalves,fromleft
toright,A,B,C,andD.TurnvalvesAandCon,sothatwaterflows.TurnvalvesBandDoff,sonowaterflows.IfwechoosetodefineeachbitasTrueorFalse,weinstinctivelywouldassignwaterflowingasTrue,andwaternotflowingasFalse.So,intheabovescenario,wewoulddescribeA-B-C-DasTrue-False-True-False,asinFigure2-2,part(a),below:
FIGURE2-2Thiswouldintuitivelybeourchoice,becausewecanseewaterflowing.Ifwe
wantedto,wecouldhavedefinedoursystemintermsofvalvepressure,insteadofwaterflow.Thatwouldbealessintuitivechoice,becausewecan’tseevalvepressure.But,ifwehadchosentodefinevalvepressureonasTrue,andvalvepressureoffasFalse,theninourabovescenariowewoulddescribeA-B-C-DasFalse-True-False-True,insteadofTrue-False-True-False.Figure2-2,part(b)displaysthisdifferentwayofdefiningthesamesystem,inthesamestate.Again,inourmicroprocessor-basedsystems,wewillfindthatthemeaningis
encodedanddefinedbythepressure.Inthemicroprocessorcase,theflowisnotthemoreobviouschoice,becausewecan’tseetheflow.Ontheotherhand,wecan’tseethepressureeither,withoureyes.However,wecanmeasureboththepressureandflow.Infact,inelectronics,thepressureiseasiertomeasurethantheflow.Ihavegonethroughtheseexamplessothatyoucangetmorecomfortablewith
theideaofstoringbinaryinformationaspressure.Ichosetheseexamplesbecausetheyareformsofpressurewecanseeandfeel.Wemustnowmovebeyondthefamiliartotheunfamiliarworldoftheatomic,orrather,thesub-atomic:totheworldoftheelectron.For,thekindofpressureusedtostorebinaryinformationinmicroprocessorsis:ELECTRICPRESSURE.
CHAPTERTHREEVOLTAGEANDCURRENT
Indigitalelectronics,thenameofthedevicethatiseitherinthe“electric
pressureon”or“electricpressureoffstate”isthetransistor.Thetransistorissimilartothefaucet,whichiseitherinthe“waterpressureon”or“waterpressureoff”state.Likethefaucet,whichallowswatertoflow,thetransistorallowselectriccurrenttoflow.Likethefaucet—inwhichwaterflowswhenpressureisgoneatthevalve—thetransistorallowselectriccurrenttoflowwhentheelectricpressureisgoneatitsvalve.Likethefaucet—inwhichwaterstopsflowingwhenpressureispresentatthevalve—thetransistorstopstheflowofelectriccurrentwhenelectricpressureispresentatitsvalve.Infact,theBritishcalledtheprecursortothetransistora“valve.”Americanscalledita“tube.”Thepreviousparagraphmerelydescribeshowthetransistorisanalogoustoa
waterfaucet.But,itusedtermsthatrequireexplanations.Youneedtoknowwhat“electricpressure”is.Youneedtoknowwhatelectriccurrentis.Youneedtoknowhowatransistoractsasavalve,ormoreprecisely,asaswitch.So,thenextsectionofthisbookactslikeabasicelectricityandelectronicscourse.Thepreviousexamplesofbinaryinformationdeviceshavesomeserious
limitations.Obviously,theyarelimitedbytheirsize.Faucetsaretoobig.Coinscan’tcommunicatewithothercoins.Thedevicesarealsolimitedbytheirflexibility.BitsonCDROMsaretiny,buttheycan’tcommunicatewitheachother.Weneedasysteminwhichinformationcanbemovedquicklyfromonepartof
thesystemtoanotherpart.Weneedasysteminwhichthestateofonepartofthesystemcanquicklyandefficientlyaffectandchangeanotherpartofthesystem.Weneedasysteminwhicheventscanhappensequentially.Weneedasystemthatrunsandchangesonitsown,ratherthanhavingeverybitcontrolledbyahumanflippingaswitch—likethetelegraph—orahumanturningonafaucet.Addtothislisttheneedforthesystemtobelow-poweredandverycompact.Theseneedscanallbemetbyabinarysystembasedonelectricity.Changesin
electricalpressurehappenveryquickly.Withtheinventionofthetransistor,thentheintegratedcircuit,digitalelectronicssystemscanbeverysmall.So,thefirstthingweneedtodoisexplainelectricalpressure.Waterpressure
comesfromawaterpumppushingonthewater.Electricalpressureisabithardertocomprehend.Whatisitaboutelectricitythatcan“push?”Whatgetspushed?Wecanseetheeffectsofmagnetism.Wehaveallprobablyplayedwith
magnetsaschildren.Wecantaketwomagnets,andmakeoneofthemmoveacrossatabletotheother.Theonemagnetmovestheother.Wecanturnonemagnetaround,andthentrytoforcethemagnetstogether.Wefindthatthemagnetsverystronglypushawayfromeachother.Wehavefirsthandknowledgethatamagneticforcefieldcanpushorpullothermagnetsorferromagneticmaterial.
Itturnsoutthatthereisanotherforcefield:theelectricforcefield.Itisverysimilartothemagneticforcefield.It,too,canmaketwopiecesofmetalmovetowards,orawayfrom,eachother.Itmakesaballoonrubbedagainstoursweatersticktous.Itmakesthosenasty,white,“peanut”packingmaterialssticktoeverything.ItmakestheelectronbeammoveacrossouroldCRTTV’sandcomputermonitors.Itmakeslightningmovethroughtheair.Itisafundamentalforceofnature.Voltageisthenamewegivetothiselectricpressure,thiselectricforcefield.
Sometimeswecallitelectromotiveforce,orEMF,forshort.“Electromotiveforce”isaperfectname,becausevoltageisa“forcethatmoveselectrons.”Ittellsusthatvoltageisaforce;thattheforcecanmovethings;andthatelectronsarethethingsthatgetmoved.Weshouldsay“voltageon”or“voltageoff”insteadof“electricpressureon”or“electricpressureoff.”Infact,usingtheterm“electricpressure”isabitinaccurate,becausepressure
meansforceperunitarea,whereasvoltagemeansenergypercoulombofcharge,orworkdonepercoulombofcharge.Sinceworkisforcetimesdistancemoved,thenvoltage=forcexdistance/coulomb.Thisequationisthemathematicalrepresentationofcallingvoltageanelectromotiveforce.Coulombsisthenumberofelectronsmoved(electro),anddistanceisthemeasurementofmovement(motive).So,pressureandvoltagehaveincommona“force”attheheartoftheirequations.Iusetheword“pressure”becauseit’ssomethingweallcanfeel,likewhenwepressonsomethingandseeitmove.Tounderstandvoltage—andcurrentforthatmatter—wemustunderstandthe
atom.Iusetheterm,“understand,”looselyhere.Idon’tfeelthatwecantrulyunderstandtheatom,ortheelectron,orlight,orgravity,orelectromagneticwaves,oranyofthefundamentalelementsofphysics.Ourbrainsbestunderstandthethingsofthemiddlerangeoftheuniverse.Wecannotcomprehendtheincrediblysmall,likeatoms,ortheincrediblebig,liketheuniverse.Thereisnoreasonforustobedesignedtocomprehendthesethings.So,weusuallyusemodels,basedonthingswecanunderstand,tohelpus
explainthingswecan’tunderstand,likeatoms.ThesimpleBohrmodeloftheatombesthelpsustounderstandhowvoltagecomesfromatoms.TheBohrmodelrepresentstheatomaslikeaplanetarysystem.Inaplanetary
system,thereisalarge,massivesunatthecenter.Orbitingaroundthesunaretheplanets,smallerandlessmassivethanthesun.Anotherforce,gravity,pullstheplanetstowardthesun,keepingthemfromflyingawayintospace.(IgnoringEinsteinandquantum,forsimplicity.)Perthismodel,theelectronsareliketheplanets.Theprotons,attheheartof
theatom,arelikethesun.Electronsarelessmassivethantheprotons.Theweaknuclearforcekeepstheelectronspulledtowardtheprotonsatcenter,ornucleus,oftheatom.Unlikegravity,butmorelikemagnetism,wesaythatelectronshaveanegative
charge(-).Protonshavetheoppositecharge:positive(+).“Like”chargesrepel,
and“unlike”chargesattract.Thismeansthatthereisafundamentalforceofnaturesuchthateveryelectron(-)pushesallotherelectrons(-)awayfromitself.Everyproton(+)pushesallotherprotons(+)awayfromitself.Thisiswhatwemeanwhenwesay,“like”chargesrepel.Everyelectron(-)andeveryproton(+)pulltowardeachother.Thisiswhatwemeanwhenwesay,“unlike”chargesattract.So,theelectronsontheoutsideoftheatomtrytostayawayfromeachother,
asmuchaspossible,whileatthesametimetheyareattractedtowardtheprotonsinthecenteroftheatom.Ifyouthinkaboutthisforawhile,youshouldwonderwhytheprotons,crammedtogetherinthenucleusandrepelledbyeachother,don’tflyapart.Sincethisdoesn’tmakesense,wesaythattheyareheldtogetherbyaforceofattraction,strongerthantheforceofrepulsion.Wecallitthe“strongnuclearforce.”Soundssuspiciouslyconvenient.Thestrengthoftheforceinoneelectronorinoneprotonisverysmall,butvery
real,nonetheless.And,therearesomanyelectrons,somanyprotons.And,theirstrengthiscumulative.Witnessthepowerofalightningstrike.Ifweaddalotofextraelectronstoonepieceofmetal(sothatitisexcessivelynegative),andremoveelectronsfromanotherpieceofmetal(sothatitisexcessivelypositive),thosetwopiecesofmetalwillmovetowardseachother,justliketwomagnets.Oneatommayhavemanyprotonsandelectrons.Andwithinthisatom,many
pressuresexist.Butthepressuresareverysmall.And,thenetpressureiszero,sinceinoneatomtherearethesamenumberofelectronsasthereareprotons,andthepositivechargeofoneprotonexactlyequalsthenegativechargeofoneproton.Puttingawholebunchofatomstogetherdoesn’tchangethings,becausetheirnetpressureisstillzero:abunchofzeronetpressureatomsaddsuptozeronetpressure.Howdowecreatetheelectricpressurewe’vebeentalkingabout?Wehaveto
un-balancetheatom.Oneofthedefinitionsofvoltage(EMF)is“aseparationofcharge.”Ifweremoveanelectronfromanatom—separatethecharge—theremainingatomnolongerhasexactlythesamenumberofelectronsasprotons.Itisnotinbalance.Itnolongerhaszeronetcharge.Ithasonemoreprotonthanelectrons,soithasanetchargeof+1,or+1timestheforceofoneproton.Onetheotherhandifweaddanelectrontoanatom—separatethechargefrom
elsewhere—theatomnolongerhasexactlythesamenumberofelectronsasprotons.Itisnotinbalance.Itnolongerhaszeronetcharge.Ithasonemoreelectronthanprotons,soithasanetchargeof-1,or-1timestheforceofoneelectron.Ineachoftheabovecases,theatomhasnetpressure,eitherpositiveor
negative.Wecallthisatomapositiveionoranegativeion.Themoreionsweputtogether,themorevoltage(pressure)wehave.Wehavefoundwhatwehavebeenlookingfor:voltage.Thequestionnowchangesto:howdoweseparatecharge,orequivalently,how
dowecreatevoltage?Onewaytodoitisthroughbruteforce.Wecanuseourmusclesandrubthingstogether.Ifyourubaballoononyourwoolsweater,the
balloonmaythenbeabletosticktoawall.Youhaveforcedaseparationofcharge.Becauseoftheiratomicstructure,woolisverywillingtogiveupelectronsandballoonsareverywillingtogainelectrons.Theballoondoestrulyhavevoltage.Itiscalled“electrostatic”voltage,or“static
electricity”.It’sthesameelectricitythatcausesthestaticshockwefeelwhenwetouchadoorknob.Butthisvoltageistemporary.Whenthechargeditemtouchessomethingthathastheoppositecharge,thelight-weightelectronsmovetothepositiveobject:thestaticvoltageisgone.Youhavetoreplenishthechargebyrubbing,again.Wewouldlikeaself-replenishingsourceofvoltage.Wecallthisself-
replenishingvoltagesourceabattery.Seethepicturebelow.Atypicalbatteryhastworodsimmersedinafluidcalledanelectrolyte.Therodsaremadeofdissimilarmetals,likenickelandcadmium.Achemicalreactionoccurs,causingtheelectronsfromonemetalrodtomovethroughtheelectrolytetotheothermetalrod.Therodthatgainselectronsiscalledthenegativeterminalorcathode.Therodthatloseselectronsiscalledthepositiveterminaloranode.Inani-cadbattery,theanodeismadeofnickel,thecathodeofcadmium,andtheelectrolyteofpotassiumhydroxide.
FIGURE3-1
Figure3-1,part(a),showstheprocessofchargeseparationwhenthe
electrolyteispouredintothebattery.Figure3-1,part(b),showstheelectricalsymbolforabattery.Thebatterynowhasvoltage:pressuretomovesomething.Whatdoesvoltage
move?Voltagemoveselectrons.Thismovementofelectronsiscalled,current.Currentiselectronsmoving.Notmovingwithinanatom,butmovingoutofanatomandgoingelsewhere.Buttowheredotheymove?Toanswerthisquestion,wehavetopauseandlookattheworldofchemistry,
atomicstructure,andtheperiodictable.Theperiodictabledescribesatoms.Each
atomisnumbered,inascendingorder.Thenumbersstandforhowmanyelectrons,protons,andneutronseachatomhas.Hydrogenisnumbered“1”becauseithasoneelectron,oneproton,andoneneutron.Oxygenisnumbered“8”becauseithaseightelectrons,eightprotons,andeightneutrons.Thistellsusthatwhatmakesoneelementdifferentfromanotheristhenumberofelectrons,protons,andneutronsinitsatom.Thecolumnsintheperiodictablehavesignificance,especiallytotheelectrical
propertiesofmatter.Theelectronsinaspecificatomarrangethemselvesingroups,frominnergroups—orshells—tomiddlegroups,tooutergroupsofelectrons.Acolumnintheperiodictabledescribeselementsmadeofatomswhoseoutershellsexhibitsimilarproperties.Theouter—orvalence—shellofaspecificatomwillhavebetweenoneand
eightelectrons.Forexample,siliconatomshavefourelectronsintheiroutershell.Copperatomshaveoneelectronintheiroutershell.Let’sgobacktothequestionofwhereelectronscanmove:wherecurrentcan
flow.Wefindthat,electrically,therearethreecategoriesofmaterials,conductors,semiconductors,andinsulators.Conductorsarematerialsthroughwhichcurrentcanveryeasilyflow.A
conductorhasoneelectroninitsoutershell.Theoneelectronneverattainsasymmetricalbalanceofattraction-repulsionwithintheatom,soitisveryfreetomoveawayfromtheatom.Intheperiodictable,youwillfindconductorsgroupedtogetherintheeleventhcolumn:copper,silver,andgold.Semiconductorsarematerialsarematerialsthroughwhichcurrentcan
somewhatflow.Asemiconductorhasfourelectronsinitsoutershell.Thesefourelectronshaveamoderatesymmetricalbalanceofattraction-repulsionwithintheatom,sotheycanbemovedawayfromtheatomifadequateoutsidepressureisapplied.Intheperiodictable,youwillfindsemiconductorsgroupedtogetherinthefourteenthcolumn:carbon,silicon,andgermanium.Insulatorsarematerialsinwhichcurrentdoesnotflow.Aninsulatorhaseight
electronsinitsoutershell.Theseeightelectronsareinastrongsymmetricalbalanceofattraction-repulsionwithintheatom,sotheyarenotfreetomoveawayfromtheatom.Intheperiodictable,youwillfindinsulatorsgroupedtogetherintheeighteenthcolumn:helium,neon,andargon.Also,whenelementscombinetogether,theytendtoshareoutershellelectronsandaligninsuchawaythateachelement’soutershellhaseightelectrons,becominganinsulator.That’swhysodiumchloride(tablesalt)isagoodinsulator.Soareplastic,glass,rubber,andair.Returningnowtoelectricalcurrent,let’simagineourbattery,withextra
electrons(negativeionatoms)congregatingonthenegativeterminal,andmissingelectrons(positiveionatoms)onthepositiveterminal.Theelectronsonthenegativeterminalwouldreallyliketogetawayfromeachother.Theywouldliketogettothepositiveterminal,sothatbothterminalswouldbeneutral.Theatomscouldreturntotheirnatural,neutral,non-ionicstate.Buttheycan’tgothroughthebattery.Itwasthechemicalreactioninthebatterythatdidalltheworkincreating
thisimbalanceinthefirstplace,storingtheworkaspotentialelectricalenergy.Youmayhaveheardofthisreferredtoaselectricalpotential.Theelectronscouldescapefromthenegativeterminalifweputaconductor,
likeacopperwire,betweenthepositiveandnegativeterminalsofthebattery.Seethepicturebelow.(WARNING:Don’tdothis,itcouldblowupthebattery.Iwillexplainabouttheneedforelectricalresistancelater.)Rememberthepreviousdiscussionaboutconductorslikecopper?Theiratomshaveoneverylooselyboundelectronintheiroutershell.Theyareveryeasilymovedbyelectricalforce.Theinstantyouconnectthewiretothebatteryterminals,theseelectronsfeeltheattractionofthepositiveionsinthepositiveterminalandtheyfeeltherepulsionfromthenegativeionsinthenegativeterminal.Theymove!Theymovetowardsthepositiveterminal.
FIGURE3-2
Let’sstoptoenjoy,appreciate,andwonderatthis.Wecallthiscurrent,because
itislikewatercurrentinastream.Butthisismovementinawire.Theverywirehasmotion—attheatomiclevel—insideit.Thesolidwirehaselectronsflowinginsideit.Wehaveansweredourquestion,“Wheredoescurrentflow?”Wehavedevicescalledammetersthatmeasuretheamountofmovement
insideawire.Theymeasurethenumberofelectronsthatmovethroughacross-sectionalareaofwire,persecond.Theunitofmeasureisthe“ampere.”Anammetermightmeasureoneampere,oroneamp,ofcurrentinawirecomingintothiscomputer.Oneampis6.25x1018electronspersecondpassingacross-sectionalareaofthatwire.That’s6,250,000,000,000,000,000electronspassingby,everysecond!(Wecall6.25x1018electronsacoulomb.So,oneampereisonecoulombpersecond.)So,theelectronsintheatomsthatconstitutethewiremovetowardthepositive
terminal.Buttheelectronsfromthenegativeterminalofthebatteryarerightbehindthem.Remember,theyarerepulsedbyeachother,andwerewaitingfortheirchancetoescape.Next,thebatteryterminal’satomsstartgoingneutral.Thenegativebattery
terminalwasnegativebecauseitsatomshadextraelectrons.Theseelectronsareleaving,sotheatomsbecomeneutral.Thepositivebatteryterminalwaspositivebecauseitsatomsweremissingelectrons.Electronsarenowmovinginandjoiningtheatoms,sotheatomsbecomeneutral.So,itwouldseemthatcurrentflowisdone.Youmightthinkthatwehavea
situationsimilartoelectrostatics,whereelectronflowstops,becausethesourcesofrepulsion/attractionareneutralizedandgone.Butno,somethinginterestinghappens.Thebattery’schemicalreactionthat
hadbeenfinisheddoingitsworkinseparatingcharge,startsagain.Assoonasterminalatomsstartgoingneutral,thebatterystartsseparatingchargeagain.Asanatomonthepositiveterminalacquiresamissingelectrontobecomeneutral,thechemicalreactioninthebatterytakesitawayagain.Itsendstheelectronthroughtheelectrolytefluid,andforcesitbackintoanatomonthenegativeterminalthathadjustgoneneutralbecauseitlostitsextraelectron.So,thechemicalreactioninthebatteryrestorestheseparationofchargeonthe
batteryterminals(thevoltage),duringcurrentflow.Theelectroncurrentflowthatmovesthroughthewirecontinuestomovethroughtheelectrolytefluid!So,thecircuitistrulyacircuit,sinceelectronsevencirculatethroughthebattery.Currentflowdoesnotstop.Remember,Isaidyoumustnotputawireacrosstheterminalsofthebattery.
Toomanyelectronswouldflow.TheequationfortheamountofcurrentflowisI=V/R,whereIiscurrent,Visvoltage,andRisresistance.Resistanceisameasureoftheabilityofamaterialtoimpedecurrentflow.Well,theresistanceofawireisnearzero.Ifyourememberalittleofhighschoolalgebra,youwillknowthat,asthedenominatorapproacheszero,thequotientapproachesinfinity.Nearlyinfinitecurrentflowsthroughthewire,ornear-infinitytimes6.25x1018electronspersecond.Somethingisdestroyed:eitherthebatteryorthewire.Whatyoushouldreallyputacrossthebatteryisasemiconductor.Amore
manageableamountofcurrentwillflow.Carbonisagoodsemiconductivematerial.Wemakecomponentscalledresistorsoutofcarbon.Ratherthanawire,aresistorshouldbeputacrossthebatteryterminalstomakeamoderateamountofcurrentflow.Nowyoucanseewhythissubjectiscalled“electronics.”Thesourceofvoltage
iselectrons:electronsseparated,thenpackedtogether.Thecurrent,too,iselectrons:electronsinmotion.Electronicsiselectronsmovingelectrons.It’sallaboutelectrons.
CHAPTERFOURTHEFAUCETANALOGY
Ifeltthattheabove,ratherlengthy,sectiononvoltageandcurrentwas
necessarysothatyoucouldunderstandthebinaryencodingofon-or-offelectricalpressure.Next,Iwouldlikeyoutorecallthatthisvoltagepressuresystemisanalogoustoawaterpressuresystem.Youencounterwaterpressuresystemseverytimeyouuseawaterfaucet.Iwouldliketouseyourfamiliaritywithwaterpressuretohelpyouunderstandamicroprocessor-basedsystem.BeforeIintroducetheconceptofatransistor-as-switch,let’sfirstlookata
faucet-as-switch.Lookatthepicturebelow.
FIGURE4-1
Theabovepictureisadiagramofanon-offstylewaterfaucet,likeadrinkingfountain.Ifyoudon’tpressthebutton,nowaterflows.Ifyoupressthebutton,
waterflows.Itiseitheronoroff.Atransistorcircuitcanbedesignedtoworklikethis:onoroff.Thisisdigitaldesign.“Digital”isapoortermforabinarysystem.Thisisnotthekindoffaucetyouhaveinyoursink.Yoursink’sfaucetisan
analogsystem,becauseitcanbeinaninfinitenumberofstates.Thewaterflowcanbealittle“on”,oralittlemore“on”,oralittlemore“on”thanthat,etc.Atransistorcanbedesignedasananalogcircuit,too.Wewouldthencallitatransistoramplifier.Thisisnothowtransistorsareusedinmicroprocessors,orinanydigitalcircuits.Indigitalcircuits,transistorsareusedason-offswitches.Digitalcircuitshave,notaninfinitenumberofstates,butjusttwostates:onoroff.Theabovefigureshowsthefaucetbuttonnotbeingpressed.Awaterpump,not
shown,isapplyingpressuretothewater,forcingitdowntothevalve.Thewatercannotgetpastthevalve,becausethevalvecompletelyblocksit.Nowaterflowsfromthebottomofthefigure.Youcannotgetadrink.Wewouldsaythattheabovefaucetisoff.Nowaterisflowing.Butwecould
alsosaythat,atthevalve,pressureison.Thevalvefeelsthefullpressurefromthewaterpump.Rememberthisdistinction,becauseitappliestotransistors.Looknowatthefigurebelow.
FIGURE4-2
Thisnewdiagramshowsthefaucetbuttonbeingdepressed.Thevalvemoves
right,andoutoftheway.Itnolongerblocksthewater.Thewaterflowsoutofthepipe,onthebottomofthediagram.Youcangetadrink.Wewouldsaythefaucetison.Waterisflowing.Butwecouldalsosaythat,at
thevalve,pressureisoff.Thevalvefeelsnopressurefromthewaterpump,becauseitisoutofthewayoftheflowingwater.Ifyougetconfusedbytransistors,justcomebacktothesebasicconcepts.Thespringintheabovedesignisapracticalconsideration.Whenyoustop
pressingthebutton,thespringpushesthevalvebacktotheblockingposition,stoppingwaterflow.
So,atransistorislikeanon/offwaterfaucet.But,onewaterfaucetoronetransistorisjustonebinarybit,soitcannotencodemuchinformation.Wecanputagroupofwaterfaucetsnexttoeachother,orgrouptogethertransistors,and
increasethenumberofuniquepiecesofinformationthatwecanencode.Seethefigurebelow:
FIGURE4-3
Intheabovediagram,usingfourwaterfaucets,wehavecreatedafourbit
binarysystem.Wechoosetonameourtwostates“1”and“0”.Wechoosetodefinethe“1”stateastheconditioninwhichthevalvereceivespressure.Wechoosetodefinethe“0”stateastheconditioninwhichthevalvereceivesnopressure.Werefertoafourbitbinarysystemasanibble(nojoke).Theabovefigureshowsthesysteminthe1-0-1-0state.Thisisoneofthe24or16uniquestateswecanencode.The16statesare:0-0-0-00-0-0-10-0-1-00-0-1-10-1-0-00-1-0-10-1-1-00-1-1-11-0-0-01-0-0-11-0-1-0
1-0-1-11-1-0-01-1-0-11-1-1-01-1-1-1Butweneedtodomorethanthis.Theabovesystemstillrequiresahandto
presseverywaterfaucet.Recallabovethatwesaid:“Weneedasysteminwhichthestateofonepartofthesystemcanquicklyandefficientlyaffectandchangeanotherpartofthesystem.Weneedasysteminwhicheventscanhappensequentially.Weneedasystemthatrunsandchangesonitsown,ratherthanhavingeverybitcontrolledbyahumanflippingaswitch.”Iwouldliketotakeyouthroughadesignofsuchasystemusingwaterfaucets.Understandingthissystemshouldhelpyoutounderstandthetransistor-basedsystem.Lookatthepicturebelow:
FIGURE4-4
Inthissystem,thestateoffaucetBiscontrolledbyfaucetA.Nohuman
pressesthebuttonoffaucetB.Nevertheless,faucetB’sbuttonisdepressed.WehaveaddedaconnectorpipefromfaucetAtofaucetB.ThepressurizedwaterflowsdownfaucetA,butgetsblockedbyfaucetA’sclosedvalve.Thewaterflowsfromlefttorightthroughtheconnectorvalve.Sincethewaterispressurizedbythepump,itpushesonfaucetB’sbutton.FaucetB’svalveopens,itsvalvehasnopressureonit,watergetspastitsvalve,andwaterflowsoutoffaucetB.Inshort,whennowaterflowsfromfaucetA,waterflowsfromfaucetB.Phrased
differently,whenpressureisonfaucetA’svalve,pressureisofffaucetB’svalve.
Now,lookatthenextpicture:
FIGURE4-5
ThissystemisthesameoneshownaboveinFigure4-4.However,thistime,
waterpressureonthefarleftentersthesystemanddepressesthebuttononfaucetA.Thiscauseseverythinginthesystemtoreverse.Now,waterflowsfromfaucetA.Now,nowaterflowsfromfaucetB.Now,nopressureisonfaucetA’svalve,whilepressureisonfaucetB’svalve.Youarenowseeingourneedfulfilled:“asystemthatrunsandchangesonits
own,ratherthanhavingeverybitcontrolledbyahumanflippingaswitch.”FaucetBisbeingcontrolled,notbyahuman,butbyfaucetA.IffaucetAflows,faucetBdoesn’t.IffaucetAdoesn’tflow,faucetBdoes.Phraseddifferently,iffaucetA’svalvehaspressure,faucetB’svalvehasnopressure.IffaucetA’svalvehasnopressure,faucetB’svalvehaspressure.Let’slearnsomemorefromthissystem.First,noticethatfaucetBiscompletely
controlledbyfaucetA.Butthereverseisnottrue:faucetAisinnowaycontrolledbyfaucetB.FaucetAiscontrolledbysomeotherfaucet,notshown.Also,noticethecontrolflowofthissystemisfromlefttoright.Thisishowwe
willdrawourtransistordesigns,too.Thefaucetsfromoff-screenleftcontrolfaucetA.FaucetA,whichisleftoffaucetB,controlsfaucetB.Now,let’sdigalittledeeperonthisleft-to-rightflow.RememberIsaidthatin
transistordesign,wefocusonpressureratherthanflow:voltageratherthancurrent.Thusfar,lookingatFigure4-5above,wehaveonlyfocusedontwopressures:oneatthevalveoffaucetA,andoneatthevalveoffaucetB.Thesearefaucetoutputpressures.But,therearetwomorepressures:oneatthebuttonoffaucetA,andoneatthebuttonoffaucetB.Thesearefaucetinputpressures.Toseethismoreclearly,lookatthepicturebelow:
FIGURE4-6
ThisisasimplifieddiagramofFigure4-5,above.Withit,wecanfocusmore
clearlyonthefourpressures.Remember,thecontrolflowofthediagramreadsfromlefttoright:faucetAcontrolsfaucetB.But,theinput-to-outputpressureflowdirectionisalsofromlefttoright.ReadingdirectlyfromFigure4-6,faucetAhasinputpressure,andnooutputpressure.FaucetBhasnoinputpressure,buthasoutputpressure.Infact,theoutputpressureoffaucetAcontrolstheinputpressureoffaucetB.
InFigure4-6,thevalveoffaucetAisoutoftheway,thepressureonitisgone,andthewaterflowsalongthepathofleastresistanceoutofthefaucet,sothatnowaterflowsacrosstheconnectorpipetoputpressureontheinputbuttonoffaucetB.Forthesakeofcompleteness,let’slookathowtheoutputpressureoffaucetA
controlstheinputpressureoffaucetBwhenthefaucetsareintheirreversestates,asshowninFigure4-7,below:
FIGURE4-7
InFigure4-7,faucetA’svalveisinthewayofthewater,soitfeelspressure.
Thewatercan’tgetthrough,soitflowsacrosstheconnectingpipe,applyingpressuretotheinputoffaucetB.FaucetA’soutputpressurecausesfaucetB’sinputpressure.There’sstillmorewecanlearnfromthefaucetsinFigure4-7.Onefaucetacts
asthemostbasicbuildingblockofdigitallogic:theinverter.Bydefinition,aninverterisalogicdevicethattakestheinput,reversesit,andplacesthereversedvalueontheoutput.LookatfaucetA,Figure4-7.Itsinputis“nopressure.”Thereverseoroppositeof“nopressure”is“pressure.”FaucetAreversestheinput“nopressure”andplaces“pressure”ontheoutput.Alternatively,faucetB,Figure4-7has“pressure”asitsinput.FaucetBtakes
theinverseoroppositeof“pressure,”placing“nopressureonitsownoutput.Indigitallogic,werepresentthetwobinarystatesasthenumbers1and0.We
oftencall1,“true.”Wecall0,“false.”Sincewecanassociatethepresenceofpressurewith“true,”andtheabsenceofpressurewith“false,”wenaturallyequatepressurewith1,andnopressurewith0.Wedothiswhetherourpressureisfromwaterorfromvoltage.Now,insteadofdescribingourfaucetasturninganinputofpressureintoan
outputofnopressure,wecansaythatitturnsaninput1intoanoutput0.Insteadofdescribingourfaucetasturninganinputofnopressureintoanoutputofpressure,wecansaythatitturnsaninput0intoanoutput1.Wecanputtheseresultsintotheformofthetablebelow:
FIGURE4-8
Thetableontheleft,(a),ofFigure4-8summarizestheonlytwopossible
behaviorsofonefaucet.ThelinelistedasSTATE1correspondstofaucetA’sstateinFigure4-7.ThelinelistedasSTATE2correspondstofaucetB’sstateinFigure4-7.Thetableontheright,(b),ofFigure4-8isequivalentto(a),butwithbinary
digits0and1replacing“NoPressure”and“Pressure,”respectively.Inthisform,thetableiscalleda“truthtable,”since1meanstrueandzeromeansfalse.Itcanalsobecalleda“logictable.”Fromthistable,itshouldbeclearthat,foraninverter—likeouronefaucet—a0inputbecomesa1output,anda1inputbecomesa0output.Nowyoucanseewhy0and1areused:theymakeforaverycompactrepresentation,andcanstandforwhateverwewantthemto—inthiscase“NoPressure”and“Pressure.”Indigitallogic,alogicsymbolisoftenusedtorepresentaninverter.Likethe
truthtable,itiscompact,savingusfromdrawingelaboratetransistorcircuitsorfaucets.Italsosimplifiesconnectingcircuitstogether,likeourfaucetscontrollingotherfaucets.Lookatthepicturebelow:
FIGURE4-9Thetrianglewithabubbleontherightisthelogicsymbolforaninverter.Idrew
ittwicetoshowtheonlytwostatesitcanbein.Figure4-9,part(a)islikestate1ofthetruthtableinFigure4-8,part(b):0ontheinputbecomes1ontheoutput.Figure4-9,part(b)islikestate2ofthetruthtableinFigure4-8,part(b):1ontheinputbecomes0ontheoutput.Noticealsothedirectionthetriangleispointing.Itislikeanarrow,pointingto
theright.Remember,Itoldyouthatcircuitcontrolflowslefttoright,withinputson
theleftandoutputsontheright.Theshapeoftheinvertersymbolhelpsustorememberthisconcept.Theinputsideisoftenlabelled“A,”andtheoutputsideisoftenlabelled“Y.”Thebubbleatthearrow’stipisacluethattheoutputisinverted.Ifweagreetocalltheinput“A”andtheoutput“Y,”wecanredrawourtruthtable
fortheinverterinanevensimplerformthaninFigure4-8.Seethepicturebelow,Figure4-10,part(a),forthesimplerinvertertruthtable.
FIGURE4-10
InFigure4-10,part(b),Ialsoplacedasimplerversionofthelogicsymbolfrom
Figure4-9.Now,withwonderfulsimplicity,Figure4-10displaysallyouneedtoknowaboutaninverter.Itcanbeimplementedwithatransistor,afaucet,oranyotherbinarydeviceyouchose,withconfidencethattheyallexhibitthesebehaviors.Next,let’sredrawFigure4-7,usinglogicsymbols.Lookatthepicturebelow:
FIGURE4-11Howsimpleitlooks,now.ThefaucetsofFigure4-7weretwoinverters,
connectedleft-to-right.Thelowpressure(0)comingintoinverter(a)wasinvertedtohighpressure.Thathighpressurewasfedtoinverter(b).Inverter(b)invertedthehighpressurebacktoalowpressure.Theinverterisjustoneofthebasicbuildingblocksofdigitallogic.Thereare
onlyafewbuildingblocks.Yet,whenputtogether,theycancreatecircuitsaspowerfulasamicroprocessor.Let’sdesignonemoresystemfromwaterfaucets,beforewemoveontotransistors.Lookatthepicturebelow:
FIGURE4-12
ThefirstthingyoushouldnoticeaboutFigure4-12isthatfaucetCisnowbeing
controlledbytwofaucets,faucetAandfaucetB.TheinputstofaucetsAandBarebothat“nopressure.”Sincetheyareinverters,theoutputsofbothfaucetsAandBareat“pressure.”ThewateranditspressureheadstotheinputoffaucetC,makingtheinputtofaucetC,“pressure.”SincefaucetCisaninverter,itsoutputbecomes,“nopressure,”andwaterisfreetoflowfromit.Nowlet’schangetheinputtofaucetA.Lookatthepicturebelow:
FIGURE4-13
Figure4-13isthesamesystemasFigure4-12,butnowwaterpressureis
appliedtotheinputoffaucetA.ThiscauseswatertostopflowingfromfaucetC,orwewouldsaythattheoutputvalveoffaucetCnowabsorbsthewaterpressureenteringthepipefromthetop,blockingwaterflow.LookcloselyatthechainofeventscausesfaucetCtoturnoff.Atransistor
circuitlikethisworksthesameway.Justlikebefore—inFigure4-6—thewaterenteringfaucetAfromthetopflowsoutthebottomoffaucetA.Thus,thewaterfromthetopoffaucetAcannolongerapplypressuretotheinputoffaucetC.However,thewaterfromthetopoffaucetBcan’tapplypressuretotheinputoffaucetCeither,becauseitnowhasapathoflessflowresistance:ittooflowsoutofthebottomoffaucetA.Inotherwords,faucetAnotonlydrainsitself,itdrainsfaucetB,too.NeitherfaucetAnorfaucetBcanturnonfaucetC.Now,lookatthepicturebelow:
FIGURE4-14
IfyouunderstoodFigure4-13,thenyoushouldhavenoproblemwithFigure4-
14.Theinputpressuresarenowreversed.InsteadofinputpressureonfaucetAandnoneonB,wehaveinputpressureonfaucetBandnoneonA.But,theresultsarethesame:FaucetCisoff—nowaterflows—andthepressureonitsvalveison.TheresultsinFigure4-14arethesameasinFigure4-13,becausethesystem’sbehavioristhesame:oneinputfaucetison,drainingnotonlyitself,butalsotheotherfaucet.Inthiscase,faucetBison,drainingnotonlyitself,butalsofaucetA.NeitherfaucetAnorfaucetBcanturnonfaucetC.NoinputpressureisavailableintoFaucetC.Thereisonlyonefinalpossiblestateforthissystem.Seeitinthepicturebelow:
FIGURE4-15
Figure4-15isthefourthpossiblestateforthissystem.Thistime,inputpressure
isappliedtobothfaucetsAandB.There’snothingtrickyhere:nocurrentflowsfromfaucetC;pressureis“on”itsoutputvalve.Thereasonisthat,sincebothfaucetsAandBareturnedon,alltheirinputwaterrunsoutoftheoutletsoftheirrespectivepipes.NopressurizedwatereverreachesfaucetCtoturniton.Figures4-12,4-13,4-14,and4-15representthefourpossiblestatesofourtwo-
inputsystem.Rememberourearlierdiscussion,whereweexplainedthatthewaytocalculatethenumberofuniquestatesofabinarysystemwastotake2tothepowerofthenumberofbits?Inthiscase,thereare22=4possibleinputstates.Thissystemisoursecondbasicbuildingblockofdigitallogiccircuits.ItiscalledanORgate.Seethepicturebelow:
FIGURE4-16
Figure4-16isoursimplifiedrepresentationofanORgate.Itislikeour
simplifiedrepresentationoftheinverterinFigure4-10.Figure4-16,part(a),isthetruthtableforanORgate,andFigure4-16,part(b)isthelogicsymbolfortheORgate.Let’sfirsttrytounderstandwhatpart(a)istellingus.Rememberthat1
represents“true”,asin“thepressureistrulyon.”0representsfalse,asin“thepressureisnoton.”TheAandBcolumnsrepresentthestatesoftheinputpressures,theinputstofaucetAandfaucetB.TheletterY—notC—istraditionallyusedasthenameforthestateoftheoutputpressure,inthiscasetheoutputoffaucetC.ThefourrowsrepresentthefourFigures:4-12,4-13,4-14and4-15.Howsimpleandcompact!Awholediagramgetsreplacedbyasimplerowofatruthtable.Thoseconfusingintermediary,internalpressuresthatcoupledtheoutputsoffaucetsAandBtotheinputofvalveCdonotappear.Wereallydon’tneedtoknowaboutthemwhendesigningatthelogicgatelevel.Part(a)helpsclarifywhatweshouldhavenoticedwhenstudyingFigures4-12
through4-15:that,aslongasatleastoneinputpressureison,theoutputpressureison.ItiscalledanORgatebecause,iftheApressureinputortheBinput,orbothinputsareon,thentheoutputpressureison.Figure4-16,part(b)isthelogicsymbolforanORgate.Noticehowtheleftside
ofthesymboliscurved,andhowthetopandbottomsidesarecurvedandcometoapointattheright.Thishelpsusremembertheleft-to-rightflowincircuitdesignandanalysis.Todesign,wedon’tneedtoknowwhat’sinside(b):itcouldbebigpipes,itcouldbelittletransistors.Wedesignwithlogicsymbols.Let’sdoadesign,now.Sofar,youknowtwologicgates:theinverterandthe
ORgate.Let’sdesignasystemtomonitoryourtoilet.Ifsomeoneflushesthetoiletandimmediatelyleavesthehouse,youcouldgetwaterdamagetoyourhouseif
thebowlorthetankoverflows.Hint:Ijustusedtheword,“or.”Seethepicturebelow:
FIGURE4-17
Let’sforgetaboutvoltagesorwaterfaucetsinsidelogicgates,fornow.Let’s
concentrateonwhat1’sand0’swillstandfor.Let’ssaythattheinputstoourdesignaretwosensors:onethatmonitorstheheightofthewaterinthetoiletbowl,andonethatmonitorstheheightofthewaterinthetoilettank.Normally,theyareinthelogic0state,meaningthewaterisnottoohigh(false).Ifsomethinggoeswrong,asensorgoesintothelogic1state,meaningthewateristoohigh(true).Theoutputofoursystemisawatershut-offvalve.Normally,itisinthelogic1
state,meaningwaterisallowed(true)tocomeintothetoiletfromthewatersupply.Ifsomethinggoeswrong,itmustgointothelogic0state(false),meaningwaterisnotallowedtocomeintothetoiletfromthewatersupply.
Ifyoulike,takeabreakandtrydesigningthissystemyourself.Putthenamesoftwoinputsensorsontheleft,thenameoftheoneoutputshut-offvalveontheright.Inthemiddle,putwhatevercombinationoflogicgatesyouneedtocreatethecontrolsystem.Don’tgethunguponthesensorsorshut-offvalve.Justtreatthemlikesourcesordestinationsof1’sandzeroes.Theanswerisinthepicturebelow:
FIGURE4-18TheORgate—asIhintedearlier—isalmostenoughforthisdesign.Remember
fromthetruthtableinFigure4-16fortheORgatethatitsoutputwillbelowifbothinputsarelow;itsoutputwillbehighifeitherinputorbothinputsarehigh.Thisistheoppositeofwhatwerequire.Wewanttheoutputtobehigh—turningonwaterflow—whenbothinputsarelow—indicatingnofaults.Wewanttheoutputtobelow—turningoffwaterflow—wheneitherorbothinputsarehigh—indicatingfault(s).Wewanttoinvert(makeopposite)theoutputoftheORgate.WedothisbyattachinganinvertertotheoutputoftheORgate.Lookatthepicturebelow:
FIGURE4-19ThefourrowsofFigure4-19showthe4possiblestatesforoursystem.Any
inputof1,onthefarleftside,meanswatertrouble.Theoutput,onthefarright,ofthatstatemustgotozero,topreventwaterdamage.Fromthisfigure,youcanseethattheinverterflipstheORgate’soutput,tomakeitworkcorrectly.
Let’scomparetheORgatetruthtableweencounteredinFigure4-16,part(a),withthetruthtablewecanbuildfromFigure4-19.Seethepicturebelow:
FIGURE4-20Part(a)ofFigure4-20isthetruthtablefortheORgate.PartBofFigure4-20is
builtfromthefourrowsofFigure4-19.TheAandBcolumnsofpart(b)arefromthefarleftsideofFigure4-19:theinputs.TheYcolumnofpart(b)isfromthefarrightsideofFigure4-19:theoutput.ThismakesiteasytoseehowtheYoutputcolumnisinvertedinFigure4-20part(b)comparedtopart(a).Itturnsoutthatthecircuitwejustdesignedisourthirdfundamentalbuilding
blockofdigitalelectronics:theNORgate.NORstandsfor“NotOR,”inreferencetothefactthateachofthepossibleoutputstatesoftheORgatearenotwhattheyusedtobe.TomakeanORgate,wesimplyneedtoaddoneextrainverter—anextrawaterfaucetortransistor—totherightendofthethree-inverterORgatewealreadycreated,asinFigure4-15.ThepicturebelowsummarizestheNORgate’struthtableandlogicsymbol:
FIGURE4-21Notice,inFigure4-21,part(b),thatthelogicsymbolfortheNORgatelooksjust
likethelogicsymbolfortheORgate,exceptthattheNORgatehasabubbleontheoutput.ThebubblemeansthattheoutputisinvertedfromtheORgate.ThisisasymbolicwayofshowingthesamethingwediscoveredinFigure4-20,comparingtheYoutputcolumnsoftheORandNORgates.RememberthattheNORgatelogicsymbolrepresentsaphysicalsystemwithfourfaucetsinside:threefromanOR,andonefromaninverter.
CHAPTERFIVESWITCHES
Wehavespentenoughtimeonfaucets.OurgoalistoteachyouhowtheseOR
andNORgates,inverters,andmicroprocessorsareimplementedwithtransistors.But,beforewedothat,wemustpickupthestoryofelectronicswhereweleftoff.Inourexplorationofelectronicswefoundthatthe“pressure”ofvoltage
producedbyabatteryiscausedbypositivechargeforcedtogetherononeterminal,andnegativechargeforcedtogetherontheother.Thisresultantpressureiscomparabletothewaterpressureproducedbyawaterpump,causedbyaspinningpropeller.Wenextfoundwecouldmakecurrentflow—makeelectronsmove—fromthe
negativebatteryterminaltothepositiveterminalofthebattery.Wedidthisbyconnectingasemi-conductor,likearesistor,acrossthebatteryterminals.Let’slookatresistanceforamoment.Seethepicturebelow.
FIGURE5-1Onekindofresistance,orsemiconductor,iscalledaresistor.Itisanelectronics
componentspecificallydesignedtocontroltheamountofcurrentflow.TheoneinFigure5-1,part(a),isaboutacentimeterlong,andcostsapenny.TheelectricalsymbolofresistanceisthejaggedlineshowninFigure5-1,part(b).Whenwebuyaresistor,wechoosehowmuchwewantittolimitcurrentflow.
Theunitofmeasurementofresistanceisohms,symbolizedbytheomegasymbol:Ω.Ifwebuyaresistorwithmoreohms(moreresistance),lesscurrentflows.Wecanbuyresistorsinunitsoflessthananohmuptounitsofgreaterthanamillionohms.Wecanactuallycalculatehowmuchcurrentwillflowwiththeequationcalled
Ohm’sLaw,whichstatesthatI=V/R.“I”isthelettersymbolforcurrent,inunitsofamperes,“V”isthelettersymbolforvoltage,inunitsofvolts,and“R”isthelettersymbolforresistance,inunitsofohms.Forexample,ifweconnecta6ohmresistoracrossa12voltbattery,then2amperesofcurrentwillflow,sinceI=V/R=12/6=2amps.Seethepicturebelow.
FIGURE5-2
Figure5-2isthewayweshouldhavebuiltfigure3-2,sinceitcontainsaresistor
tolimitcurrentflow.Thereareafewthingsyoushouldnotice.First,wehaveconnectedtheresistortothebatterywithtwowires.Second,thevoltageappearsacrossthebatteryterminals,andisappliedacrosstheresistor.Third,thecurrentflowsthroughthetwowires,throughtheresistor,andthroughthebattery.Forth,eventhoughtheelectronsflowfromthenegativebatteryterminaltothepositiveterminal,weusuallydrawthe“conventional”currentflowtheotherway:fromthepositiveterminaltothenegative.Thisconventionisduetoanearlybadguessbyinvestigatorswhoassignedthisdirectionbeforeweknewaboutelectrons.
FIGURE5-3Figure5-3istheschematicdiagramofthecircuitinFigure5-2.Aschematic
diagramisanelectronicsshorthandmethodofrepresentingaphysicalcircuit.Itusesschematicsymbolsinplaceofpicturesofactualcomponents.Ihaveintroducedthesesymbolsinpreviousfigures.GivenFigure5-3,anelectronicstechnicianorengineercanbuildthecircuitdrawninFigure5-2.Let’slookatanotherschematicdiagram.SeeFigure5-4,below:
FIGURE5-4
CompareFigure5-4toFigure5-3.Thefirstthingtonoticeisasecondresistor.
Ifyouweretobuildthiscircuit,youwouldconnectawirefromthepositiveterminalofthebatterytooneendoftheresistorlabeledR1.YouwouldconnectasecondwirefromtheotherendofresistorR1tooneendofresistorR2.Youwould
connectathirdwirefromtheotherendofresistorR2tothenegativeterminalofthebattery.Youcouldsolderthewireconnections,orusewiresterminatedbyalligatorclipsorspring-loadedclips.Thewirescouldevenberibbon-likecoppertracesonacircuitboard.Thesecondthingtonoticeisthathalfasmuchcurrentflowsnow,comparedto
Figure5-3.Thisisbecausethesame12voltbatterynowhastoworktwiceashard,forcingelectronsthroughtwiceasmuchresistanceasbefore:6ohms+6ohms=12ohms.Twiceasmuchresistancetothesamevoltageleadstohalfasmuchcurrent.Ohm’sLawpredictsthis:I=V/(R1+R2)=12/(6+6)=12/12=1amp.Let’sredrawFigure5-4asFigure5-5,withresistorvalueschanged:
FIGURE5-5InFigure5-5,wearerevealingsomethingstrange.Thereiscertainlynothing
oddaboutlabelingthevoltageacrossthe12voltbatteryasbeing12volts.Butstrangely,weareclaimingthat4voltsappearsacrossthe4ohmresistor,and8
voltsappearsacrossthe8ohmresistor.Arewetryingtoclaimthattheresistors,likethebattery,cancreatevoltage?Absolutelynot.Figure5-5revealsjusttheopposite:inasense,theresistors
takeawayvoltage.Figure5-5exhibitsforustheLawofConservationofEnergy.Inthiscase,alltheenergyputintothesystemisexactlyequaltoalltheenergythatcomesoutofthesystemaswork.Itwouldbehardforyoutocometothisconclusion,becausetraditional
electronicsterminologyhidesthetruth.YoulookatthecircuitofFigure5-5andseethreevoltages.Butthesevoltagesarenotthesame.Itwouldbeniceiftheywerelabeleddifferently,buttheyarenot:theyareallcalled,“voltages,”andmeasuredinunitscalled,“volts.”Intruth,thevoltageacrossthebatteryisonekindofvoltage,andthevoltage
acrosstheresistorsisanotherkindofvoltage.Thevoltageacrossthebatteryisinputenergy(percoulombofcharge).Thevoltageacrosstheresistorsisoutputwork(percoulombofcharge).NowwhenyoulookatFigure5-5,youcanseetheLawofConservationofEnergyinplay.Theinputenergyis12volts,acrossthebattery.Thisexactlyequalstheoutputenergy(work)of4voltsplus8voltsequals12voltsacrosstheresistors.ThelittleplusandminussignsinFigure5-5areatraditionmeanttoflushout
thishiddendifference.Ifyoutraceyourfingerinaclockwisedirectionaroundthiscircuit,youwillfindthattheorderoftheplusandminussignsareoppositewhenencounteringabattery,comparedtoencounteringaresistor.Asyourfingergoesclockwise,whenyourfingerentersabattery,itwilltouchanegativesign,andwhenitexitsabattery,itwilltouchapositivesign.Stillgoingclockwise,whenyourfingerentersaresistor,itwilltouchapositivesign,andwhenitexitsaresistor,itwilltouchanegativesign.StillfocusingonFigure5-5,noticethelabelsA,BandN.Inanelectricalcircuit,
weusuallypickaneutralpoint,whichIhavelabelled,“N.”Theneutralisapointofreferenceforallourvoltagemeasurements.Wechooseittobeour“zerovolts”point.Oncewepickourneutral,allourvoltagemeasurementsarerelativetoneutral.Thereisnoabsolutezerovoltagepoint,onlyarelativezerovoltagepoint.Remember,thebatteryhaspressureonbothends,negativepressureontheanode,andpositivepressureonthecathode.Wetraditionallypickthenegativebatteryterminalasneutral.Thewireleadingtothebottomresistorisalsoneutral.MovinguptheleftsideofFigure5-5,fromNtopointA,thebatterycausesour
circuittogofromzerovoltsupto+12volts.Wenowhave+12voltsrelativetoneutral.Sometimeswesaywehavegained12voltsofelectricalpotential.Youmayremembertheconceptsofpotentialandkineticenergyfromhigh
schoolphysicsclass.AtpointA,ourcircuitnowhasthepotentialenergytodo12voltsworthofwork.Butwhatisthework?Theworkisforcingelectronsthrough4+8=12ohmsofresistance.LooknowatpointBinFigure5-5.Atthispoint,the12voltsofelectricalvoltage
potentialhasaccomplishedsomework:ithasforcedelectronsthroughthetop,4ohmresistor.Wemeasurethatworkas4voltsacrossthe4ohmresistor.Wesaywehadavoltagedropof4volts,becausewebeganwith12volts,butdid4voltsofwork,sowehave12-4=8voltslefttoforcecurrentthroughthe8ohmresistor.Whenwemeasurethe8voltsacrossthe8ohmresistor,wearemeasuringtheworkdonebythebatterytogetthecurrentthroughthe8ohmresistor.Westartedwith12voltsofenergy,completed12voltsofwork,andhavearrivedbackatneutral(N),backatzeroenergy.But,whyisthere4voltsofworkdoneacrossthe4ohmresistor,and8voltsof
workdoneacrossthe8ohmresistor?Well,weknowthatthetotalworkhastoequal12volts,becausethetotalenergyfromthebatteryis12volts,andtheLawofConservationofEnergysaystheworkoutmustequaltheenergyin.Verysimply,it’stwiceasmuchworkforthebatterytoforceelectronsthroughan8ohmresistorthanitistopushelectronsthrougha4ohmresistor.So,wemeasuretwiceasmuchvoltage,8volts,acrossthe8ohmresistor,thanthe4voltswemeasureacrossthe4ohmresistor.Ichose4ohmsand8ohmsformyconvenience,toarriveat4and8volts.But,
iftheupperresistorhadbeen12ohmsandthelowerresistorhadbeen24ohms,westillwouldhavemeasured4voltsacrosstheupperresistorand8voltsacrossthelowerresistor.Thetotalhastobe12volts,andit’stwiceashardtogetcurrentthrougha24ohmresistorasthrougha12ohmresistor,so4voltsmustbemeasuredacrossthe12ohmresistorand8voltsmustbemeasuredacrossthe24ohmresistor.(Ofcourse,lesscurrentwillflowinthecircuitwiththe12and24ohmresistorsthaninthecircuitwiththe4and8ohmresistors.)Asananalogy,it’stwiceasmuchworkforyoutolifta24poundweightasitisforyoutolifta12poundweight.Figure5-5mightremindyouofphysicsconceptsofpushingarockupahill.
TheleftsideofFigure5-5isuphill.Therightsideisdownhill.Youhaveenergyfromthefoodyoueat.(Thebatteryhasenergyinitschemicalstructure.)Youdoworkbypushingarockupahill.(Thebatterydoesworkbyseparatingcharge.)Therocknowhaspotentialenergy.(Thepositiveandnegativeionshaveelectricalpotentialenergy.)Whentherockfallsdownthehill,itreleasesenergyaskinetic,workenergy.(Whentheelectronsgodownthroughtheresistors,theyreleaseenergyaswork-doneenergy).Whentherockfallsbackdownthehilltoitsstartingpoint,itnolongerhastheenergyyouputintoit.(Whentheelectronsgetbacktoneutral,theynolongerhavetheenergythebatteryputintothem.Thebatterymustputenergybackintothemtokeepcurrentflowing.)Youmaythinkwehavegottenoff-track.Yes,thisiselectronics.Butwhatdoes
allthishavetodowithdigital,orbinarysystems?Rightnow,wearegoingtomakeonechangeinthissystemtoturnitintobinary.Lookatthepicturebelow:
FIGURE5-6
Figure5-6isjustlikeFigure5-5,butthebottom,8ohmresistorhasbeen
changedtoa0ohmresistor.Ratherthandrawthejaggedresistorsymbol,Ihavedrawnawire.Awirehas0ohmsofresistance—ornoresistancetocurrentflow—becauseitisaconductor.Infact,Ihavedrawnthesymbolforaclosedswitch.Youhaveusedswitchesthousandsoftimesinyourlife.Aclosedswitchturnsonalightorbrewsthecoffee.Aclosedswitchisjustawire.Weneedtomakesenseofthevoltagemeasurementacrossthewire,the
closedswitch.Thebatteryis,likebefore,12volts.So,thevoltagedropsacrosstheresistorandthewiremustaddupto12volts.Theydo:the12voltsacrosstheresistorplusthezerovoltsacrossthewireequal12volts.Whyisthere0voltsacrossthewire?Because,ittakesnoworkforthebatterytogetcurrentthroughawire.Awiredoesnotresistcurrentflow:itisnotasemiconductor,itisaconductor.Alltheworkthebatterydoesgettingcurrentthroughthecircuitisexpendedontheoneresistor.
Now,let’sopentheswitch.Lookatthepicturebelow:
FIGURE5-7TheonlythingwehavedoneinFigure5-7—comparedtoFigure5-6—is
openedtheswitch.Remember,theswitchisthecomponentonthebottom-rightofourfigure.Whenweopenaswitch,alightgoesoff,orcoffeestopsbrewing.Weeffectivelyremoveawirefromacircuit.Actually,oneendofthewireispushedtotheside,justlikepicturedinFigure5-7.Thecircuitisnolongeracircuit:currentcan’t“circulate.”SuchasimplechangecausessomestrangeresultsinFigure5-7.First,the
resistanceacrosstheswitchisnowinfinity!Thereisnow,effectively,nocomponentwherethewireoftheclosedswitchusedtobe.Theonlythingbetweenthetwocontacts—thedotsinthefigurethatarepointsofcontacttotheexternalwiresofthecircuit—isair.And,airisaninsulator.Insulatorshaveinfiniteresistance.Next,thevoltagemeasurementsinFigure5-7havereversed,comparedto
Figure5-6.Zerovoltsarenowacrosstheresistor,and12voltsarenowacross
theopenswitch.Thisresultisoftennotwhatpeopleexpect.Peopleexpecttofindzerovoltsattheswitchif“nothing”isthere.Instead,wefind0voltsacrosstheresistor,becausenoworkisbeingdone
there.Sincethisisan“open”circuit,nocurrentisflowing.Ifnocurrentisflowingthroughtheresistor,thebatteryisdoingnoworkthere.Next,let’slookatthe12voltsacrosstheopenswitch.Aswewentclockwise
frompointNinthecircuit,throughthebattery,topointA,potentialenergyroseto+12volts.Sincenovoltsdroppedacrosstheresistor(nocurrentflowmeansnoworkdone)thevoltageatpointBmuststillbethesameasatpointA:12volts.Sinceallvoltagesarerelativetoneutral,thatmeanswehave12voltsacrosstheopenswitch.Anotherwaytolookatthisisbycomparingittothe“waterfaucetoff”figure.In
the“off”waterfaucet,nocurrentflows,soallthewaterpressureisappliedtothevalve.Similarly,inFigure5-7,sincenocurrentflows,undiminishedvoltageisappliedtothetopoftheswitch(pointB),relativetothebottom(pointN).YoumaychoosetoviewtherightsideofFigure5-7tobeliketwovoltage
drops,0+12=12volts,addinguptothevoltageriseontheleftsideofFigure5-7.WedidthisinFigures5-5and5-6.Or,youmaychoosetoseenovoltagedrops:noworkhasbeendone,soeverywherewelook—otherthanneutral—wefindpotentialenergy,or12volts.ComparingFigures5-6and5-7,weseegoodreasonforleavingelectricalwork
totrainedpeople.Figure5-7couldbethelightswitchinyourhouse;theresistorcouldbealightbulb;andthevoltagecouldbeadangerous120voltsAC.Anuntrainedpersonmightthinkthat,sincetheswitchisoffandthelightisoff,thentheelectricityisoff,andit’ssafetotouchtheswitchcontacts.WRONG!Thatpersonwouldbepartofalivecircuit,andcouldgetafatalshock.Counter-intuitively,itissafertotouchacrosstheclosedswitchindiagram5-6,sincenovoltageappearsacrossit.Don’tdothiseither:somethingelsecouldbewrongwiththecircuit,soitcouldstillfatallyshockyou.Atthispoint,wehaveabinaryelectricalsystem.Thetwostatesare,physically,
12voltsand0volts.Likewiththefaucetsystem,“on”and“off”arebackwards.Whentheswitchison—makingcurrentflowandalightturnon—thevoltageacrosstheswitchis“off,”or0volts.Whentheswitchisoff—makingcurrentstopandalightturnoff—thevoltageacrosstheswitchis“on,”or12volts.
CHAPTERSIXTRANSISTORS
Unfortunately,theswitch-basedbinarysystemisnotgoodenoughtosatisfyour
needs.Itrequiresahumantofliptheswitch.That’swhyweneedthetransistor.Weneedanelectroniccomponentthatactslikeaswitch,buthasaninputsidethatcontrolswhethertheswitchisonoroff.And,thatinputsidemustbeabletobecontrolledbytheoutputsofothertransistors.Let’slooknowatatransistorcircuit.Seethepicturebelow:
FIGURE6-1
Beforeweproceed,rememberoutgoal.Wewantanelectronicdevicethatacts
likeanelectricalswitch(Figures5-6and5-7),butonethatcanbecontrolledbyotherdevicesofthesamekind(likethefaucetsofFigures4-4through4-7).
InFigure6-1,weintroduceatransistor.Itselectronicsymbolisinthelowerright-handcorner:acirclecontaininganalien-lookingsymbol.Itisathree-terminaldevice,withtheconnectionsnamedS,G,andD,forsource,gate,anddrain.First,let’sgetsomephysicalexercise.Figure6-1separatesneatlyintotwo,
interrelatedpaths.Useyourfingertotraceonepath.Startatthe+terminalofthebattery.Moveclockwise:up,right,thendownthroughtheresistorlabeledRout.Keepgoingthroughthetransistor,enteringthedrain(D),andexitingthesource(S).Godown,thenleft,thenuptothenegativeterminalofthebattery.Thisistheoutputpathofourcircuit.Next,let’stracetheinputpath.Again,startatthe+terminalofthebattery.
Moveclockwise:up,right,thendownthroughtheresistorlabeledRin.Keepgoingthroughthetransistor,enteringthegate(G),andexitingthesource(S).Godown,thenleft,thenuptothenegativeterminalofthebattery.Asyoutraceeachofthesetwopaths,trytoseethateachoneresemblesthe
kindsofcircuitswesawinFigures5-5,5-6,and5-7.Imaginethevoltagerisingontheleft,thenfallingontheright,asitprogressesthroughtheresistorandthetransistor.Noticehowbothpathsinvolvethetransistor,butthroughdifferententrypoints.Wewillhavemuchtosayabouttheinterrelationshipofthesetwopaths.ThekindoftransistorIhavechoseniscalledanN-channelenhancement-mode
MOSFET(metal-oxidesemiconductorfieldeffecttransistor).Ichoseitbecauseitistheonethatmostresemblesthewaterfaucetmodelabove,andbecauseitiscommonlyusedinmicroprocessorsduetoitslowpowerconsumptionandfastswitchingspeed.Here’showthistransistorworks.Applyingavoltageatthegatethatismore
positivethanthevoltageatthesourcecausesconventionalcurrenttoflowfromthedraintothesource(electronsactuallyflowtheotherway,buttrytoforgetthat).Thegreaterthegate-to-sourcevoltage,thegreaterthedrain-to-sourcecurrent.That’sallyouneedtoknowforabasicunderstandingofthistransistor.So,whatcanwedowithtransistors?Well,foronething,wecanmakea
voltageamplifier.Asmallaudiosinewaveacrossthegate-to-sourcecausesasinewaveofcurrentfromdrain-to-source,whichcausesalargevoltagesinewaveacrossasuitablylargeRoutresistor.Butwecarehereabouttheuseofthetransistornotasanamplifier,butasa
switch.Here’swhatmakestransistorsdifferent,andalittlestrange.WhenwegobacktoourbasicelectronicstheoryofFigure5-3(onebatteryacrossoneresistor),wefindthatcurrentisbeingcontrolledbyourchoiceofvoltageandresistance.Oncewechosea12voltbatteryanda6ohmresistor,theamountofcurrentwasdetermined.Ohm’sLawsaidwewouldget:I=V/R=12/6=2ampsofcurrent(Review:Istandsforcurrent,Vstandsforvoltage,Rstandsforresistance).But,theRoutresistordoesnotcontroltheamountofcurrentflowthrougha
transistor.LookatFigure6-1.+5voltsfromthebatteryisacrossthecombined50
ohmresistorandthedrain-to-sourceofthetransistor.Andyet,the50ohmresistordoesnotaffectthecurrentthroughthatbranch.Ifitwasa100ohmresistor,thesameamountofcurrentwouldflow!Thisupendswhatabeginnerinelectronicsistaught:thatmoreresistancecauseslesscurrent.Wehavetocomeupwithanewnameforthedrain-to-sourcepathofthe
transistor.Wecallitadependentcurrentsource.It’skindoftheoppositeofabattery.Abatteryproducesa(somewhat)constantvoltage,regardlessofwhatcurrentcomesoutofit.Acurrentsourceproducesa(somewhat)constantcurrent,regardlessofwhatvoltageappearsacrossit.So,thecurrentfromdrain-to-sourceisdetermined.Whatdeterminesit?I
alreadytoldyou:thevoltageacrossthegate-to-source.Thedrain-to-sourcecurrentisthesamecurrentthatgoesthroughRout.Yet,thevalueofRoutdoesnotcontroltheamountofcurrentthatgoesthroughitself!Thedrain-to-sourcecurrentcontrolsRout’scurrent,andthedrain-to-sourcecurrentisitselfcontrolledbythegate-to-sourcevoltage.Ifyouwanttobereallyfancy,youcancallthisMOSFETdependentcurrentsourceavoltage-controlledcurrentsource,sincethegate-to-sourcevoltagecontrolsthedrain-to-sourcecurrent.Sincethegate-to-sourcevoltageisthecontroller,whatisthevalueofthegate-
to-sourcevoltage?Well,the+5voltsfromthebatterygoesacrossthecombinedRinresistorandthegate-to-sourceofthetransistor.Butyouneedtoknowthis:theresistanceoftheMOSFETtransistor’sgate-to-sourcepathisnearlyinfinite,likeanopencircuit.IfyoulookbackatFigure5-7andrememberhowvoltagesbehaveinanopencircuit,youwillseethatallthe+5voltsappearacrossthegate-to-source,andzerovoltsappearacrosstheRinresistor.Thisisonereasonthatthistransistorisagoodchoiceformicroprocessorsthat
havemillionsoftransistorspackedtogether.NocurrentflowsthroughRinorthroughthegate-to-sourceoftheMOSFET.Nopower,hencenoheatisgenerateddownthatpath.Controloftheoutputismaintained,notbyinputcurrent,butbytheelectricfieldgeneratedbytheinputvoltage.(Weexplainedthiselectricforcefieldearlierinthisbook.)ThiselectricfieldisinsidetheMOSFET.Thegate-to-sourcevoltagecontrolstheelectricfieldintensity,andtheelectricfieldintensitycontrolshowmuchcurrentisallowedtoflowfromdrain-to-source.That’swhythisdeviceisanFET:fieldeffecttransistor.Toreiterate:+5voltsappearsacrossthegate-to-sourceofthetransistor.From
this,howdoweknowhowmuchcurrentflowsfromdrain-to-source?WelookitupinthedatasheetfortheparticularMOSFETwebought.Let’ssaywefindthatourmodelMOSFETproduces.1ampsfromdrain-to-
sourcewhen+5voltsarepresentfromgate-to-source.Thismeansthat.1ampsalsoflowsthroughthe50ohm,Routresistor.Fromthis,wecancalculatethevoltagedropacrossthe50ohmresistor.WeusealgebratorearrangeOhm’sLaw,I=V/R,sothatitbecomesV=IxR.ThisformofOhm’sLawbeautifullydescribeshowavoltagedrop,V,isthework
done(percoulombofcharge)bytheenergysourceingettingcurrentthrougharesistance.InV=IxR,ifIisafixedvalue,thenincreasingRmeansmoreworkwasdoneingettingthatsameI(current)throughabiggerresistance.Ontheotherhand,ifRisafixedvalue,thenincreasingImeansmoreworkwasdonepushingmorecurrentthroughthesameresistance.Usingthisequation,wefindthatthevoltagedropacrossthe50ohmresistoris:
V=IxR=.1x50=5volts.Ichosethesevaluesonpurpose,becauseIwanted5volts.You’llseewhyinamoment.(Aside:inarealworldcircuit,Iwouldchooseabiggerresistorvalue,toreducepowerconsumption,butthatisanadvancedtopicthatwouldruintheclarityofthistutorial.)Looknowatthepicturebelow:
FIGURE6-2OntheleftIhaveredrawnFigure6-1withallthevoltagesandcurrents.Onthe
rightIhaveredrawnFigure5-6,slightlymodifiedtobemoreequivalenttothecircuittoitsleft.Wejustconcludedthatwehavea5voltvoltagedropacrossthe50ohmresistor.Ifwestartedwitha5voltvoltagerisefromthebattery,andused5voltsofworktogetcurrentthroughthe50ohmresistor,wehave0voltsofworklettogetthecurrentthroughthedrain-to-sourceofthetransistor.Thismeansthatthedrain-to-sourceofthetransistor,withzerovoltsacrossit,isactinglikeawireoraclosedswitch:acomponentwithnoresistance,causingnovoltagedrop.CompareFigure6-2,part(a),withFigure6-2,part(b),toseethismoreclearly.
Allthevoltagesandallthecurrentsintheoutputpathalignexactly.Thetransistorisbehavinglikeaclosedswitch.Itmayhavetakenusmanyparagraphstoexplaintheprocess,buttheresultissimple.NoticealsothattheinputpaththroughRinto
thegateseemstodisappear,sincenocurrentgoesdownit.ThepaththroughRinisimportant,though.Let’schangethatpath.Lookatthe
picturebellow:
FIGURE6-3
ComparedtoFigure6-1,theonlychangeisthatoneendofRinisnow
connectedtoneutral:tothenegativeendofthebattery.Remember,neutralisthe0voltspoint,thereferencepointfromwhichwemakeallourvoltagemeasurements.Wenowhavenovoltagedifferencebetweenthegateandthesourceofthetransistor.Ifyoutraceyourfingerfromthenegativeofthebattery—0volts—andgoupthroughRin,outthetopofRin,turnright,enterthegateofthetransistor,thencomeoutthesourceofthetransistor,youwindupwhereyoustartedfrom:0volts.Reiterating:thereisnovoltagedifferencebetweenthegateandthesourceof
thetransistor.Thedrain-to-sourcecurrentofthetransistoriscontrolledbythe
amountofgate-to-sourcevoltage.Lessgate-to-sourcevoltageproduceslessdrain-to-sourcecurrent.And—thespecificationsheetsforthistransistortellus—novoltagedifferencebetweenthegateandsourceofthetransistormeansnocurrentflowsfromitsdraintoitssource:0amps.Ifthereisnodrain-to-sourcecurrent,itiseffectivelyanopencircuit.Lookatthepicturebelow:
FIGURE6-4Figure6-4,part(a),isarepeatofFigure6-3.Figure6-4,part(b),isarepeatof
Figure5-7,anopenswitchcircuit.Ifyoucomparethevoltagesinthesetwocircuits,youwillnoticethattheirvoltagesexactlycorrespond.Youwillalsonoticethattheircurrentsexactlycorrespond:nocurrentflowsanywhere.YouwillconcludethattheMOSFETtransistorcircuitwith0voltsinputatthegatebehavesexactlylikeanopenswitch.Let’ssummarize,then.AMOSFETtransistorcircuitwith5voltsinputatthe
gatebehavesexactlylikeaclosedswitch(Figure6-2).AMOSFETtransistorcircuitwith0voltsinputatthegatebehavesexactlylikeanopenswitch(Figure6-4).Furthermore,theMOSFETswitchiscontrolledbyinputvoltage,ratherthanahumanhandflippingtheswitch.TheinputvoltagecanbefromotherMOSFETtransistors.Weweregettingsurprisinglyfarwithourbuildingourbinarylogicsystemfrom
thegroundupwithwaterfaucets.Let’splaceafaucetside-by-sidewithourMOSFETtransistorcircuit.Seethepicturebelow:
FIGURE6-5
Closeexaminationrevealshowsimilarthetwocircuitsare.Myhopeisthatyour
understandingofwatersystemsyouhavebeenusingsinceyouwereachildwillhelpyouunderstandthelessintuitivetransistorcircuit.Let’sstartwiththeflow.Imodifiedthewatersystemalittle,tohavethewater
circulateinsteadofcomingfromareservoir.(Otherwise,youwoulddepletethissystemwhenyoudrinkthewater.)Ifyoucomparethewaterflowpathwiththecurrentflowpath,youwillfindthattheycirculateidentically.Noticehow,inpart(a),thewaterthatisapplyingpressuretothevalve’sbuttonisnotflowing(moving).Nevertheless,itisaconduitforthepressurefromthepump.Thesamephenomenahappensin(b).Eventhough0ampsofcontinuouscurrentflowsdowntowardthegateofthetransistor,theredistributionofelectronsonthesourceandgatecausedbythebatterycreatesthegate-to-sourcevoltage.Let’snowcomparethewaterpressuretovoltage.Thepumpisthesourceof
waterpressure,asthebatteryisthesourceofvoltage.InFigure6-5,part(a),pumppressure(transmittedthroughthewater)appliespressuretothevalve’sbutton,turningonwaterflowthroughthefaucet.InFigure6-5,part(b),batteryvoltage(causingaredistributionofelectronsonthesourceandgate)appliesthevoltagethatturnsoncurrentflowthroughtheoutputdrain-to-sourcepath.Also,noticeinFigure6-5,part(b),thatthereisnovoltagedropacrossthe
drain-to-sourceofthetransistor.Thesameholdstrueinpart(a):thereisnowaterpressureonthevalve.ThedifferenceyoumightfindbetweenthetwopartsofFigure6-5isthe
presenceofresistanceinpart(b).But,therereallyisresistancetowaterflowinpart(a).Thepipesthemselvesactasthisresistance.Theskinnierthepipe,themoreresistancetowaterflow,producinglesswaterflow:Flow_rate=1/4xπx(pipe_diameter)2x(water_velocity).Forexample,replacinga
pipewithonethat’shalftheoriginalpipe’sdiametercausesthewatertoflowataquarteroftheoriginalflowrate.Let’snowlookattheno-flowcounterpartstothesystemsinFigure6-5.Seethe
picturebelow:
FIGURE6-6
WefindgreatsimilaritiesbetweenFigure6-6,part(a),the“off”drinking
fountain,andpart(b),the“off”MOSFETtransistorcircuit.Let’slookatcurrents,first.Nocurrentflowsanywhere.Nowatercurrent,noelectroncurrent.Let’slooknextatinputpressures.Neithersystemhasinputpressure.Inpart
(a),theon/offbuttongetsnowaterpressure.Thewatercomingfromthebottomisnotpressurized:itdoesn’tgetpressurizeduntilitcomesoutthetopofthepump.Inpart(b),thegatehasnovoltageinrelationtothesource,becausebothpathsleadtoneutral,ourcircuit’s0voltsreference.Now,let’slookatoutputpressures.Bothsystemshaveoutputpressure.Inpart
(a),thevalve,notbeingturnedon,isblockingthewaterflow.Hence,itisreceivingthewaterpressure.Inpart(b),thedrain-to-source,notbeingturnedon,isblockingdrain-to-sourcecurrentflow.Hence,thedrain-to-sourceisreceivingthebatterypressure.LookingatFigures6-5and6-6onelasttime,wefindthefaucetandtransistor
systemsalmostidentical.Youmerelyneedtosubstitutethewords“waterpressure”and“voltage”,andsubstitute“waterflow”and“current”,tomakethesystems’descriptionssoundthesame.Tosummarize,then,whenwelookatfigures6-2,6-4,6-5,and6-6,wefindthat
ourMOSFETtransistorcircuitbehaveslikeacontrollabledigitalswitch.Wealsofindthatitworksmuchliketheon/offwaterfaucetthatwestudiedearlier.Because
ofthissimilarity,wecanreplaceourearlierfaucet-baseddesignswithtransistor-basedones.Lookatthepicturebelow:
FIGURE6-7
Youmightwonderwherethebatteryis.Electricalcircuitsoftendon’tshowit,for
avarietyofreasons.Thepowersupplyvoltageandneutralareusuallydrawnlikethis,aslabels.Infact,forMOSFETcircuits,5voltsisoftenlabelled“VDD,”and0voltsisoftenlabelled“VSS.”
Figure6-7islikeouroldFigure4-6,fortwofaucets.Inspiteofallthecomplexityinunderstandinghowelectricityandtransistorswork,ourcircuitcanreallyonlydotwothings.Itcanonlybeineitherstate(a),ontheleft,orstate(b),ontheright.RecallthatwerefertothebehaviorinFigure6-7asan“inverter.”+5volts(gate-
to-source)inputgetsinvertedinto0volts(drain-to-source)outputinpart(a).0volts(gate-to-source)inputgetsinvertedinto5volts(drain-to-source)outputinpart(b).Inthepicturebelow,Ihavereplicatedourearlierinvertertruthtableandlogicsymbolthatwedevelopedusingawaterfaucet:
FIGURE6-8Noticehowclearandunclutteredthesetwopicturesare,comparedtothe
actualcircuitinFigure6-7.Thelabels,AandY,shouldhelpyouunderstandhowFigure6-8representstheactualcircuitinFigure6-7.FindthepointsmarkedAandYinFigure6-7.Fromthepointofviewofthelogic,theyaretheonlypointsthatmatter.ThatiswhyFigure6-8iseasiertounderstand:everythingelseinthecircuithasbeenthrownawaytocreateFigure6-8.Ifyouneedabriefreview,Figure6-8,part(a)isthetruthtablefortheinverter.
“1”standsfor“true,”or“itistruethat5voltsispresent.”“0”standsfor“false,”or“itisfalsethat5voltsispresent,so0voltsmustbepresent.”A1isusedinsteadof5becausenotalldigitalsystemsuse5volts.Also,1istraditionalandconvenientintheformalstudyoflogicandBooleanalgebra.ThefirstrowrepresentseverythingyouneedtoknowaboutFigure6-7,part(b).ThesecondrowrepresentseverythingyouneedtoknowaboutFigure6-7,part(a).Figure6-8part(b)displaysthisinformationsymbolically:itletsyouknowthatAistheinputtotheinverter,andYistheoutput.Together,thesetwoitemssay,“0voltsingivesyou5voltsout,”and“5voltsingivesyouzerovoltsout.”Next,let’sredrawFigure4-11,andshowhowonetransistorinvertercancontrol
asubsequentone.Lookatthepicturebelow:
FIGURE6-9Doyourememberthisdiagram?Let’sseehowtoimplementthislogicusing
transistorsinsteadofwatervalves.Lookatthepicturebelow:
FIGURE6-10
Figure6-10isthephysicalcircuitsymbolicallyrepresentedinFigure6-9.TheY-
to-AlineinthemiddleofFigure6-10istheconnectionbetweenthefirstinverterandthesecond.FindwhereIhavelabelledtheresistorsR1andR2,andthetransistorsT1andT2.Thislabellingisstandardpractice,andsaveswordsinthenextparagraphs.First,refertoFigure4-4.SeeingFigure6-10intermsofwaterpressurewillhelp
you.ThinkoftransistorT1asawatervalvethatisturnedoff,sinceithasnopressure(voltage)atitsinput.Sincepressurizedcurrentcan’t“drain”downthroughT1’sdrain,thepressurizedcurrentinsteadappliesitselftotheinput“button”(gate)ofT2.ThisturnsontheoutputcurrentflowdownT2,drain-to-source,removing“pressure”(voltage)there.Nowlet’sspeakpurelyinelectronicratherthanhydraulic,terms.Let’ssayin
wordswhatFigure6-10pictures.Anexternal0volts,probablyfromsomeotherlogicgate,reachesthegateoftheT1.Thisturnsoffcurrentflow,drain-to-source,inT1.Thatbecomesacurrentflowdead-end.YoumightthinkthatcurrentmightinsteadflowacrossfromYtoAandintothegateofT2.But,that’sacurrentflowdead-end,too.Byitshigh-resistancenature,nocurrenteverentersthegateoftheT2.ThatmeansnocurrentgoingthroughtheR1,noworkisdonetoit,andsonovoltagedropsacrossit.Thus,theexternal5voltsbypassesR1,andisapplieddirectlytothegateofT2.Thisturnsthedrain-to-sourceoutputcurrentofT2on.Thatoutputcurrentispulleddownfromthe5voltsupplythroughR2.Wedesignedourcircuitsothatall5voltsofwork/coulombdropsacrossR2.Thisleaves0voltsremainingacrossT2’sdrain-to-source.Or,tomakealongstoryshort,0voltsentersthefirstinverter,and5volts
comesoutofit.That5voltsisappliedtothesecondinverter,and0voltscomesoutofit.
WecanmakeFigure6-10easiertounderstand.Lookatthepicturebelow:
FIGURE6-11Figure6-11isthesamecircuitasFigure6-10.Butremember,wesaid
transistorscanactasswitches,solet’sreplaceT1andT2byswitches.SinceT1isoff,wereplaceitwithanopenswitch,asseeninFigure6-4.SinceT2ison,wereplaceitwithaclosedswitch,aseeninFigure6-2.Now,wehavesimplifiedfromthecomplicatedtransistortothesimplerswitch.Butnext,wecanmakethiscircuitsimpler,still.Lookatthepicturebelow:
FIGURE6-12
Nowwehavetrulysimplifiedthecircuit.Figure6-12isthesimplificationofFigure6-11,whichitselfsimplifiedtheactualcircuitrepresentedbytheschematicinFigure6-10.Lookbackatpart(a)ofFigure6-11.T1’soutputisanopenswitch.Anopenswitchisforallintentsandpurposes,nothing.Itisair.Nocurrentgoesthroughit.Inasense,it’snotthere.So,inFigure6-12,part(a),Ididn’tdrawit.Next,lookbackatpart(b)ofFigure6-11.T2’soutputisaclosedswitch.A
closedswitchis,forallintentsandpurposes,nothingbutawire.So,InFigure6-12,part(b),Idrewawireleadingtoneutral.TherewasnoneedtodrawR2orthe5voltsfeedingit,becausetheydon’taffecttheoutput.T1andT2’sgateinputsaresuperhighresistances,sotheydon’tallowinput
current(althoughtheydoaffectoutputcurrent).ThisisanotherreasonnottodrawT1orT2.Conceptually,thisishowsimplethecircuitinFigure6-10trulyis.Let’sstep
throughFigure6-12.Weseethat0voltsentersfromtheleft,asA.WithT1theoreticallygone,the5voltsfromthepowersupplycomesinfromtheupperleft,goesoutoftheleftinverter’sYoutput,andenterstherightinverter’sAinput.Finally,0voltscomesoutoftheYoutputofinverter2,becausenovoltageeverappearsacrossawire(Remember?Noworkisneededtomoveelectronsthroughnoresistance.)Thetricktosimplifyingthesecircuitsistonoticethattheoutputsideofeach
inverterdividesintotwohalves:aswitchandneutralonthebottomhalf,andaresistorand5voltsonthetophalf.(SeeFigures6-2and6-4.)But,iftheswitchison,theoutputreducestothewireandneutralonthebottomhalf.Iftheswitchisoff,theoutputreducestotheresistorand5voltsatthetop.Now,let’slookatthecircuitinFigure6-9again,butthistimewithalogical1,or
5volts,enteringonthefarleft.Seethepicturebelow:
FIGURE6-13
ThistimewewillskipthestepsfromFigure6-10—drawingthecircuit—and
Figure6-11—replacingthetransistorswithswitches.WewillgodirectlytothestepinFigure6-12—drawingthesimplifiedresult.Seethatresultinthepicturebelow:
FIGURE6-14Figure6-14istheultra-simplifiedversionofwhat’sinsideFigure6-13.Weknow
thatFigure6-13isaninvertercontrollinganotherinverter.WeknowthattheseinvertersareMOSFETtransistors.WefollowtherulesoutlinedabovetosimplifyFigure6-13intoFigure6-14.5voltscomesintotheleftinverter/transistor(thetransistorswitchison),sowesimplydrawawiretoneutral.Neutral’s0voltscomesintotherightinverter/transistor,keepingthetransistorswitchoff;sowesimplydrawaresistorto5volts.That5voltsexitstherightinverter.So,ultimately,thetransistorcircuitprovidesthenextcircuitwitheitherapathto
zerovolts,orapathto5volts.Wehavepressureornopressure;onoroff;digital;binary.Let’stakeanotherlookatourORgate,thistimeusingtransistors.
Asaquickreference,IhaveredrawnthetruthtableandlogicdiagramoftheORgatedirectlybelow:
FIGURE6-15
RecalltheconceptunderlyinganORgate.Ifoneormoreinputsare1(true,
high),theoutputis1.NowlookatthetransistorversionoftheORgate,picturedbelow:
FIGURE6-16
Figure6-16displaysthefirstlineofthetruthtableoftheORgate,asseenin
Figure6-15,part(a).WhenboththeAandBinputsarelow(zerovolts),theYoutputislow.Thisistheonlyconditioninwhichtheoutputislow.ReferbacktoFigure4-12toseethewaterfountainversionofthiscircuit.Itwillhelptogiveyouafeelforthecircuitflowsandpressures.InanalyzingFigure6-16,wefindthatbothT1’sandT2’soutputdrain-to-source
currentflowsareturnedoff.That’sbecausebothT1’sandT2’sinputgate-to-sourcevoltagesarelow.YoushouldnowcoverT1andT2withyourthumbs:makethemdisappear.Sincetheyarenowbehavinglikeopenswitches,theyareeffectivelygone,fromthepointofviewoftheiroutputsides.Theonlythingyoureyes—andtheinputtoT3—seeareR1,R2,and5volts.Don’tlettworesistors(R1andR2)andtwo5voltsconfuseyouThereisreallyonlyone5volts,labelledtwiceforconvenience.And,R1andR2aren’tdoinganythingatthemoment,sincenocurrentflowsthroughthem.The5voltsisapplied(gate-to-source)toT3.ItturnsonturnsT3’sdrain-to-sourcecurrent,makingitactlikeaclosedswitch.Sinceaclosedswitchhasnovoltageacrossit,0voltscomesoutofT3.IfyouprefertolookatFigure6-16likeawaterfaucetsystem,thinkofT1and
T2aswatervalvesthatareturnedoff,sincetheyhavenopressure(voltage)attheirinputs.Sincepressurizedcurrentcan’tdraindownthrougheitherT1orT2,thepressurizedcurrentappliesitselftotheinput“button”(gate)ofT3.ThisturnsontheoutputcurrentflowdownT3,drain-to-source,removing“pressure”(voltage)there.Let’slookatlinenumbertwooftheORgate,asshowninFigure6-15,part(a).
Thepicturebelowdemonstrateslinenumbertwo:
FIGURE6-17
Summarily,ifanORgatehas0voltsinputtoA,and5voltsinputtoB,5volts
willexitY.TransistorT2,inFigure6-17,seemstobehavenormally.5voltsinputintoitsgateturnsonT2’sdrain-to-sourcecurrent,causing5voltstodropacrossR2,andnovoltstodropacrossT2(drain-to-source),theclosedswitch.ThebehavioroftransistorT1,however,isanythingbutnormal.(Itmayhelpif
youreviewFigure4-14,thewaterfaucetsystem,tounderstandthistransistorsystem.)T1has0voltscomingintoitsgate.Hence,nocurrentflowsdownT1’sdrain-to-source.Whenthishappens,weexpectR1tohavenovoltagedrop,andT1’sdrain-to-sourcehaveafivevoltdrop.Butinstead,wefindbothvoltagesaretheopposite:R1hasa5voltdrop,andT1’sdrain-to-sourcehasa0voltdrop.Whyisthisso?ThereasonfortheoppositevoltagesbehavioraroundT1isthatthe5volts
aboveR1hasanalternatepathtopushcurrentthrough.(SeethedashedlinesinFigure6-17,tofollowthepathsofcurrentflow.)Remember,eventhoughT1isoff,
T2ison.Thecurrentfromthe5voltsupplygoesthroughR1,thenthroughT2insteadofT1.SincecurrentgoesthroughR1,workisdone,sovoltageisdropped.SincethecurrentavoidsT1,itappliesnopressure(voltage)toT1,sowemeasures0voltsdrain-to-source.Ifyouwerepayingverycloseattention,younoticedthatIchangedtheresistor
valuesaboveT1andT2from50ohmsto100ohms.Thisisabitadvanced,buthere’swhyIdidthat.TheT2wehavebeenusingpullsdown.1amps.Inthiscase,itispullingitthroughtwo,equal-valuedresistors,R1andR2.The.1ampfromthe5voltsupplysplitsevenly:.05ampsgoesdownR1,and.05ampsgoesdownR2.Thismakesthevoltagedropacrosseach100ohmresistor:V=IxR=.05x100=5volts.The5voltsvoltagedropacrossRoutisnowthesameasinourinvertercircuit,with0voltsleftacrossthetransistors’drain-to-source.Let’slookatlinenumberthreeoftheORgatetruthtable,asshowninFigure6-
15,part(a).Thepicturebelowdemonstrateslinenumberthree:
FIGURE6-18
Summarily,ifanORgatehas0voltsinputtoB,and5voltsinputtoA,5voltswillexitY.Iwon’tspendmuchtimeonthiscircuit,sinceitbehavesexactlylikeFigure6-17:likelinetwoofthetruthtable.Theonlydifferenceisthattheinputvoltagesarereversed.Thesingle5voltsinputisappliedtoAinsteadofB.Thebehaviorsarethesame.Thistime,though,T1absorbsallthecurrentflowcomingthroughR1andR2,sinceT1isturnedon.T2absorbsnone,sinceitisturnedoff.Theresult,5voltsoutofY,isthesameasinFigure6-17.Let’slookatlinenumberfouroftheORgatetruthtable,asshowninFigure6-
15,part(a).Thepicturebelowdemonstrateslinenumberfour:
FIGURE6-19Summarily,ifanORgatehas5voltsinputtoB,and5voltsinputtoA,5volts
willexitY.ThiscircuitisactuallyeasiertounderstandthantheprevioustwoinFigures6-17and6-18.NeitherT1’snorT2’scircuitvoltagesare“foolingus”intothinkingtheyareon,whentheyarereallyoff.T1andT2reallyare“on”thistime,sincetheybothhave5voltsappliedtotheirinputs(gate-to-source).T1andT2
eachconductcurrent,behavelikeclosedswitches,oractlikewaterfaucetsthatareturnedon(seeFigure4-15,ifthathelpsyou).But,likeinFigures6-17and6-18,theendresultisthesame.SinceallcurrentthroughR1andR2isdrainedawayfromthegateofT3,nopressure(voltage)canbeappliedtoT3.Itstaysoff.Itsoutputcurrentstaysoff.Pressure(voltage)from5volts—throughR3—buildsupatT3,drain-to-source:atY.(Warning:youmightwanttoskipthisparagraphandthenexttwo,becausethe
topicisabitadvanced.)ThechangeofR1andR2to100ohmssolvedaproblemforuswhenonlyR1oronlyR2conductedcurrent.But,havewejustintroducedanewproblem?Let’sdothemath.IfT1pullsdown.1ampandR1is100ohms,thenOhmsLawsaysV=IxR=.1x100=10voltsofworkisdonegettingcurrentthroughR1.WecouldsayexactlythesamethingaboutT2andR2.Doesn’tthatbreaktheLawofConservationofEnergy?Aren’tweaccomplishingmorework(10voltspercoulomb)thanenergysupplied(5voltspercoulomb)?Wecan’tbreakthelawsofnature.TheLawofConservationofEnergy,andthe
transistoritself,preventsthisfromhappening.Thetransistorwillself-limititscurrentflow.Thetransistorwillcutbackoncurrentflow,downtothepointwhere0voltsdropsacrossit(drain-to-source)andallthe5voltsofsupplyvoltagedropsacrosstheresistor.Thus,ratherthan.1amps,T1willdraw.05ampsthroughR1,thenintoitself.ThiswillcreateV=IxR=.05x100=5voltsworkdoneacrossR1,andnonedoneacrossT1.T2willdothesame.Becauseoftheabovecharacteristicoftransistors,weusuallychooseamuch
highervalueofdrainresistorthanthe50or100ohmswehavebeenusing.Astheresistorgetshigher,thetransistor’sdrain-to-sourcecurrentgetslower.Lesscurrentmeanslesspowerconsumption.Thismeanslessheat.Whenweareputtingmillionsofthesetransistorcircuitsinamicroprocessor,wemustminimizeheat.Wehavecoveredthreeofthefundamentallogicgates:theinverter(Figure4-
10),theORgate(Figure4-16),andtheNORgate(Figure4-21).Weneedtocoverjustafewmore.But,wearegoingtotakeashort-cut.Rememberthataninverter,initssimplestform,isjustaone-transistor,oneresistorcircuit.Pictorially,wecansay:
FIGURE6-20Figure6-20impliesthat,ifwewantto,wecandrawthesimplerinverterlogic
diagraminpart(b),inplaceofthemorecomplicatedcircuitdiagraminpart(a).Withthisshort-cut,werealizethatwecandrawtheORgatecircuitfromFigures6-16,6-17,6-18,and6-19inthefollowing,morecompact,forminpart(a):
FIGURE6-21
TodrawFigure6-21,part(a),allIdidwasreplaceeachtransistor-resistorpair
fromFigures6-16,6-17,6-18,and6-19withtheinvertersymbol.Now,Figure6-21,part(a),iscertainlymuchsimplerthanthoseweencounteredinFigures6-16,6-17,6-18,and6-19.ButitisnotsimplerthanthelogicsymbolfortheORgateinFigure6-21,part(b).So,whydidIbothertodothis?Ididitsothatyoucouldseeanexampleofourapproachfortheremaininglogic
gates.Ratherthangothroughthelengthycircuitsdrawingsandcircuitanalyses,wewillsimplydesigntheremaininglogicgateswithinverters.Afterall,digitalelectronicsandmicroprocessorsareprettymuchalltransistors.Ifyoucanjustgetcomfortablethinkingofeachinverterasatransistor/resistorcircuit,youwillhavenolossinunderstanding.ThenextlogicgatewewanttostudyistheANDgate.Thetruthtableandthe
logicsymbolfortheANDgateareinthepicturebelow:
FIGURE6-22Remember,eachoneofthefourrowsofthetruthtableinpart(a)isapossible
stateoftheANDgate,drawninpart(b).Ineachrow,AandBrepresentapairofinputstates;Yrepresentstheoutputstateforthoseinputs.ItiscalledanANDgatebecauseonlywhenAandBareboth1(true,high,5volts)willtheoutputYbe1.Findthatstateinthefourthrowofthetruthtable.Anyotherpairofinputsproducesa0(false,low,0volts)output.Therearemultiplewaysofmakinglogicgatesfromtransistors.Ifwewantto,
wecanmakeanANDgatethefollowingway:
FIGURE6-23
InFigure6-23,onlywhenbothT1andT2areturnedon(by5voltsatAandB)
willcurrentflowthroughR1,T1andT2.OnlythenwillT3beturnedoff,producing5voltsatY.Thiswouldbelikehavingonewaterfaucetwithtwovalvesandtwobuttonsyouwouldhavetopresstoturnonthewater.Let’snotgothatroute.Eventhoughthisisamoreefficientdesign,let’sjust
continuedesigningallofourgateswithoursamefundamentalbuildingblock,thetransistor/resistorinverterofFigure6-20.Ourgoalhereisnotforyoutobecomeadesignerofoptimallyefficientlogicgates.Ourgoalisforyoutounderstandhowmicroprocessorswork.Wewantminimalconfusion,andIamafraidthatdesigningdifferentcircuitsforeachgatewillconfusematters.Plus,Ifindbeautyinthesimplicityofbuildingourmightymicroprocessorfromonesimplecircuit.BelowisapictureofhowtocreateanANDgate,usingourshort-cutmethodof
drawingonlyinverters.Remember:thinkofeachinverterasourtransistor/resistorcircuitofFigure6-20,part(a).
FIGURE6-24InFigure6-24,Ihavelabeledthesixtransistor/resistorcircuits(inverters)with
numbersinsidetheinvertertriangles.Outsidethetriangles,IhavelabeledthelogicstatesforrowfouroftheANDgatetruthtable:logic1’s(5volts)ontheAandBinputsproducingalogic1ontheYoutput.Thisoneisprettyeasytofigureout,sinceeachinvertertakeswhat’sontheinputandproducestheoppositeontheoutput.FortheANDcircuit,Iwillonlyshowonemorelineofthetruthtable:linethree.
Seethepicturebelow:
FIGURE6-25LinethreeofthetruthtableforanANDgatesaysthata1(5volts)ontheA
inputanda0(0volts)ontheBinputproducesa0ontheYoutput.Youshould
noticesomethingfunnyaboutinverternumber3:logic0(0volts)onitsinputproduceslogic0onitsoutput.Itdoesn’tinvert.Andyetinverternumberfourdoesproducethecorrectoutput:alogical1(5volts)onitsinputproducesalogical0onitsoutput.Itdoesinvert.Itshoulddawnonyouthattheycan’tbothworkcorrectly.Ifinverter3produced
a1atitsoutputandinverter4produceda0atitsoutput,youwouldhavetheinputtoinverter5besimultaneously1and0.Logically,itwouldbelikesomethingbeingtrueandfalseatthesametime.Voltage-wise,itwouldbelikehavingboth5voltsand0voltsatthesameplace.So,whydoesinverter4winthelogicbattlewithinverter3,sothatitproduces
thecorrectoutput,forcinginverter3toacceptthe(forit)wrongoutput?Youalreadyknowtheanswer(Theofftransistorininverter3can’tbuilduppressure,becausecurrentbypassesitandheadstotheontransistorininverter4.)ReferbacktoFigure6-17,ifyoudon’tremember.Inverters3,4,and5ofFigure6-25areexactlythesameastheonespicturedinFigure6-17.Reviewthatmaterial,ifyouneedto.Inverters1,2,and6,arejusttransistor/resistorpairsaddedbeforeandafterthatcircuit,whichyoualreadyunderstand.ThenextlogicgatewewanttostudyistheNANDgate.Thetruthtableandthe
logicsymbolfortheNANDgateareinthepicturebelow:
FIGURE6-26ThenameNANDgateisshortforNot-ANDgate.Comparethetruthtablefor
theNANDinpart(a),above,withthetruthtablefortheANDinFigure6-22,part(a).YouwillfindthattheNANDisliketheANDwitheachrow’sYoutputinverted.That’swhythelogicsymbolfortheNAND,inpart(b),above,looksjustlikethelogicsymbolfortheAND,butwithabubbleaffixedtotheYoutput.Thebubblesymbolizesthattheoutputisinverted.Putintowords,aNANDgateproducesa0output(false,low,0volts)onlywhenboththeAandBinputsarehigh.
Lookatthesimplified,inverter-stylediagramfortheNANDgate,below:
FIGURE6-27PerhapsyourememberedthewayweturnedanORgateintoaNORgate,way
backinFigure4-18.WeaddedaninvertertotheoutputofanOR.RatherthanaddingaseventhinvertertotheoutputoftheANDgate,inFigure6-24,wesimplyremovedthelastone.Itgivesthesameaffect.Usingthissametrickofremovinganinverterinsteadofaddingone,let’srevisit
Figure6-21.Thatisaninverter-stylediagramofanORgate.Ratherthanaddinganinvertertotheoutputofthelastinverter,tocreateaNORgate,wecanremovethelastinverter,instead.WestillcreateaNORgate,anditlooksverysimple,asyoucanseeinthepicturebelow:
FIGURE6-28
ThenextlogicgateweshallstudyistheXORgate.ThetruthtableandthelogicsymbolfortheXORgateareinthepicturebelow:
FIGURE6-29
OnewaytodescribethisXORgateisthatitstruthtablelooksjustlikethetruth
tableforanORgatewithoneexception:thefourthrow’soutputis0.Anotherwayistosaythata1intoAorB,butnotboth,producesa1outofY.But,thebestwaytodescribethetruthtableinvolveslookingateachrowseparately.Foreachrow,countthenumberof1’sontheinputs.Ifyoucountanoddnumberof1’s,thentheYoutputwillbea1.Ifyoucountanevennumberof1’s,thentheYoutputwillbea0.No1’sisanevennumberof1’s,sorownumberonewillhavea0outputonY.Rownumbertwohasonlyone1,intheBcolumn.Oneisanoddnumber,sotheYoutputofrowtwois1.Thereasonweusethismoreelaboratewayofdescribingthebehaviorofthe
XORgateinvolvessomethingIhavenotyetexplained:gates(exceptforinverters)arenotlimitedtotwoinputs.Youcanhavethreeormoreinputs.However,fortheAND,OR,NAND,andNORgates,extrainputsarenota“bigdeal.”Theirbehaviorsarealogicalextensionoftwo-inputgates.Briefly,forthreeinputs,A,B,andC,wehaveeightpossiblerowsofatruth
table.Athree-inputANDgatebehaveslikeatwo-inputANDgate:onlythelastrowhasaYoutputof1(Figure6-30,part(b));a1isproducedonlywhenA,B,andCinputsare1’s.Athree-inputNANDgatebehaveslikeatwo-inputNANDgate:onlythelastrowhasaYoutputof0;a0isproducedonlywhenA,B,andCinputsare1’s.Athree-inputORgatebehaveslikeatwo-inputORgate:onlythefirstrowhasaYoutputof0(Figure6-30,part(a));a1isproducedwhenA,B,orCinputsare1’s.Athree-inputNORgatebehaveslikeatwo-inputNORgate:onlythefirstrowhasaYoutputof1;a0isproducedwhenA,B,orCinputsare1’s.
LookatthepicturebelowtoseewhatImean:
FIGURE6-30ThebehaviorofXORgatesaswemovefromtwoinputstothreeormore
inputs,isnotsoeasilysummarized.Lookatthepictureofthethree-inputXORgateinpart(a),below:
FIGURE6-31LookingatthefirstfourrowsofFigure6-31,part(a),yourecognizethesameY
outputsasthefourrowsofFigure6-28.But,theYoutputsofthenextfourlinesofFigure6-31arethereverseoftheYoutputsofthefirstfourlinesofFigure6-31.Becauseofthis“strange”behavior,weusethemorecomplicateddescriptionoftheXORgatebehavior.Anoddnumberof1’sontheinputsproducesa1ontheoutput.Anevennumberof1’sontheinputsproducesa0ontheoutput.Athree-inputversionofagateiseasytodraw.Seethepicturebelow:
FIGURE6-32Internally,toaddthethirdinput(C),wesimplyaddanewtransistor/resistor
inverterbehindtheCinputline,andattachitinternallythesamewaytheAandBinvertersareattached.ThelastlogicgateweshallstudyistheXNORgate.Thetruthtableandthe
logicsymbolforthe2-inputXNORgateareinthepicturebelow:
FIGURE6-33
Asyoumightpredict,theXNORgateistheXORgatewithitsoutputinverted,
foreachlineoftheircorrespondingtruthtables.Thebubbleontheoutputofthelogicsymbolalsoindicatesthis.WedescribethebehavioroftheXNORgatebysaying:anoddnumberof1’sontheinputsproducesa0ontheoutput.Anevennumberof1’sontheinputsproducesa1ontheoutput.Refertothethree-inputXNORtruthtable,inFigure6-31,part(b),toseewhythisdescriptionisnecessary,andtoprovetoyourselfthatitworks.Let’slookatthecircuitthatcreatestheXORgate.Lookatthepicturebelow:
FIGURE6-34
Atfirstglance,Figure6-34mightdisturbyou.Youexpecttoseeacircuitforthe
XORgate,andinsteadyouseethreeothergates,connectedtogether.Butremember:allofthesefiguresarepictorialorsymbolicwaysofexplaininghowourbasictransistor/resistorinvertercircuitsareconnectedtogether.WealreadyknowallwereallyneedtoknowaboutthebehavioroftheXORgatefromthetruthtableinFigure6-29.So,welearnhowtheXORgateworksbynavigatingthroughseverallevelsof
diagrams.WestartwiththelogicsymbolinFigure6-29,part(b).WelearnthatthecircuitinsidethisbehaveslikethethreeinterconnectedgatesinFigure6-34.WerememberthattheNANDgateinFigure6-34behaveslikethefiveinterconnectedinvertersinFigure6-26;theANDgatebehaveslikethesixinterconnectedinvertersinFigure6-24;andtheORgatebehaveslikethethreeinterconnectedinvertersinFigure6-21.Finally,werememberthattheinvertercircuitrepeatedfourteentimes—butconnectedinveryspecificwaysdescribedbythesediagrams—issimplytheactualcircuitdescribedbyFigure6-20.Thisisanimportantmomentinyourunderstandingofmicroprocessors.You
havejustfoundthat,fromthebasicbuildingblockofthetransistor/resistorinverter,webuildthebuildingblockscalledgates.Fromthesebuildingblocks,webuiltamorecomplexbuildingblock,theXOR.Wewillkeepbuildingmorecomplexbuildingblocksfromsimplerblocks,untilwehaveawholemicroprocessor.OnelastpointconcerningFigure6-34:noticethe0’sand1’sIhaveplacedon
theinputsandoutputsofthegates.IhavesetupforyouademonstrationoflinenumbertwoofthetruthtableforanXORgate.Weknowthata0ontheAinputanda1ontheBinputproducesa1ontheYoutput.Partofthefunofdigitalelectronicsiswatchingtheflowofthelogicasitripplesthroughthegates.Testyourknowledgeofthetruthtablesforthegatesthatmakeupthiscircuit.Makesureyouunderstandwhyeach1or0appearswhereitdoes.TrysolvingfortheotherthreelinesoftheXORtruthtable.
CHAPTERSEVENLATCHES
Thelogicgateisoneofthetwobasicbuildingblocksofdigitalcircuitry.The
otherbasicbuildingblockisthelatch.Justasthereareseveralkindsoflogicgates—AND,OR,etc.—thereareseveraltypesoflatches—D,RS,clockedRS,JK,etc.Thelatchalsohasasibling,theflip-flop,whichwewillencounterlater.Whatisalatch?Alatchisthefundamentalunitofstorageinalogiccircuit.A
latchstoresonebit.Whatdowemeanbystorage?Whenwedelvedeeperintomicroprocessors,
wewillfindthatmuchofwhatgoesoninvolvesmovinginformationaround.Agroupofbitsmovesfromthekeyboardintothemicroprocessor;fromthemicroprocessortothevideodisplay;fromtheharddrivetothesystemmemory,etc.InformationmovesfrompointAtopointB.Thepointis,onceitarrivesatpointB,itmust“stick”there.Itmuststaythere
untilwechoosetoreplaceitwithnewinformation,anewgroupofbits;those,too,must“stick”thereatpointB.Furthermore,whenwemoveinformationfrompointAtopointB,theinformationdoesnotdisappearfrompointA.It“sticks”there,too,untilwechoosetochangeit.Thus,whenwe“move”agroupofbitsfrompointAtopointB,wearemakinganexactcopyatpointBofthebitsthatareatpointA.ThistemporaryreplicationandretentionofinformationfromtheAgroupoftransistorstotheBgroupoftransistorsis“storage.”Whydoweneedstorage?Microprocessorsaresequentialdevices.Things
happeninanorderlyprocess:step1happens,followedbystep2,etc.Furthermore,step2willoftenoperateontheinformationinvolvedinstep1.Itcan’toperateonitifitisgone.Itcanonlyoperateonitifit(step1)isstored.Forexample,microprocessorscanaddtwo8-bit(8-transistor)numbers
together.Thisisasequentialoperation:stepAhappensattime1;stepBhappenslater,attime2;andstepChappenslater,attime3.Ifstep1putsnumberAinstorageareaA,andstep2putsnumberBinstorageareaB,step3needsgroupAandgroupBtostillbetherewhenitaddsAtoB.There’sanotherreasonmicroprocessorsneedstorage.Thefirstreason,above,
hadtodowiththingshappeningsequentially.Thesecondreason,below,hastodowithavoidingthingshappeningsimultaneously.Forreasonsofefficiency,microprocessorsystemsoftenhaveonedeviceconnectedtomanydevices.Seepart(a)inthepicturebelow:
FIGURE7-1
Part(a),abovedescribesasourcedevice,labelledS,connectedtotwo
destinationdevices,labelledD1andD2.ImagineyouareS.Youarebinary.Youcommunicateonecommand—eitherTfortrueorFforfalse—byholdingupasign.Onesideofthesignismarked,T;theothersideismarked,F.D1andD2areyourtwoco-workers.Theyarealsobinary.D1respondstotheT
signbyshuttingdownthenuclearplant;herespondstotheFsignbynotshuttingdownthenuclearplant.D2respondstotheTsignbyfiringthenuclearmissiles;sherespondstotheFsignbynotfiringthenuclearmissiles.Now,imagineinFigure7-1,part(a),thatSfindsoutaboutafailureatthe
nuclearpowerplant,andmusttellthattoD1,soD1canshutdownthenuclearpowerplant.Asshownabove,SdisplaystheTsideofthesign.D1shutsdownthenuclearpowerplant.Unfortunately,D2alsoseestheTsign.Sinceshehasnowayofknowingtheinformationisnotintendedforher,shefiresthenuclearmissiles.Armageddonfollows.So,weneedtemporarystoragedevicesatD1andD2.Whenweneedtoshut
downthenuclearpowerplant,weneedtobeabletoopenupadoorintoD1—butnotintoD2—andstoreaTcommandsignwithD1,untilitissafeforhimtocomeoutofshutdown.SincewedidnotopenupthedoorintoD2,shestillretainsanFcommandsign,soshedoesnotfirethenuclearmissiles.Now,lookatFigure7-1,part(b).Inasimpleone-to-onesystemlikethis,S
couldjustsitthereaslongasnecessarywiththeTinformation,becauseithasnothingelsetodo.D1doesnothavetobeastoragedevice;D1canbeagate.But,lookingbackatFigure7-1,part(a),Sdoeshavesomethingelsetodo.ShastocommunicatewithD2,separatelyfromD1.SoD1andD2mustbestoragedevices:latches;theycan’tbegates.Furthermore,D1andD2mustbemorethanjuststoragedevices:theymustbe
selectablestoragedevices.Ialreadymentioned“openingadoor”beforestoringinformation.IfD1andD2wereassimpleasshowninFigure7-1,part(a),wewouldwindupwiththesameproblemwestartedwith:whenwestoreaTatD1,aTwouldalsobestoredatD2,andthemissileswouldincorrectlybefired.So,thephysicaldesignofourlatchcircuitmustincorporatetheabilitytobeselected:theabilitytohaveitsdooropened.Lookatthepicturebelow:
FIGURE7-2
Figure7-2,part(a),showsthebehaviorwewant—thenuclearplantshutdown,
andthenuclearmissilesnotfired.Toaccomplishthis,wemustaddsomeadditionalcontrolcircuitry,externaltoourstoragecircuitry.Ourcontrolcircuitry,labelledC,isthe“dooropening”sendingcircuitry.WheneverShasa1or0tostoreineitherD1orD2,Cmustsenda1tothe“dooropening”receivingcircuitry,labelledE,builtintothedesiredlatch.IfCsendsa0toeitherD1,D2,orboth,theoutputofSisignoredbyD1,D2,orboth,respectively.Let’stracethroughhowthisworksinFigure7-2,part(a).SsendsouttheT
(true)sign.However,sincethecontrolcircuit,C,hassenta0toD2’sEinput,D2can’treceivetheT;the0onEclosesD2’sdoor.Noticethat,eventhoughD2hasaTatitsentrance(input),theTisnotatitsexit(output).Ontheotherhand,D1doesreceivetheT,becauseitsdoorisopen.Noticethat
D1hasaTatitsentrance(input),andtheTpassesthroughtoitsexit(output).Itpassesthroughbecausethecontrolcircuit,C,hassenta1toD1’s“dooropener.”The1onitsEopensD1’sdoor.TheoutputsofD1andD2willstayatthelogiclevel—TorF—thatwaspresent
attheirinputsthelasttimethelasttimetheirdoorwasopenedwithalogic1on
theirEinputs.D1andD2ignorethestateoftheirinputswhenthedooropenerisclosedwithalogic0.Youmaywonderwhywegothroughallthiseffort.Iclaimedthisisdonefor
greaterefficiency.But,itmaylooklikelessefficiencytoyou,becausewehaveaddedmorewirepaths,notless.And,wehaveaddednewcontrolcircuitry,aswellastheneedformorecomplexityinsideourflip-flops.However,lookatFigure7-2,part(b),above.Typically,wearenotsendingone
bitofinformationfromStoitsdestinations,asinpart(a).Inpart(b)IhavedrawnSneedingtosendsixbitsofinformation,simultaneously,toeitherD1orD2.Ifthedesignofpart(b)didnotincludetheselect-and-storedesignelementsofpart(a),Swouldneedtwelvelinescomingoutofit.Lookatthepicturebelow:
FIGURE7-3
InFigure7-3,part(a),wehaveusedtheselect-and-storetricksofFigure7-2,
part(a).(Wehaven’tdrawnthatextracontrolcircuitry,topreventconfusion.)Usingthesetechniques,weareabletotransferandstoreeightbitsofinformation—onebyte,bydefinition—toeitherD1,D2orD3.WehavekeptthenumberoflinescomingoutofStojusteight.Alineisacopperwire,oracoppertraceonacircuitboard.Perhapsitisapinorleadstickingoutofanintegratedcircuitchip(IC).NowlookatFigure7-3,part(b).Here,wehavenotusedtheselect-andstore
tricksofFigure7-2,part(a).Now,Smusthavetwenty-fourseparatelines.ThoselinesaretotallydedicatedtomaintainingtheoutputsofD1,D2,andD3.Theycanneverbeusedforanythingelse.Now,imaginearealmicroprocessorsystem.Smightberequiredtosendtoten
devices:D1throughD10.InsteadofsendingeightbitstoD1throughD10,S
mightsendsixty-fourbits.Since64x10=640,SinFigure7-3,part(b)wouldhave640linescomingoutofit.Thiswouldcreateanimpossiblyhugemicroprocessor.UsingFigure7-3,part(a),Swouldhavesixty-fourdatabitconnections:amuchmoremanageablenumber.Beforewemoveontodescribinghowwewillbuildourlatch,let’stakea
momenttoappreciatethewonderandstrangenessofwhatwearedescribing.Wearetalkingaboutinformationmovingaround,onitsown,fromonetinyplacetoanother.It’slikeyouwritingamessage,makingacopyofit,walkingthecopytoafriend’shouse,andhandingittothefriend.But,inthemicroprocessor,thereisno“you.”Itallhappensautomatically,undermachinecontrol.Wearetalkingaboutcreatingapatternorsequenceofvoltages(5volts)and
non-voltages(0volts),intransistors.Thiswholeconceptofvoltagesishardenoughtocomprehend.Voltageis“pressure-like.”Wehaveonebattery,butmanyvoltages.Then,amazingly,wemovethispatternsomewhereelse,toadifferentgroupoftransistors.Thevoltageswereinoneplace,andnowtheyareintwoplaces.Now,itistimetodesignourlatch.Ofcourse,therearedifferentwaystobuilda
latch,butIenjoytheeleganceanduniformityofbuildingoursystemfromthesamebuildingblock,thetransistor-resistorinverterseeninFigure6-20.Lookatthepicturebelow:
FIGURE7-4Figure7-4isthefirststepinbuildingourlatch.Thefirstthingtonoticeisour
basictransistor-resistorinverter,repeatedfourtimes,andlabelledT1throughT4.Next,noticehowthedrainsofT1andT2areconnectedtogether.Wehave
seenthisarrangementbefore.IfyoulookbackatFigure6-28—twoinverterswiththeiroutputsconnectedmakingaNORgate—andrealizefromFigure6-20thataninverterisourbasictransistor-resistorcircuit,youwillrealizethatT1andT2havebeenconnectedtocreateaNORgate.SinceT3andT4areconnectedthesameway,draintodrain,theytoohavebeenconnectedtocreateasecondNORgate.Third,noticehowtheoutputoftheT1-T2NORgateconnectstothegateinput
ofT4.Symmetrically,theoutputoftheT3-T4NORgateconnectstothegateinputofT2.Fourth,noticethattheinputgateofT1islabelledS,andtheinputgatetoT3is
labelledR.TheseareourSetandResetinputs,ourmeanstocontrolthelogic
stateofthelatch.Fifth,theoutputofNORgateT1-T2islabelledQwithalineaboveit,or“NOT
Q.”TheoutputofNORgateT3-T4islabelledQ.Qisourstoredoutputbit.NOTQistheoppositeofQ,meaningifQis1(5volts),NOTQis0(0volts).IfQis0(0volts),NOTQis1(5volts).WewillsoonignoreNOTQ.Itcomesinhandyforindividual,stand-alonelatchesindigitalelectronics,butmicroprocessorsusuallyinvolveonlytheQoutputsofparallelcollectionsoflatches.Lookatthepicturebelow,toseewherewearesofar:
FIGURE7-5
Part(a),inFigure7-5istheratherdulllogicsymbolfortheRSlatch.It’svery
high-level:itonlyshowsthetwoinputs,setandreset,ontheleft;andthetwooutputs,QandNOTQ,ontheright.Part(b),inFigure7-5,isamuchneaterandtidierversionofFigure7-4.WhenweanalyzedFigure7-4,wespentawholeparagraphrevealingthetransistorsconnectedasNORgates,andalloftheotherconnections.Figure7-5,part(b),hidesthetransistorsinsidetheNORgates,sowecan
betterviewtheconnections.Thediagraminpart(b)helpsusseethat,strangely,theoutputofeachNORgatefeedsbackintotheinputoftheotherNORgate.Also,noteinpart(b)thatwherethelinescrisscross,theydonottoucheachother.Onelinehopsovertheother.Whenlines(wiresorcircuitboardtraces)aremeanttoconnecttoeachother,weusuallydrawalittleblackcircle.Let’sstartwithanoverviewofhowthislatchworks.Itisnotourfinished
product,becausethisRSlatch,thoughitstores,isnotselectable.Itdoesn’thavetheEcontrolofFigure7-2.RefertoFigure7-6,below,asyoureadthefollowingsummary.
Normally,theRandSinputsarebothlow.Whenwewanttostorea1(5volts)inthelatch,weraisetheS(Set)inputto1.Thelogic1appearsatQ.WepulltheSbackto0(0volts),andthestoredlogic1staysatQ.Again,normally,theRandSinputsarebothlow.Whenwewanttostorea0(0
volts)inthelatch,weraisetheR(Reset)inputto1(5volts).Thelogic0appearsatQ.WepulltheSbackto0,andthestoredlogic0staysatQ.Wehavenamesforthestatesofthelatch.ThesetstatemeanstheQoutputis
storinga1.Wecanuse“set”asaverb:thelatchhasbeensetto1.TheSlabelstandsfor“set.”TheresetstatemeanstheQoutputisstoringa0.Wecanuse“reset”asa
verb:thelatchhasbeenresetto0.TheRlabelstandsfor“reset.”TheholdstateoccurswhenbothRandSinputsare0.Thelatchisneither
beingcommandedtoSet,nortoReset.So,itisholding—orstoring—thelaststateitwascommandedtobein,whentherewasa1oneitherRorS.Thelatchshouldneverhavea1(5volts)atboththeRandSinputs,atthe
sametime.Underthoseconditions,thelatchisbeingtoldtosetandresetatthesametime.Qisbeingtoldtobeat0voltsand5voltsatthesametime,tobesimultaneouslytrueandfalse.Thisisknownastheillegalstate,andproducesunpredictableresults.WecanconstructabrieftabletosummarizethebehaviorofourRSlatch.See
thepicturebelow:
Figure7-6
UseFigure7-6tohelpyourememberthecontentoftheparagraphs
immediatelyprecedingit.Aswithpreviouslogictables,eachrowrepresentauniqueoutputstateandtheSandRinputsthatcauseit.ThequestionmarksinlinefourofFigure7-6reflecttheunpredictableresultsoftheillegalstate.Ourfinaldesignwillrenderreachingthisstateimpossible.Thusfar,weseehowalatchworksfromtheoutside:fromthepointofviewof
externalinputsandoutputs,andfromlogictables.But,whatisthesecret,whatisthemagictrick,thesleightofhandinsidethatmakesitwork?Forthat,weneedtopeerinsidethecircuitry.Let’sdothatbylookingatthepicturebelow.
Figure7-7
Let’sdemonstratethethirdlineofthetruthtablefromFigure7-6.Itsaysthat
applyinga1totheSinputstoresa1attheQoutput.Hopefully,bynow,youarecomfortablementallyreplacinga1with5voltsanda0withzerovoltsasyoulookatFigure7-7.Ihavelabelledthesequenceofeventsas“a”through“i”intheabovefigure.Thelabel1-ameansthat,atthatlocation,thefirststep—a—ofthesequencehappens;andthelogiclevelatthatlocationis1(5volts).At1-a,5voltsisappliedtotheSetinput.T1turnson,likeaclosedswitch,
bringingT1’soutputto0volts(see0-b).IfyourecallourearlierlooksattheparallelconfigurationofT1andT2,youknowthatitdoesn’tmatterwhatvoltagesarearoundT2.“Thelowvoltagealwayswins,”atthedrainjunctionofT1andT2.(ReviewFigures4-13and6-17:theoffvalve/transistorcan’tbuilduppressure,becausecurrentbypassesitandheadstotheonvalve/transistor.)So,theNOTQoutputisat0volts,whichlooksgoodforthetruthtablerowwearetryingtoprove.At0-c,0voltsisappliedtothegateinputofT4.T4turnsoff,likeaclosed
switch,potentiallybringingitsdrainoutputto5volts(see1-d).Isay,potentially,becauseifT3ison,its0voltsoutputwouldover-rideT4’s5voltsoutput(“thelowvoltagealwayswins”attheT3-T4junction).However,T3isnoton.TheRinputtoT3is0volts(0-e),keepingT3off(1-f).Remember,itwouldbeillegalforRtobeat5voltswhenSisat5volts.So,theQoutputisat5volts,whichalsolooksgoodforthetruthtablerowwearetryingtoprove.But,westillhavethreeconcerns.One,theSinputof5voltswillgoaway,
becoming0volts;howwillthisaffectQandNOTQ?Two,howisthe5voltsstoredatQ:bywhatmechanismdoesit“stick”there?Three,whereisthemagictrickthatmakesthisstoragehappen?Allthreeofthesequestionsarevariationsofthesamequestion,anditsanswer
isatstep1-g.Weleftourcircuitat1-dand1f,with5voltsthere,sinceT3andT4arebothoff.That5voltsisappliedat1-g,tothegateinputofT2.Here’swherethe“trick”happens.The1-astepofapplying5voltstothegateofT1hasjustbeenreplicatedatthegateofT2(1-g).Ithappensinstantly,eventhoughittookmemanywords.T2turnson(0-h),justlikeT1ison.Theybothpulltheirdrainstothe0voltsstate.However,onlyoneofthemisrequiredtomaintainthatlowvoltagestate.Remember,“Thelowvoltagewins,”attheoutputsofthesekindsofcircuits?So,theinputatSintothegateofT1cannowsafelyreturnto0volts(0-i),becauseT2isnowdoingT1’sjobofholdingQat5voltsandNOTQat0volts.Atstep0-i,wehavearrivedattheholdstate,lineoneofthetruthtable,sincebothRandSinputsareat0volts.Thelatchis“holding”theresultoftheSetstate.WecoulddoasimilaranalysisoflinetwooftheRSlatchtruthtable,reworking
Figure7-7fortheResetstate,byplacing5voltsattheRinput,and0voltsattheSinput.But,sincetherightsideofthecircuitisamirrorimageoftheleftside,theanalysiswouldbeidentical,butwithoppositeresults:RwouldmakeQequal0volts,andNOTQequal5volts.Infact,ifwewenttoFigure7-7andrelabeledRasS,SasR,QasNOTQ,andNOTQasQ,wecouldusethesamediagramandthesameanalysistodescribelinetwoofthetruthtable.Instead,let’suseFigure7-5,part(b),ahigher-levelabstraction,toanalyzeline
twooftheRSlatchtruthtable.Lookatthepicturebelow:
FIGURE7-8
Figure7-8,part(a),displaystheactofresettingtheRSlatch.(Remember,logic
1means5voltsforourdesign,andlogic0means0volts.)5voltsisappliedtotheRinputofthelatch,andentersNORA.ReferbacktothelogictablefortheNORgate,foundinFigure4-20,part(b).ThetruthtabletellsusthatifoneinputofaNORgatehas5voltsonit,theoutputisautomatically0volts.Itdoesn’tmatterwhattheotherinputis.So,NORA’soutput,whichistheQoutputofthelatch,is0volts.ThatistheexpectedresultfortheResetoperation:Qisresetto0volts,bydefinition.Noticethatthatsame0voltsfeedsbacktooneinputofNORB.Theotherinput
ofNORBisalso0volts.ThetruthtabletellsusthatifallinputsofanNORgateare0volts,theoutputmustbe5volts.So,5voltscomesoutofNORB.ThatistheexpectedresultfortheResetoperation:NOTQis5volts,theoppositeofQ’s0volts,bydefinition.Sofar,sogood.But,theRinputmustgobackto0volts,incasethelatchneedstobeSetinthe
future.Itcan’tbeSetbyapplying5voltsatSwhile5voltsarestillatR:thatwouldbetheillegalstate,withunpredictableresults.Now,wecanobservethe“trick”thatmaintainsandstorestheresultofthe
Resetstate.Stilllookingatpart(a),noticethatthe5voltsthatweanalyzedascomingoutoftheoutputofNORBfeedsbacktotheotherinputofNORA.ThatmeansthatNORAnowhasbothinputsat5volts.ThetruthtabletellsusthatifbothinputsofNORAareat5volts,0voltscomesoutofNORA.But,NORAdoesn’tneedbothinputstobeat5volts,itonlyneedsoneinputtobeat5voltstoproducea0atitsoutput.It’ssafe,thenfortheResetinput,R,ofthelatchtoreturnto0volts.TheRinput
ofNORAnolongerneedstobe5volts,becausetheotherinputofNORAisnowat5volts.That’sthe“trick”thatmaintainsQat0voltsandNOTQat5volts.You
canobservethisinFigure7-8,part(b).TheRinputisnowbackto0volts.TheSinputalwayswasat0volts.Wehaveenteredtheholdstate,andthelatchisholdingorstoringtheresultoftheResetstate.Thoughittookmanywordstodescribethereplicationofthe5voltsfromtheRinputofNORAintoNORA’sotherinput,ithappensveryquickly.TheRinputonlyneedsabriefpulseof5voltstostorethe0voltsattheQoutput.Ourlatchdesignworkswell,butitisunfinished.Itneedscircuitrybuiltintoitthat
allowsittobeselectable,aswewitnessedinFigure7-2,part(a).Ourlatchmaybeoneofmanylatches,allwiththeirSetbitsconnectedtogether,andallwiththeirResetbitsconnectedtogether.Theyallmaybeconnectedtoonesourcebitofinformation.Thesourcemustbeabletoselectjustonelatchtosendinformationto.Thecorrectlatchmustbeabletoreceiveit,andtheotherlatchesmustbeabletoignoretheinformationnotmeantforthem.Let’slookfirstatthepicturebelow:
FIGURE7-9
Figure7-9,part(a),isourhighlevellogicsymbolforourfinishedlatchdesign.Notice,ithasanewname.ItisnowaDlatch,insteadofanRSlatch.TheDstandsfordelay.TheDlatchhastwoinputs,DandE,and2outputs,QandNOTQ.NOTQis
alwaysintheoppositelogicstateofQ,soI’llignoreit,tosavetime.Thetruthtableinpart(b)explainshowtheDlatchworks.Again,welookatseparatebehaviorsofatruthtableonerowatatime.Again,alogiclevelof1means,forourdesign,5volts;a0logiclevelmeans0volts.WeintroducedtheletterEinFigure7-2.Estandsforenable.Eisthevoltage
inputthatenablestheDinput.WhentheEinputis5volts,asseeninrowstwoandthreeofthetruthtable,theDinputvoltageappearsattheQoutput.So,0voltsonDappearsas0voltsonQ(truthtablerowtwo).And,5voltsonDappearsas5voltsonQ(truthtablerowthree).Irepeat,thesetransfersonlyoccur
whentheEinputisat5volts.Whathappens,then,whenEis0volts?The“x”inrowoneofthetruthtable
means,“don’tcare.”Itmeans,wedon’tcarewhatinputisonD,becausetheDinputisignored,itisblocked.Thedoorisclosed.TheDinputvoltagedoesnotcrossovertotheQoutput.TheQoutputholdswhatevervoltagewaslaststoredtherewhenEwas5volts.So,whateverishiddeninsidetheboxthattheElineconnectstoinFigure7-9,
part(a),holdsthesecrettoourlatch’sabilitytobecorrectlyselectedandstoredtobythesourceofinformation.Let’sopenupthatbox.Itsmysteriesarerevealedinthepicturebelow:
FIGURE7-10
Figure7-10isourfinishedlatch.NoticefirstthatouroldRSlatchisontheright
side:NOR1andNOR2,connectedthesameway.So,weknowournew,Dlatchcanstore.Ontheleftisnewcircuitry,whichallowsourDlatchtoeitherbeselectedorignored.NoticehowIhavechangedthelabellingofRto“wasR,”andSto“wasS”.Theirbehaviorshaven’tchanged,butthenameofthelatchhas.ThisisaDlatch,sowereallyshouldnotbeusingRSlabels.YouwillnoticewenowhaveaDexternalinputonthefarleftside,whichreplacestheoldRandSexternalinputs.Also,wehaveournewcontrolinput,calledE.Youknowitspurposefromtheabovediscussion.WealreadyknowhowtherightsideofFigure7-10works.5voltsat“WasS”
setsQto5volts;5voltsat“WasR”resetsQto0volts.0voltsatboth“WasS”and“WasR”makesQholdormaintainthepreviouslystoredvoltagebit.Let’slookatthatinverter,labeledI,ontheleftsideofFigure7-10.Theinverter
allowsustocompresstwoinputs,RandS,downtooneinput,D.LookbackatFigure7-6,thetruthtablefortheRSlatch.Noticethatinrowstwoandthree,theRandSinputsareinoppositestatesfromeachother.Inotherwords,inrowtwo,
Sis0andRis1:opposites.Inrowthree,Sis1andRis0:opposites.Wedon’tneedrowsoneandfour.Rowfourisillegal,andasourceofpotentialtrouble.OurEinput,aseparatecircuit,willperformtheholdstate,sowedon’tneedrowone.Aninverteralwayshasitsinputandoutputoppositeeachother.So,wewireit
asshowninFigure7-10toreplacetwoinputs,RandS,withoneinput,D,whichhasaninverteroutputofNOTD.TheDinputtakesontheroleoftheoldSinput.TheNOTDoutputoftheinvertertakesontheroleoftheoldRinput.ThatleavesustoexplainhowtheEcircuittakescareoftheholdstate’sfunctionality.ThetaskoftheEcircuitistoblockinputdataDfromgettingto“WasS”and
“WasR”.WhenEisat0volts,theEcircuitmustkeep“WasS”and“WasR”at0volts,regardlessofthevoltageatD.When“WasS”and“WasR”arebothat0volts,NOR1andNOR2willbeintheholdstate.TheEcircuitaccomplishesthistaskviatheAND1andAND2gates.Oneway
oflookingatanANDgateisasa“pass/block”circuit.Lookatthepicture,below:
FIGURE7-11
LookattheANDgatetruthtableinFigure7-11,part(a).Ihavecircledthefirst
tworows.Inboththeserows,theAinputis0volts.Noticethat,nomatterwhatthevalueisattheBinput,theYoutputis0volts.Youcanwatchthisbehaviorplayingoutinpart(b).TheAinputis0volts;theBinputischangingfrom0voltsto5volts,repeatedly.Nevertheless,theYoutputstaysstuckat0volts.TheBinputisblockedfromreachingY,whenAis0volts.NowlookattheANDgatetruthtableinFigure7-11,part(c).Ihavecircledthe
lasttworows.Inboththeserows,theAinputis5volts.NoticethatwhatevervoltageisattheBinputappearsattheYoutput.Youcanwatchthisbehaviorplayingoutinpart(d).TheAinputis5volts;theBinputischangingfrom0voltsto5volts,repeatedly.TheYoutputexactlymatchestheBinput.WhenBis0volts,Yis0volts.WhenBis5volts,Yis5volts.TheBinputpassesthroughtotheYoutput,whenAis5volts.This“pass/block”functionalityisexactlywhatwewantinourlatchdesign.Look
oncemoreatFigure7-11.ThewaytheAinputcontrolstheinformationflowisexactlywhatwewantourEinputtodo.Now,lookbackatFigure7-10,ouractualDlatchcircuit.ThinkoftheEinputas
thecontrollerofinformationflowto“WasR”and“WasS.”WhenEis5volts,itputsAND1andAND2inthe“passthrough”mode.Then,ifDis5volts,AND2letsitpass,and“WasS”becomes5volts.Also,theinvertermakesNOTD0volts,soAND1letsitpass,and“WasR”becomes0volts.WearenowattherightsideofFigure7-10,whichisouroldRSlatch,withvoltagesthatmatchrowthreeofitstruthtable(Figure7-6).Ofcourse,thismeansQbecomes5volts.Again,let’slookatthescenariowhereEis5volts,puttingAND1andAND2in
the“passthrough”mode.Thistime,though,assumeDis0volts.AND2letsitpass,so“WasS”alsobecomes0volts.Also,theinvertermakesNOTD5volts,andAND1letsitpass,so“WasR”becomes5volts.WearenowattherightsideofFigure7-10,whichisouroldRSlatch,withvoltagesthatmatchrowtwoofitstruthtable(Figure7-6).Ofcourse,thismeansQbecomes0volts.Lastly,let’slookatthescenariowhereEis0volts.Now,EputsbothAND1and
AND2intheblockedstate.Boththeiroutputsbecomestuckat0volts.WearenowattherightsideofFigure7-10,whichisouroldRSlatch,withvoltagesthatmatchrowoneofitstruthtable(Figure7-6).Ofcourse,thisistheholdstate,whichmeanstheQoutputmerelymaintainswhatpreviousdataitheld,regardlessofwhatvoltageisatDorNOTD.NowthatyouknowhowtheDlatchworksinternally,let’slookathowthe
microprocessoruseslatches.WeintroducedtheseconceptsinFigure7-2,part(a),toexplaintheneedforselectablestorage.Then,weusedtermslikesourcedeviceanddestinationdevice.Now,let’sreviewthisprocessmorerealistically,usingD,Q,andElabelsfromourlatchtutorial,andfromthepointofviewofamicroprocessorcommunicatingwithitslatches.
AssumetherearetwoDlatches:latchAandLatchB.Thepicturebelowmayhelp:
FIGURE7-12
Ifthemicroprocessorwantstosenda1tolatchA,itplaces5voltsontheDline
(wire/trace).Then,themicroprocessorraiseslatchA’sE0lineto5volts.Then,themicroprocessorlowerstheE0lineto0volts.ThisE0lineisuniquelyforlatchA;itisfornootherdevice.LatchAnowstoresthelogic1,delivering5voltstoitsownQoutput.Next,assumethemicroprocessorwantstosenda0tolatchB.Itplaces0volts
ontheDline(wire/trace).Then,themicroprocessorraiseslatchB’sE1lineto5volts.Then,themicroprocessorlowerstheE1lineto0volts.ThisE1lineisuniquelyforlatchB;it’sfornootherdevice.LatchBnowstoresthelogic0,delivering0voltstoitsownQoutput.Afterthesetwosteparecomplete,latchAisstoringalogic1,andlatchBis
storingalogic0.NotethatbothlatchAandlatchBsharethesame,one,wiredconnectioncalledD,fromthemicroprocessor.However,latchAandlatchBdonotsharetheEline.Eachlatchgetschosenbyitsown,uniqueEline.Aswehavedescribedearlier,asinFigure7-3,part(a),anditsassociatedtext,
inamicroprocessorsystem,weusuallywanttostoremanybitsatthesametime,ratherthanonebitatatime.InsteadofsendingtolatchA,thenlatertolatchB,weusuallysendtolatchgroupA,thentolatchgroupB.It’snotunusualforalatchgroupconsistof64bits.Let’sdesigna4-bitDlatch.An8-bit,16-bit,32-bit,or64-latchwouldlook
similar.Seethepicturebelow:
FIGURE7-13
This4-bitDlatchissimpletodesignandunderstand.Youshouldrecognizeour
1-bitDlatchrepeatedfourtimes.AllfouroftheElinesaretiedtogether,andconnectedtotheoneEinputline.ThefourDlines,however,arekeptseparate.Thus,eachDlatchinthegroupcanstoreitsownbitofinformation,receivedfromitsownDinput.But,allfourcanbeloadedatthesametime,fromoneEline.Notice,too,thefouravailableDlatchoutputs,Q0throughQ3.Withthisdesign,ifQ0istheonlyoutputthatmustchange,Q1throughQ3mustbere-loadedwiththeirpreviousvalueswhenQ0isloadedwithitsnewvalue.Anotherconsiderationforourdesignsofbothgatesandlatchesistheeffectof
connectingoutputstogether.Lookback,now,atFigures7-1through7-3.Remember,forreasonsofefficiency,detailedintheparagraphsaroundthosefigures,wefoundwehadtoaccommodateonesourceofoutputvoltageconnectingtomanydestinationsofinputvoltage.Theoppositearrangementisalsocommon.Seethepicturebelow:
FIGURE7-14Thisnew,opposite,arrangementis:manysourcesofoutputvoltageconnecting
toonedestinationofinputvoltage.Figure7-14,part(a),demonstratesthatarrangement.Part(b)showswhatproblempart(a)overcomes.Ifwecouldnotselectandstorewithlatches,thedestinationwouldneedalineforeverysourceline,24linesinthisexample.Ifeachsourcehad64bits,andthereweretensources,thedestinationwouldneed640lines(wiresortraces).Figure7-14,part(a),showsthree8-bitlatchsources(S)connectingtoone8-bit
latchdestination(D).Insteadof24lines,thedestination(D)inpart(a)onlyrequireseightlines.Thedestination(D)needstohaveacopyofthevoltagescontainedinonlyoneofthethreesources(S).NotshowninFigure7-14,part(a),isthecontrolcircuitrynecessarytomake
surethatonlyonesource(S)atatimeisselectedtodeliveracopyofits8bitstothedestination(D),whiletheothertwosourcesareturnedoff.Ihavealsonotdrawnallofthelineconnections,topreventchaosandconfusion.But,Ididdrawoneoftheeightconnections.Followthearrowstoseethedirectionofvoltagetransfer.But,howdoweturnonoroffoutputvoltagesinthesources?Unfortunately,
withthecircuitwehavebeenusingthusfar—ourbasictransistor/resistorinverter—itcan’tbedone!0voltsstoredatany“on”outputtransistorwoulddefeatthe5voltsstoredatany“off”transistor.Whenconnectedtogether,outputvoltagescontaminate,andinsomedesignsdestroy,eachother.Weneedare-designattheexitofanygateorlatchwithoutputstiedtogether.
There-designwillenablethegateorlatchtoeffectivelydisappear,fromthepointofviewofothergatesorlatches.Theonelatchorgatethatdoesnot“disappear”canthensendvoltagestothedestination,withoutcontaminationordestruction.Weneedasecondtypeoftransistorforthisnewdesign.Lookatthepicture
below:
FIGURE7-15
ThetransistorinFigure7-15iscalledaP-channelenhancement-mode
MOSFET.Comparethiswiththeonewehavebeenusing,theN-channelenhancement-modeMOSFET,asseeninFigure6-1.Youwillfindthatthisnewoneislikeaverticalmirrorimageoftheoldone.NoticethatIhavedrawnthisnew
oneabovetheresistor;Ihaveplacedthesource(S)atthetopandthedrainatthebottom;thearrowinsidethecirclepointsoutwards.Themostimportantthingstonoticearehowthevoltagesandcurrentsare
reversed,comparedtotheoldN-channeltransistor.LookatFigure7-15,part(b).Theconventionalcurrentflowsfrom5voltstoground,asbefore;butnow,itentersthesourceandexitsfromthedrain.Also,toturnonthesource-to-draincurrent,thegatemustnowbemademorenegative(0volts)thanthesource(5volts).Thesource-to-drainthenactsasaclosedswitch,with0voltsacrossit.Now,lookatFigure7-15,part(a).Toturnoffsource-to-draincurrent,thegate
mustnowbemadethesame(5volts)asthesource(5volts).Thesource-to-drainthenactsasanopenswitch,with5voltsacrossit.AllthesebehaviorsarethereverseofwhatweencounteredwiththeN-channeltransistor.Let’snowlookatanewinverterdesign.Lookatthepicturebelow:
FIGURE7-16
Thefirstthingtonoticeinournewinverterdesignisthattheoldresistorhasbeenreplacedbyasecondtransistor,T1.T1isaP-channelenhancement-modeMOSFET.T2remainsunchanged;itisanN-channelenhancement-modeMOSFET.Noticealsothattheirgatesarewiredtogether,thenwiredtotheinputvoltage,A.Finally,noticethattheirdrainsarewiredtogether,thenwiredastheoutput.Wecouldhavebuiltallofourgatesandlatcheswithtwotransistors,anN-
channelandaP-channelenhancement-modeMOSFET,wiredinthisway.Ichosenotto,fortworeasons.One,Iwantedtoteachthroughacomparisonoftransistorswithwaterfaucets,andwaterfaucetsdonotworkthisway.Second,thiscircuitishardertounderstand,involvingtwodifferenttypesoftransistors.Understandingitdependsmoreonelectronictheorythanhydraulics.Youshouldbemorecomfortablenowwiththeunderlyingelectronictheory.You’llseeshortlywhywenowneedthiscircuit.Lookatthepicturebelow,sowecanexplorehowthisnewinverterdesign
works:
FIGURE7-17Ihavedrawnthesamecircuittwice,sowecanstudyitsbehaviorwith5volts
input,thenwith0voltsinput.ThefirstthingtonoticeaboutFigure7-17isthatthiscircuittrulyisaninverter.Inpart(a),5voltscomesin,and0voltscomesout.Inpart(b),0voltscomesin,and5voltscomesout.Let’sseehowthishappens.Inpart(a),5voltsisappliedtobothgates.T1—theP-channeltransistor—turns
off,sinceitsgatevoltageisthesameasitssourcevoltage.Itactslikeanopenswitch.Recallthatanopenswitchisnothingbutair.Thatpartofthecircuiteffectivelydisappears,asIhaveindicatedinpart(a)withthecrossed-outcircle.
Stillinpart(a),the5voltsappliedtothegateofT2,theN-channeltransistor,turnsiton.Draintosource,itactslikeaclosedswitch,likeawiredpathtoneutral(0volts).That0voltsappearsattheoutput.The5voltsatthesourceofT1istotallyblocked.Turningnowtopart(b),0voltsisappliedtobothgates.T2,theN-channel
transistor,turnsoff,sinceitsgatevoltageisthesameasitssourcevoltage.Itactslikeanopenswitch.Recallthatanopenswitchisnothingbutair.Thatpartofthecircuiteffectivelydisappears,asIhaveindicatedinpart(b)withthecircle.Stillinpart(b),the0voltsappliedtothegateofT1,theP-channeltransistor,
turnsiton.Draintosource,itactslikeaclosedswitch,likeawiredpathto5volts.That5voltsappearsattheoutput.The0voltsatthesourceofT2istotallyblocked.Thereis,however,athirdthingwecandowiththisinverterthatwecouldnotdo
withourresistor/transistorinverter.Toseethisfeature,lookatthepicturebelow:
FIGURE7-18
InFigure7-18,Ihaveremovedtheconnectionbetweenthetwogates.Inow
cancontrolthetwotransistorsseparately.So,Iapply5voltstothegateofT1,turningofftheP-channelFET.Fromthepointofviewoftheoutput,T1isgone.Next,Iapply0voltstothegateofT2,turningofftheN-channelFET.Fromthepointofviewoftheoutput,T2isgone.Infact,fromthepointofviewoftheoutput,thewholeinverterisgone!Thisdisappearingactissometimesreferredtoasthehi-Zstate,meaninghighimpedancestate,althoughitremindsoneofthecircuitgoingtosleep,asin“catchingsomeZ’s.”Thisishowwecanhavemanydigitalvoltageoutputsconnectedtogether
withoutthevoltagesaffectingeachother.Wesimplymakeunusedoutputsdisappearbyputtingtheminthehi-Zstate.Figure7-18,above,showsusawaytomakeoutputsdisappear.Ourworkisnotyetdone,though.Weneedsomeadditionalcontrolssothat,
whenthiscircuitisactive,itbehaveslikeFigure7-17;andwhenthiscircuitisdisabled,itbehaveslikeFigure7-18.Seethepicturebelow,forthefinisheddesign.
FIGURE7-19
ThecircuitinFigure7-19isoftencalledatri-stateinverter.It’scalledtri-state
becauseitsoutputcanbeinthreedifferentstates:0volts,5volts,andthehi-Zstatedescribedabove.WhentheEninputisat5volts,thecircuitinFigure7-19behaveslikeanormal
inverter.EnstandsforEnabled,anditmeansthattheoutputvoltage,atO,isabletoreachadestinationcircuit.EitherT1orT2isturnedon.Ontheotherhand,whentheEninputis0volts,theoutputvoltage,atO,isunabletoreacha
destinationcircuit.BothT1andT2areturnedoff.Let’sstartwiththelatter,first.WhenEnislow(0volts),theAinputstoboththe
ANDandtheNANDgatesarelow.ThetruthtableforanANDgate,asseeninFigure6-22,showsthatwhentheAinputislow,theYoutputislow.Youdon’tevenhavetobotherlookingattheBinput.This0voltsturnsoffT2.Also,thetruthtableforaNANDgate,asseeninFigure6-26,showsthatwhentheAinputislow,theYoutputishigh(5volts).Youdon’tevenhavetobotherlookingattheBinput.This5voltsturnsoffT1.BothT1andT2areoffwhenEnislow,sothiscircuitbehaveslikeFigure7-18:theoutputvoltagesnolongeraffectcircuitstheyareattachedto.Now,let’sseewhathappenswhenEnishigh(5volts).Thisisalittletrickier.
Whatwewouldlikeisthat,whenEnishigh,theIinputvoltagelevelgetsappliedtothegatesofbothT1andT2.Thisway,itwouldbeactingjustlikeFigure7-17:likeaninverter.Here’swhatactuallyhappens.WhenEnishigh(5volts),ahighlogiclevelis
appliedtotheAinputsofboththeANDandtheNANDgates.FromourearlierdiscussionaboutFigure7-11,werememberthatforanANDgatewiththeAinputhigh,theBinput(fromI)passesthroughandbecomestheYoutput.Thisiswhatwewant.TheIinputbecomesT2’sgateinput.AcarefullookattheNANDgatelogictableinFigure6-26revealsthatfora
NANDgatewiththeAinputhigh,theBinputpassesthrough,flipstotheoppositelogiclevel,thenbecomestheYoutput.Thisisnotwhatwewant.Wedon’twantthisflip.Ifwecouldflipthisflip,thentheIinput’svoltagewouldbethesameasT1’sgatevoltage.That’sthefunctionoftheinverter.TheinverterflipstheIinputtotheopposite
logicstate.But,theNAND(withtheAinputhigh)flipstheIlogicstatebacktoitsoriginalvalueasitpassesfromitsBinputtoitsYoutput.Thus,withEnhigh,theIinputvaluedoes,infactreachbothT1’sandT2’sgates.WithEnhigh,ourFigure7-19circuitbehaveslikeaninverter,andtheoutputvoltageatOaffectsthedestinationcircuit.WithEnlow,ourFigure7-19circuit’soutputatOiscompletelydisconnectedfromanydestinationcircuit.Ifyoudon’twantthecircuitinFigure7-19toinverttheinputlogicasitpasses
fromItoO,thesolutionissimple.ApplytheIinputtoBoftheNAND.Then,attachtheIinputtotheinputoftheinverter,pointtheinverterdownwards,andattachtheoutputoftheinvertertoBoftheANDgate.SeewhatImeanbylookingatthepicture,below,thencomparingittoFigure7-19.Ifthetri-statecircuitdoesnotinvert,itiscalledatri-statebuffer.
FIGURE7-20
Ournexttopicisanotherstunningone.Itiscertainlyamazingthatweareable
tomovevoltagesfromonepartofadigitalsystemtoanother.Or,thinkofwhatisgoingonatthemachinelevelwhenweaddtwonumberstogether.AgroupofbinaryvoltagesismovedtotheAinputofanaddingcircuit;asecondgroupofbinaryvoltagesismovedtotheBinputofanaddingcircuit;thecircuitproducesthesumofAandBasagroupofbinaryvoltagesatitsYoutput.Allofthisisaccomplishedwiththesametwoelectricalcomponentsarrangedasourinverter;thenthoseinvertersarecombinedinpatternswecallgatesandlatches;thenthosegatesandlatchesarearrangedinpatternswecalldigitaladders.ItiscertainlyamazingthatwecanmoveacopyofvoltagesfromsourceAto
destinationB.But,wealsomovethemback,alongthesamewires,fromBtoA.Wecandothiswithonelatch,butusuallywedothiswithagroupoflatches.Thinkofthis.Wecanmoveavoltagepattern,inlogicformas10101010from8-bitlatchAto8-bitlatchB,alongeightwires.Someothercircuitrycanmodifythatvalue(maybesubtractingfromit)inB.Theresultant,newvoltagepatterncanbemovedbacktoA,inthereversedirection,alongthesame8wires!Now,lookbackatFigure7-3.Itshowsonesourcelatchgroupabletopickout
oneofmanydestinationlatchgroups,and“write”toit.Wedefinethewriteoperationasthecopyingofabitpatternfromthecontrollinglatchgrouptoadestinationlatchgroup.Next,lookbackatFigure7-14.Itshowsonedestinationlatchgroupabletopickoutoneofmanysourcelatchgroups,and“read”fromit.Wedefinethereadoperationasthereplicatingorcopyingofabitpatternfromasourcelatchgrouptothecontrollinglatchgroup.Theabilitytocopyvoltagesinbothdirectionsonthesamewiresgivesusthe
powertocombinethecapabilitiesdemonstratedinfigures7-3and7-14.InFigure7-3,thesourcelatchgroupwasthecontroller.InFigure7-14,thedestinationlatch
groupwasthecontroller.Inamicroprocessor-basedsystem,themicroprocessoristhecontroller.Itisboththesourceanddestinationofinformationflow.It“reads”voltagesintoitself,andit“writes”informationelsewhere.Lookatthepicturebelow,inpart(a),showingacomplexsysteminwhichvoltagescanmovebothways.
FIGURE7-21
Ignorepart(b),fornow.LookingatFigure7-21,part(a),weneedtodefine
sometermsandconcepts.First,D1,D2,andD3are8-bitlatchgroups.Thecomponentlabelledthe“CPU”isthecentralprocessingunit:the“brains”ofthemicroprocessor.However,theinternalpartoftheCPUattachedtothe8wiresgoingtoD1throughD3isjustanother8-bitlatch.WewillrefertoitastheCPUlatch.Next,a“bus”isacollectionofwireswithacommonpurpose.Voltagesmove
simultaneously,or“inparallel,”acrossthesewires.WecancalltheeightwiresinFigure7-21,part(a),a“data”bus,sincethegroupofeightvoltagesonitisinformationor“data.”Next,“bi-directional”meansvoltagescanmoveineitherdirectionalongthebus:
fromtheCPUlatchtostorageinoneofthethreeD’s;orfromoneofthethreeD’stostorageintheCPUlatch.EachoftheD’sisan8-bitlatch,orlatchgroup.Don’tthinkoftheDlatchgroupsasonlybeingdestinationlatchesanymore.
TheDnowstandsforthefactthattheyarebuiltfromD-stylelatches.Inearlierfigures,alatchgrouplabelledSwasalwaysasourcelatchgroup,anoutputofvoltages;whilealatchgrouplabeledDwasalwaysadestinationlatchgroup,adestinationforvoltages.Inabi-directionalbussystem,anylatchgroupissometimesasource,andatothertimesadestination.
InFigure7-21,part(a),wealsoneedtodescribesomenewdrawingtechniques.Thearrowwithatailonbothendssignifiesthatvoltagescanmoveinbothdirectionsalongthebus.Thethick,black,verticallineisashortcutwayofdrawingthe8-wiredatabus.Therearetrulyonlyeightuniquewiresinoursystem,here,eventhougheachwiresplitsthreewaysasitheadsouttothethreeD’s.Itisdifficulttodrawthisthree-wayspliteighttimes,soweoftendrawthethicklinetostandfortheeightlines,thendrawtheeightlinesemergingfromthethickline.Thereisno“thickwire.”IfyoulookbackatFigure7-3,oratFigure7-13,youwillnoticethat,ina
standardlatch,foreveryinputline,weneedanoutputline.NoticeinFigure7-21,part(a),IhavenotdrawneightlinesontherightsideofeachDlatchgroup.Idon’tneedtodrawthem,becausetheydon’texist:eachinputandoutputsharesthesameline.Withoutthebi-directionalbus,Iwouldneedtwiceasmanywires:IwouldneedtheadditionaleightwirescomingoutoftherightsidesofeachoftheD1throughD3latchgroups,thenmergingtobecomeeightuniquewires,thenenteringintonewinputconnectionsontheleftsideoftheCPU.Figure7-21,part(b),depictsthemessycomplexityIhavejustdescribed.Ifwehadnotacquiredthecapabilitiesoftheone-to-manyinFigure7-3;the
capabilitiesofmany-to-oneinFigure7-14;andthecapabilityofusingonebusinsteadoftwoseparateonesformovingdataintoandoutoftheCPU,oursysteminFigure7-21wouldrequire48uniquewires,insteadof8.A“realworld”examplewith10peripherallatchesanda64-bitdatabusrequires64uniquewires,ifimplementedwithallourdesigntricks.Withoutallourdesigntricks,the“realworld”examplewouldrequire1280wires.Let’snowlookatthecircuitthatallowsustohaveabi-directionalbus.Seethe
picturebelow:
FIGURE7-22Thiscircuitdisplayshowtoturnanormal,1-bitlatchintoabi-directionallatch.
Youwouldcombineeightofthesetogethertomakean8-bitlatch,likeD1inFigure7-21,part(a).AlleightwouldshareoneEandoneR/Wline.Let’sstartwiththeboxlabeled“D-Latch”inthelowerright-handcorner.Thisis
thesameselect-and-storecircuitwestudiedinFigure7-10.TherestofthecircuitryinthepictureallowstheDinputandQoutputtosharethesamewire,orturnsoffaccessaltogether.TheDinputandQoutputsharethesamewirebytakingturnsonthesame
wire.WhentheDvoltagecomesintothiscircuit,thelatch’sQvoltageoutputmustbeblocked.WhentheQvoltagecomesoutofthiscircuit,thelatch’sDinputmustbeblocked.HowdowestoptheQoutputfromreachingtheDline,thedatabusline?We
alreadyknowhow.Wealreadydesignedatri-statebuffersothatmanyoutputscanbeconnectedtogether,turnedoff,andonlyoneturnedonatatime.InthedesignofFigure7-22,weneedtoturnofftheQoutputwhenitsvoltagewouldcontaminatethevoltagecomingintotheDlatchinput.Thus,youwillseethetri-statebufferdrawnintheupperright-handcornerofFigure7-22.Thisisyourfirstlookatthelogicsymbolforatri-statebuffer.Inside,itcontainsthecircuityousawinFigure7-20.WhentheEnlineonthetristatebufferis5volts,thevoltageonIappearsatO.WhenEnis0volts,thetri-statebuffer’soutputdisappears,fromtheDinputline’spointofview.TheD,E,andR/WlinesareunderthecontroloftheCPU.Inshort,Disthe
binarydatabit,Eisthebitthatenablesthislatchtodoanything,andR/Wselectswhetherthislatchreceivesorsendsalogicbit.TheCPUreadsthislatchwhenitsendsalogic1onR/W.TheCPUwritestothislatchwhenitsendsalogic0onR/W.WhentheCPU’slatchwanttowriteabittothislatch,itmakestheR/Wline0
volts.Itplaceseither0voltsor5voltsontheDline.Then,itplaces5voltsontheEline.ItcanthensafelypulltheElinebackto0volts.WhentheCPU’slatchwanttoreadabitfromthislatch,itmakestheR/Wline5
volts.Then,itplaces5voltsontheEline.Itgrabsthelatch’sdataofftheDline.ItcanthensafelypulltheElinebackto0volts.Thus,R/WcontrolsthedirectionofinformationtransferontheDwire.Let’slookathowthecircuitryin7-22accomplishesallofthis.Notice,first,that
boththelatchandthetri-statebufferhaveenablecontrolinputs:Enforthetri-statebuffer,andEfortheDlatch.Also,bothEnandEinputsarehigh-true,meaningthatahighlogiclevelturnseachoneon.Next,noticethatEnforthetri-statebufferiscontrolledbyAND1,andEfortheDlatchiscontrolledbyAND2.Thisleadstotheconclusionthatalogic1outofAND1turnsonthetri-state
buffer,forthereadingofQbytheCPU.Similarly,alogic1outofAND2turnsontheDlatch,forwriting(storing)intotheDlatchbytheCPU.So,ifthisbitlatchisnottheoneselectedbytheCPUcontrollerlatch,bothAND
1andAND2outputsmustbeatalowlogiclevel.Neitherthetri-statebufferforoutputnortheDlatchforinputwillbeselected.Recall,fromthelogictablefortheANDgate,asseeninFigure6-22,thatifoneinputtoanANDgateislow,itsoutputislow.Youdon’tevenneedtolookattheotheroutput.Well,theEinputonthefarleftgetsappliedtotheAinputonbothAND1andAND2.SoiftheexternalEinputfromtheCPUcontrollerislow,bothANDgatesoutputswillbelow,andboththetri-statebufferandtheDlatchwillbeoff:thatis,blockedoutoftheoutsideworldontheDwire.Youmayalsoremember(againfromitslogictable)that,ifoneinputtoatwo-
inputANDgateishigh,thentheotherinputpassesthroughtotheoutputwiththesamelogiclevel.TheEinputonthefarleftgetsappliedtotheAinputonbothAND1andAND2.So,ifEishigh,bothAND1andAND2areprimedfortheirYoutputsgoinghigh.AlleitheroneneedsisahighlogiclevelonitsBinput.Let’sfocusnextongettingahighlogicleveltotheBinputs.Butfirst:wedon’twanttoallowbothBinputsofAND1andAND2tobehigh.
Thiswouldcauseasimultaneousread/write,input/outputclash,ratherthanthetakingofturnsinsharingtheDbus.Ourslickwaytopreventthisscenarioistousetheinverter,seeninthelowerleft-handcornerofFigure7-22.Bydefinition,thelogiclevelsontheinputandoutputofaninverterareneverthesame;theyarealwaysopposite.Bothcannotbehigh.So,weconnecttheinputsideoftheinvertertoBofAND1,andtheoutputsideoftheinvertertoBofAND2,knowingtheywillneverbothbehighatthesametime.Wewillneverreadandwriteatthesametime.WhenEishigh,wewilleitherreadorwrite,butneverboth.Next,weconnecttheR/WcontrolsignalfromtheCPUtotheinputsideofthe
inverter(andtotheBinputofAND1).AssumenowthatEishigh.WhenR/Wishigh,theYoutputofAND1goeshigh,causingthetri-statebuffertoturnon,passingtheDlatch’sQoutputtothebi-directionalbus,sothattheCPUlatchcanreadit.TheinverterinvertsthehighonR/WandsendsalowtoBofAND2,pullingtheYoutputofAND2low,andturningofftheDlatchfromanunwantedwrite.StillassumingthatEishigh,let’sseewhathappenswhenR/Wislow.AND1’s
Youtputgoeslow,sothetri-statebufferturnsoff.TheQoutputisblockedfromreachingtheDlineofthetri-statebus.TheinverterinvertsthelowonR/WandsendsahightoBofAND2,pullingtheYoutputofAND2high,andturningontheDlatchforstorageoftheinputdatabitontheDline.Let’ssayafewwordsabouttheCPUlatch.CPU,aspreviouslystated,stands
forcentralprocessingunit.Itisthe“brains”ofthemicroprocessor.Itisthecircuitrythatcontrolsothercircuitry.Itisthecircuitrythatexecutestheprogramcommands.Insomemicroprocessordesigns,themicroprocessorincludesonly
theCPU.Non-CPUthings,likememoryandinput/outputports,areexternaltothemicroprocessor.Inothermicroprocessordesigns,themicroprocessorincludeseverything:CPU,memory,input/output/,etc.Inthelastfewparagraphsandfigures,IhavereferredtotheCPUlatch.Thisis
justoneelementintheCPU.ItisonelatchgroupinsidetheCPU:forourdesignitisan8-bitlatch,nodifferentfromD1,D2,orD3inFigure7-21.YoumayhavewonderedhowtheCPUlatchworks,comparedtolatchesD1
throughD3thatwehavebeenexplainingindiagram7-21.Itworksthesameway,withonemajordifference:theCPUmakestheR/WlineontheCPUlatchtheoppositelogiclevelasontheR/WlinetotheexternallatchesD1,D2orD3.Thismakessense.IftheCPUistryingtoreadfrom8-bitlatchD1,thenthatmeansitisalsotryingtowriteD1’scontentstoitsCPU8-bitlatch.IftheCPUistryingtowriteto8-bitlatchD1,thenthatmeansitisalsotryingtoreadoutthecontentsofitsCPUlatchtoputitinD1.Remember,theonlydifferencebetweenreadingandwritingtoalatchisthelogicleveloftheR/Wline.
CHAPTEREIGHTAMICROPROCESSORINACTION
Thusfar,wehavebeenslowlybuildingupthepiecesofthepuzzlethathelpus
understandhowamicroprocessorworks.Now,let’stakeabigstepforward,andlookathowthosepiecesfittogethertomakeaworkingmicroprocessor.Ourpatternhasbeentoproceedfromactualcircuitstosimplerlogicdiagrams
thatencapsulatetheactualcircuitsinside.Thishasallowedustobuildmorecomplexcircuitsbyconnectinglogicdiagrams,sothatthedetailofactualcircuitsdoesnotoverwhelmus.Figure7-22,above,isagoodexampleofthis.Itisaninterconnectionoffive
logicdiagrams.But,eachlogicdiagramcontainsinsideitaphysicalcircuitwhichwehavepreviouslydesignedandstudied.Ifwehaddrawnallthephysicalcircuitrycontainedinthesefivelogicdiagrams,thecomplexitymightoverwhelmus.Wearenowtakingabigstepforwardtoahigh-levellogicdiagramofthewhole
microprocessor.Itismoreofasketchyblockdiagram.Wecanuseittogetafeelforhowthewholemicroprocessorgoesaboutdoingitswork.Oncewegetagetafeelforthefunctionalityatthislevel,wewillthenbacktrackandexplorethecircuitsinsidetheseblocksinmoredetail.Thosecircuitsarethefinalpiecesofthepuzzlethataccomplishtheeventswitnessedinthefollowingdemonstration.Let’sbegin.Ifsomeoneasksyou,“Whatdoesamicroprocessordo?”youcan
answer,“Fetch,decode,andexecute.”Itperformsthissequenceofactions,inthisorder,overandover,millionsoftimespersecond.Whentheexecuteactioniscomplete,thenextfetchbegins:fetch,decode,execute,fetch,decode,execute,fetch,decode,execute,etc.Whenyouturnonthemainpowerswitch,thefirstthingthemicroprocessordoesis:fetch.Inthefetchoperation,themicroprocessorreadsthenextcommandor
instructionfromprogrammemory.Inthedecodeoperation,circuitryinthemicroprocessordeciphersthecommand,settingupallthenecessarysub-circuitsrequiredtocarryoutthecommand.Intheexecuteoperation,themicroprocessorcarriesoutthecommand,usingallthecontrolcircuitryandsub-circuitsunderitscommand.Let’swatchhowthisplaysoutinthepicturebelow.
AddressBusDataBus
FIGURE8-1First,let’sgetcomfortablewiththisfigurethroughanoverview.Comparethis
figurewithFigure7-21.TherightsideofFigure8-1isthebi-directionaldatabusthatyoualreadyunderstand,fromFigure7-21.ThedatabusinFigure8-1hassixbits,labelledD0throughD5.TheCPUselectsoneoftheDlatchesintheROM,keyboard,RAM,orvideoblocks.Then,iteitherwritessixparallelbitstoit,orreadssixbitsparallelbitsfromit.TheCPUblockinFigure8-1hasmorethingsinit.But,twoofthem,the
instructionregisterandtheaccumulatorarejustCPUlatches,liketheoneinFigure7-21.Youalreadyunderstandbi-directionalDlatches.Everythingelseinthefigure,belowtheblocklabelledCPU,isjustDlatches.Icountnine,6-bitlatchgroups.SixofthemareclumpedtogetherintheblocklabelledROM.StilllookingonlyattherightsideofFigure8-1,noticethearrowsalongthedata
bus.ThearrowtotherightoftheCPUpointsbothways.Thisindicatesthat
informationflowsbothwaysonthedatabus:intoandoutoftheCPU.Thesingle-endedtailstotherightoftheROM,keyboard,RAM,andvideoblocksaredrawntohelpyouunderstandwhichwaythevoltageismovingonthedatabusaswewalkthroughthisprogram’sexecutionNext,let’sgetcomfortablewiththedevicesinFigure8-1.Thisisaverysimple
system.ROMstandsforread-onlymemory.It’swhereourcomputer’sprogramlives.TheprogramcommandsareintheROM,evenwhenpoweristurnedoff.Themicroprocessorneedsaprogram’scommandsavailablefromtheinstantitisturnedon,becauseithastofetch,thendecode,thenexecute.TheROMiswherethemicroprocessorfetchesfrom.RAMstandsforrandom-accessmemory.Unlikeread-onlymemory,random-
accessmemorycanbebothreadfromandwrittento.“Random”meansthemicroprocessorcanpickanylocationinRAMtoreadorwrite;itdoesnothavetogosequentially.Wewillhavemuchmoretosayaboutthisselectionprocess,shortly.Thekeyboardisthelocationfromwhichourmicroprocessorreadsacomputer
keyboardkeypress.Thevideoisthelocationtowhichourmicroprocessorwritestheletterpressedonthekeyboard,sothelettercanbeviewedontheLCDscreen.Now,let’slookattheleftsideofFigure8-1,theaddressbus.Theaddressbus
inthissystemisfourbits—onfourwires—labelledA0throughA3.ItispartoftheDlatchselectionprocess,inwhichtheCPUchooseswhichofthenineDlatchesintheROM,keyboard,RAM,orvideoitwritestoorreadsfrom.Again,wewillhavemuchmoretosayaboutthisselectionprocess,shortly.Noticethearrowsalongtheaddressbus.Theaddressbusisnotbi-directional.
VoltagescomeoutoftheCPUblock,eitherfromtheprogramcounteroraddressregister,andgototheROM,keyboard,RAM,orvideo.Thevoltagesonthisbusaren’tforstorage,justforselection.TheaddressofeachofthenineDlatchesinvolvedinthisprogramisdrawnon
thefarleftofeachblock.Forexample,thefirstROMlocationisataddress0.Thekeyboardlocationisaddress16.Thevideolocationisaddress48.Rememberthatthesearehuman,decimalnumbers.TheCPUwillputthesenumbersinbinaryvoltageformontheaddressbus,aspartoftheselectionprocess.Wewillhavemoretosayaboutbinarynumbers,shortly.Let’sgetstarted.Iwillgothroughasimpleprogram,in36steps,usingFigure8-
1asreference.Duringeachstep,lookatthestepnumber,drawnandcircledinFigure8-1,tolocatewheretheeventoccurs.Sothatyouknowinadvancewhattheprogramdoes:itreadstheletterUpressedonthekeyboard,storesacopyofthatletterinRAM,thenstoresthesameletterinvideo,forscreendisplay.Step1.)Youalreadyknowwhatstep1willinvolve:afetch.Theprogram
counterintheCPUcontainsabinaryvalueof0atpower-up.Thebinary0voltagesareplacedontheaddressbus.
Step2.)ROMlocation0isselected.Step3.)ThebinarycodeforaREADcommandgoesoutofROMandontothe
databus.Step4.)TheREADcommandgoesintotheCPU’sinstructionregisterfor
decoding.Theprogramcounterbumpsupby1;ithadbinary0,sonowithasbinary1.ThedecodingoftheREADcommanddeterminesthatthecommandisincomplete.Moreinformationisneededbeforethecommandexecutioncanoccur.Step5.)Anotherfetchoccurs.Theprogramcounterplacesabinaryvalueof1
ontotheaddressbus.Step6.)ROMlocation1isselected.Step7.)Thebinaryvalueofdecimal16comesoutofROMandgoesontothe
databus.Step8.)Thebinary16enterstheCPU’sinstructionregister,andisappendedto
theREADcommand.Theprogramcounterbumpsupby1;ithadbinary1,sonowithasbinary2.Thecompletecommandintheinstructionregisterisnowabinarycodethatstandsfor,“READaddress16.”Decodingdeterminesthatthiscommandiscomplete,socommandexecutioncannowbegin.Step9.)Thebinaryaddress,16,intheinstructionregistermovesintothe
addressregister,thenontotheaddressbus.Step10.)Keyboardlocation16isselectedforreading.Step11.)ThebinarycodefortheletterU,thekeyboardkeythattheuser
pressed,goesoutofthekeyboardlatchandontothedatabus.Step12.)ThebinaryUenterstheAccumulatorlatchintheCPU.The
AccumulatorisautomaticallythedestinationoftheREADcommand.Thecurrentexecutionprocessiscomplete.Step13.)Thefetchprocessstartsagain.Theprogramcounterplacesabinary
valueof2ontotheaddressbus.Step14.)ROMlocation2isselected.Step15.)ThebinarycodeforaWRITEcommandgoesoutofROMandonto
thedatabus.Step16.)TheWRITEcommandgoesintotheCPU’sinstructionregisterfor
decoding.Theprogramcounterbumpsupby1;ithadbinary2,sonowithasbinary3.ThedecodingoftheWRITEcommanddeterminesthatthecommandisincomplete.Moreinformationisneededbeforethecommandexecutioncanoccur.Step17.)Anotherfetchoccurs.Theprogramcounterplacesabinaryvalueof3
ontotheaddressbus.Step18.)ROMlocation3isselected.Step19.)Thebinaryvalueofdecimal32comesoutofROMandgoesontothe
databus.
Step20.)Thebinary32enterstheCPU’sinstructionregister,appendedtotheWRITEcommand.Theprogramcounterbumpsupby1;ithadbinary3,sonowithasbinary4.Thecompletecommandintheinstructionregisterisnowabinarycodethatstandsfor,“WRITEaddress32.”Decodingdeterminesthatthiscommandiscomplete,socommandexecutioncannowbegin.Step21.)Thebinaryaddress,32,intheinstructionregistermovesintothe
addressregister,thenontotheaddressbus.Step22.)RAMlocation32isselectedforwriting.Step23.)ThecontentsoftheCPU’sAccumulatorlatchisplacedonthedata
bus.TheAccumulatorisautomaticallythesourcefortheWRITEcommand.Remember,itcontainsthebinarycodefortheletterU,acquiredinstep12.Step24.)ThebinaryUvalueentersRAMlocation32forstorage.Thecurrent
executionprocessiscomplete.Step25.)Thefetchprocessstartsagain.Theprogramcounterplacesabinary
valueof4ontotheaddressbus.Step26.)ROMlocation4isselected.Step27.)ThebinarycodeforaWRITEcommandgoesoutofROMandonto
thedatabus.Step28.)TheWRITEcommandgoesintotheCPU’sinstructionregisterfor
decoding.Theprogramcounterbumpsupby1;ithadbinary4,sonowithasbinary5.ThedecodingoftheWRITEcommanddeterminesthatthecommandisincomplete.Moreinformationisneededbeforethecommandexecutioncanoccur.Step29.)Anotherfetchoccurs.Theprogramcounterplacesabinaryvalueof5
ontotheaddressbus.Step30.)ROMlocation5isselected.Step31.)Thebinaryvalueofdecimal48comesoutofROMandgoesontothe
databus.Step32.)Thebinary48enterstheCPU’sinstructionregister,appendedtothe
WRITEcommand.Theprogramcounterbumpsupby1;ithadbinary5,sonowithasbinary6.Thecompletecommandintheinstructionregisterisnowabinarycodethatstandsfor,“WRITEaddress48.”Decodingdeterminesthatthiscommandiscomplete,socommandexecutioncannowbegin.Step33.)Thebinaryaddress,48,intheinstructionregistermovesintothe
addressregister,thenontotheaddressbus.Step34.)Videolocation48isselectedforwriting.Step35.)ThecontentsoftheCPU’sAccumulatorlatchisplacedonthedata
bus.TheAccumulatorisautomaticallythesourceforWRITEcommands.Remember,itcontainsthebinarycodefortheletterU,acquiredinstep12.Step36.)ThebinaryUvalueentersvideolocation48forstorageandviewing
onascreen.Thecurrentexecutionprocessiscomplete.Ourprogramiscomplete.That’sallthereistoit.Oursimpleprogram,foroursimplemicroprocessor
system,isdone.Whatdoesourmicroprocessordonext?Youknowthatithastofetchacommand.Ournextcommand,atROMaddress6couldbe,GOTO0.TheGOTOcommandreplacesthecurrentcontentsoftheprogramcounterwiththevalueinthesecondpartoftheGOTOcommand.SinceourcommandisGOTO0,abinary0wouldbeplacedintheprogramcounter,sothatthefetchwouldbefromROMaddresslocation0.Thiseffectivelystartsourprogramagain,fromthebeginning.Infact,ourprogramrestartseverytimeitfinishes,duetotheGOTO0commandattheend.Wecallthisaninfiniteloop.Theprogramloopsbackfromendtobeginningeverytime,forever,oruntilthepowersupplytothemicroprocessoristurnedoff.
CHAPTERNINEBINARYNUMBERS
Nowwecanexplorethedetailsoftheaddressbus.Iintentionallyworked
backwards,here.Icouldhaveshownyouthenutsandboltsofhowaddressselectionworksfirst.Ipreferredtofirstshowanaddressbusinaction,sothatyoucouldseewhyweneedone.And,soyoucanappreciateitsimportance.Binarygroupscanrepresentwhateverwewantthemtorepresent:command
code,numbers,alphanumericcharacters,etc.Ontheaddressbus,wetreatthebinaryvoltagesasnumbers:asnumericaladdresses,justlikeourhouseshaveaddressnumbers.Youneedtoknowalittleabouthowwerepresentnumbersinbinary.Weconstructthebinarynumbersystemthesamewayweconstructthe
decimalnumbersystem.Inthedecimalnumbersystem,wehavetendistinctdigits.Inbinary,wehavetwodistinctdigits:0and1.Topreventconfusionwhentalkingaboutbinaryanddecimal,Iwillappendabattheendofabinarynumber,andadattheendofadecimalnumber.So,ifIhave0basterisks,Idon’thaveanyasterisks.IfIhave1basterisks,Ihavethismanyasterisks:*.HowdoIrepresent**asterisks?Justlikeindecimal,whenIwanttogettothe
nextnumber,Iadd1btothecurrentnumber.Thisiscalledcounting.CountingishowIwentfrom0bto1b:Iadded1bto0btoobtain1b.NowIwanttoadd1bto1btogettothenextnumber,whichwillrepresent**asterisks.ButIhaverunoutofnumbers.Thereisnoone-digitnumberafter1b,inbinary.
WhatdidIdoindecimal,whenIwascounting(adding1tothecurrentnumber)andranoutofnumbers?Thishappenedat9d.After9d,thereisnohigherone-digitnumberindecimal.WhenIreached9dandadded1dto9d,Iresetthe9dbackto0dandaddeda1dtothenextcolumntotheleft.Mynextnumber,after9d,became10d.Seetheexample,below:
TABLE9-1
Whatisthesignificanceofthenextcolumntotheleft?Numbersinthenewcolumn,secondfromtheright,areworthtentimesasmuchasnumbersinthefirstcolumn(indecimal).So,a1dinthefirstcolumnisworth*asterisk.But10dhasa1dinthesecondcolumnfromtheright,soitisworthtentimesasmanyasterisks:**********.Infact,everytimewemoveanothercolumntotheleft,thevalueofthatdecimaldigitincreasesanotherten-fold.Followingthesamerulesweusedfordecimal,wefindthatthebinarynumber
after1bis10b.Howdidwearriveatthisanswer?Weresetthe1bto0b,andadda1btothenextcolumn.Thenewnumber,10b,represents**asterisks.Seetheexample,below:
TABLE9-2
Nowyoucanseetheimportanceofusingabordafterournumbers.Indecimal,10drepresents**********asterisks.Inbinary,10brepresents**asterisks.Withoutthebord,theylookthesame:10.Indecimal,anumberinanycolumnisworth10dtimesasmanyasterisksas
thesamenumberinthecolumntoitsright.So,indecimal321d,the3disreallyworth(3d)x(100d),or300d;the2disreallyworth(2d)x(200d),or200d;andthe1disreallyworth(1d)x(1d),or1d.Addthemup,andwewriteitas321d.Inbinary,anumberinanycolumnisworth10btimesasmanyasterisksasthe
samenumberinthepreviouscolumn,toitsright.10binbinaryis2dindecimal,toushumans,comfortablespeakingindecimal.So,speakingasahumanindecimal,abinarynumberinanycolumnisworthdouble,ortwiceasmany
asterisksasthesamenumberinthecolumntoitsright.Ifwecontinuecountinginbinary,wekeepusingtheruleofresettingto0band
adding1btothenextcolumntotheleft.Forexample,ifwehavecountedto11b,thenextnumberis11b+1b.Weadd1btotherightmostcolumnof11b.Wehaverunoutofdigits,soweresettheresultantto0bandcarrythe1btothenextcolumntotheleft.Thecarry1bplusthe1binthesecondcolumnalsooverflows,soweresetto0bagain,andadd1btothenextleftcolumn.Theanswerbecomes11b+1b=100b.So,countinginbinarylookslikethis:
TABLE9-3
Wesaythatabinarynumberinanycolumnisworthdouble,ortwiceasmanyasterisksasthesamenumberinthecolumntoitsright.Usingthisknowledge,wecanconvertanybinarynumbertodecimalbyusingthechartonthefollowingline:
TABLE9-4Theabovesequenceistheweightingvalueofthebitpositionforeachbitofan
8-bitbinarynumber.Eachvalue(aftertherightmost)isdoublethenumbertoitsright.Toconvert00111011bfrombinarytodecimal,lineupthe8binarydigitsundertheircorrespondingweightingvalues.Multiplyvertically,thenaddthemultiplicationresultshorizontally.Seetheexamplebelow.
TABLE9-559disthedecimalformofthebinarynumber00111011b.
Thereareformalwaystoconverttheotherway,fromdecimaltobinary,butthey
involvelongdivision.Moststudentsnowadayspreferatrialanderrorsolution(oruseascientificcalculator).It’sliketheabovemethod,butinreverse.Forexample,toconvert50dtobinary,preparethischart:
TABLE9-6Startfromtheleft,andworktowardtheright.Findthebiggestnumberthatdoesnotexceed50d.Thatwouldbe32d.Replacethe0bunderthe32dwitha1b.Keepaseparaterunningtallyofthenumbersabovethebitswechangefrom0bto1b.Ourtallynowonlycontain32d.(Seebelow.)
TABLE9-7Keepworkingyourwaytotheright,findingthenextdecimalnumberwecan
addto32d,withoutthesumexceeding50d.16disthenextnumber,because32d+16d=48ddoesnotexceed50d.Changethe0bunderthe16dtoa1b,andaddthe16dtoourrunningtally:32d+16d=48d.Ourchartnowlookslikethis:
TABLE9-8Werepeatthisprocess,stoppingonceourrunningtallreaches50d.Weareat
48d.Obviously,wemustnotadd8d,because48d+8d=56d,whichexceeds50d.Infact,at48d,weonlyneed2dmoretoexactlyarriveat50d.So,wecanalsoskipover4d.Wechangethe0bunderthe2dtoa1b,andaddthe2dtoourrunningtally:48d+2d=50d.Ourchartnowlookslikethis:
TABLE9-9So,westartedwithdecimal50dandwantedtoknowthebinaryequivalent.We
concludethat00110010bisthebinaryequivalentof50d.Thefirsttwozeroesontheleftarenotrequired.Theanswerdoesn’tchangeifyouweretowrite110010b,insteadof00110010b.
CHAPTERTENTHEADDRESSBUSANDDECODER
Returningtoouraddressbus,assumewehavea4-bitaddressbus.Assume
wehavelabelledthefourwiresofthebusasA3,A2,A1,andA0.WeagreethatthewirelabelledA3standsforthemostsignificantbit,andtheonelabelledA0standsfortheleastsignificantbit.Inotherwords,thattheyfollowthechartbelow:
Let’ssaywewanttoenablethelatchthathasthedecimaladdressof9d.What
binaryaddressdoweputonthedatabus?Well,9dindecimalisthesamenumberas1001binbinary.Theybothdescribe*********asterisks.Sinceweputvoltagesontheaddressbus,ouraddressbuswouldphysicallycontainthefollowingvoltagesatthefollowinglocations:
Nowthatyouunderstandwhatisphysicallyontheaddressbus,younextneed
tounderstandhowthesevoltagesaredecoded:howtheyselectonlyoneofthemany6-bitdatalatchesinFigure8-1.Goback,rightnow,toFigure7-12.Yousee,inFigure7-12,aboxlabelledCwiththeabilitytoselectoneofseveraldatalatches:tomakethevoltageattheE(enable)inputofonedatalatch5volts,whilekeepingalltheotherEinputsofthenon-selecteddatalatches0volts.ThissectionexplainswhatisinsidethatmysteriousboxlabeledC:theaddressdecoder.Forthemoment,let’ssimplifyourFigure8-1evenfurther.Let’spretendthat
ROMisonlyonelatchgroup,RAMisonlyonelatchgroup,thekeyboardisonlyonelatchgroup,andvideoisonlyonelatchgroup.Fourlatchgroupsrequirefouruniqueaddresses(22=2x2=4)todecodethem.Theaddresseswouldbe:00b,01b,10b,and11binbinary,forROM,keyboard,RAM,andvideo,respectively.Let’slabeltheaddresslinesA5andA4.Seethepicturebelowtolearnhowthe
microprocessorsystemdecodesA5andA4:
FIGURE10-1InFigure10-1,asmallmicroprocessoraddressdecoder,Ihavearrangedthe
middlesectionpurelyforeaseofunderstanding.Thisinternalbusdoesn’tleadanywhereoutofthepicture.Thereonlytwoinputs,A5andA4.Therearefouroutputs:EofROM,Eofkeyboard,EofRAM,andEofvideo.Estandsforenable.Remember,eachDlatchisaccessibleonlywhenitsEinputishigh.Thelogictable(sometimescalledthetruthtable)thatcompletelydescribesthebehaviorofthisaddressdecoderis:
FIGURE10-2
Readingthetruthtableonerowatatime,wefindsummarizedwhatwe
describedintheparagraphsabove.Forexample,inthefirstrow,whenA5andA4arebothlow,onlytheEoutputtoROMishigh,meaningonlytheROMlatchisenabled.Let’slookatFigure10-1toseehowthisdecodingtakesplace.A5andA4,
generatedbytheCPU,entertheaddressdecoder.Theyareimmediatelyinvertedbyinverters,sothattheirlogicaloppositesareavailableasNOTA5andNOTA4.InFigure10-1,theseinversionsareshownasA5andA4withlinesabovethem.It’shardforwordprocessingsoftwaretoputlinesabovecharacters,soinsteadweputtheword,“NOT”infrontoftheinvertedlogic.Anothertechniqueistoputaforwardslashinfront,asin/A5and/A4.Now,fourdifferentlogicstatesareavailabletothefourANDgates.Non-
invertedversionsofA5andA4godirectlytoAND4.So,perthetruthtableofANDgates,AND4’soutputgoeshighwhenA4andA5arebothhigh.Thiscreatesrow
fourofthetruthtable.AND1’stwoinputsbothcomefromtheinverters.So,whenA5andA4areboth
low,inverteroutputs/A5and/A4arebothhigh,causingAND1’soutputtogohigh.Thiscreatesrowoneofthetruthtable.AND2’soutputgoeshigh(true)whenA4—whichdoesn’tgetinverted—ishigh
andA5—whichdoesgetsinverted—islow.Thiscreatesrowtwoofthetruthtable.AND3’soutputgoeshigh(true)whenA5—whichdoesn’tgetinverted—ishigh
andA4—whichdoesgetsinverted—islow.Thiscreatesrowthreeofthetruthtable.Thecreationofcomplexityfromsimplicityfollowsthefollowingprocessindigital
electronics.Westartwithvoltagesources,transistors,andresistors.Weputthemtogethertomakeinverters.Weputinverterstogethertomakegates.Weputgatestogethertomakelatches.Weputgatesandlatchestogethertomakemorecomplexcircuits.Weputmorecomplexcircuitstogethertomakemachinesanddeviceslikemicroprocessors.ThecircuitinFigure10-1isanexampleofputtingtogetherbasicbuildingblocks
—justgatesinthiscase,nolatches—tocreateaslightlymorecomplexcircuit.Itsnameisa2-to-4binarydecoder.Aswecreatetheseslightlymorecomplexcircuits,wegivethemnames,andencapsulatetheminnewlogicdiagrams.Thisway,wedon’thavetodrawthecircuitryinFigure10-1repeatedly.Wecaninsteaddrawthemuchsimplerlogicdiagramforthe2-to-4binarydecodershownbelow:
FIGURE10-3Theinputandoutputlabelsabovearegenericonesyouwillfindin
documentationfordecoders.ThelogicdiagraminFigure10-3focusesourattentionontheinputsontheleftandtheoutputsontheright.AlongwiththetruthtableinFigure10-2andyourunderstandingofhowthedecoderworks,younolongerhavetobeconcernedwiththecircuitryitencapsulatesinFigure10-1.Also,youdon’thavetoconcernyourselfwiththeresistorsandtransistorsthatFigure10-1’sANDgatesandinvertersencapsulate.Let’sreturn,now,toFigure8-1:ourmicroprocessorsystem.Intheabove
analysis,Isimplifiedtheaddressbusbymakingeachaddressablesubsystemcontainonlyonelatch:oneROMlatch,oneRAMlatch,onekeyboardlatch,andonevideolatch.Inarealsystem,eachaddressablesubsystemcontainsmanylatches.InoursystemofFigure8-1,eachsubsystemhas16latches.TheCPUaccessed6ofthe16ROMlatches.OurprogramaccessedonlyonelatchfromeachoftheRAM,keyboard,andvideosubsystem,butitcouldhaveaccessed16latchesineach.Amicroprocessor-basedsystem,then,actuallyperformslatchselectionina2-
stepprocess.DidyounoticethatinoursimplifiedanalysisinFigure10-1IlabelledtheaddressbuswiresasA5andA4?Andyet,inouractualcircuitofFigure8-1,IlabelledtheaddressbuswiresA3,A2,A1,andA0.Thisisevidenceofa2-stepprocess.Oursystem’sfinishedaddressbusreallyrequires6addresslines.Ina
microprocessorsystem,thehighestorderbitsareseparatedfromthelowerorderbits;thehighestorderbitsarethensenttoanaddressdecoder.Thus,thehighestorderbitsareusedtogeneratetheenablesignalthatpicksjustonesubsystem.Thelowerorderbitsarethenusedtoselectjustonelatchofthemany
containedintheoneactivesubsystem.Thoughthelowerorderbitsgotoallthesubsystems,theyareignoredbythenon-selectedsubsystems.So,let’sapplythisnew-foundknowledgetooursystem.Let’sremovethepartsofFigure8-1wedon’tneed—likethedatabus—andinsertwhatwehavejustlearned.Seethepicturebelow:
FIGURE10-4
InFigure10-4,youcanseehowthe2-stepaddressselectionprocessplaysout
inoursystem.NowyoucanseeallsixoftheaddressbitsourCPUgenerates.Youcanseetheseparatepaththehigher-orderaddressbits,A5andA4,taketotheaddressdecoder.Thisisstepone.Theaddressdecoderisthe2-to-4decoderfromFigure10-3.Theaddressdecoderactivatesonlyoneofthefoursubsystems,byraisingitsEwirehigh.Oncethechosensubsystemisactivatedbytheaddressdecoder,addresslines
A3,A2,A1andA0arefurtherdecodedinsidethesubsystemtopicktheonelatchgroupof16towritetoorreadfrom.Thisissteptwo.FromtheCPU’spointofview,itputs64differentaddressesonitsaddressbus.
That’sthenumberofuniquecombinationsofa6-bitbinarynumber(theaddressbusis6bitswide).TheCPUdoesn’tknowabouttheaddressdecoderoraboutfourdifferentsubsystems.Fromthesubsystems’(ROM,RAM,keyboard,andvideo)pointofview,eachoneofthemonlyreactsto16differentaddresses:decimal0dto15d,whichisthesameasbinary0000bto1111b.Theyalsoknownothingabouttheaddressdecoderoraboutothersubsystems.Theyknownothingaboutanyaddresseshigherthan15dor1111b.It’stheaddressdecoder,orperhapsweshouldsaythedesigneroftheaddress
decoder,thatcreatesthememorymapyouseeinFigure10-4.Lookclosely,andyouwillseethattheROMrespondstoaddresses0dto15d,thekeyboardrespondstoaddresses16dto31d,theRAMrespondstoaddresses32dto47d,andthevideorespondstoaddresses48dto63d,thataresentoutoftheCPU.Lookatthechartbelow:
FIGURE10-5EachrowinFigure10-5showstheaddressrangeforonesubsystem,andhow
itisderived.Thecolumnwiththeheading,“A5-A0decimal”showstheaddresses
thattheCPUsendsoutontoits6-bitaddressbus,andwhatdevicesrespondtothem.Thedecimalnumbersdon’tmakemuchsenseuntilyoulookattheminbinary,asshownintheadjacentcolumnwiththeheading,“A5throughA0.”Forexample,thechartsaysthattheVIDEOsubsystemrespondstothedecimal
rangeofaddresses48dthrough63d,whichisthebinaryrangeofaddresses110000bthrough111111b.(Youalreadyknowhowtododecimaltobinaryandbinarytodecimalconversions.)But,wheredothesebinarynumberscomefrom?Well,thecolumnlabelled,“A3
throughA0,”showswhateachsubsystemseesatitsaddressinputwires.Clearly,eachsubsystemseesthesameaddressrange:0000bthrough1111b.ThecolumnslabeledA5andA4completethestory.AddressbusvoltagesA5
andA4—viatheaddressdecoder—selectadeviceinonerowofthechart,toaccessthatdevice’sinternal0000b-1111baddresses.So,wenowknowwheretheVIDEOsubsystemsaddressrangeof110000bthrough111111bcomesfrom.WeusenumbersfromtheVIDEOrowinFigure10-5.Wewrite,fromlefttoright,thebinaryvaluesfor:A5(a1b),thenA4(alsoa1b),thenthe4-bitbinaryvaluesforA3throughA0(0000bthrough1111b).Wesaywe“append”thevalues,0000bthrough1111b,to11b,toproduce110000bthrough111111b.ThesearetheaddressnumbersthecomputerengineerwhodesignedthissystemusestoaccessVIDEO.Asstatedabove,oncethechosensubsystemisactivatedbytheaddress
decoder,addresslinesA3,A2,A1andA0arefurtherdecodedinsidethesubsystemtopicktheonelatchgroupof16towritetoorreadfrom.Now,I’llshowyouhowthedecodinginsidetheRAM,insidethevideo,etc.,happens.Actually,theaddressdecodinginsidethesubsystemisverysimilartothe
addressdecodingyoualreadyhavewitnessedoutsidethesubsystem,asinFigure10-4.Thedifferenceis,inFigure10-4wehadtoselectoneoffouraddresses,whereasinsideeachsubsystem,wemustselectoneofsixteenaddresses.Wehavefouraddresslines,A3-A0,toselectoneofthosesixteenaddresses,soweneeda4-to-16decoder.Wecoulddesignanew,4-to-16binarydecoder.Youmaybeabletodesignit
yourself,fromFigure10-1.(Hint:usefourinvertersandsixteen,4-inputANDgates.Instead,let’sfollowourprocedureofbuildingnew,progressivelymorecomplexcircuitsoutofouroldones.Let’sbuildour4-to-16decoderoutoftwo2-to-4decodersandsomeextraANDgates.We’llevensaveafewtransistorsdoingitthisway.Seethepicturebelow:
FIGURE10-6ThecircuitshowninFigure10-6isinsideeachofthefoursubsystems,ROM,
keyboard,RAM,andvideo.DC1andDC2aretwoofour2-to-4binarydecoders.TheyconnecttotheworldoutsidethemvialinesA3,A2,A1,andA0,asshownabove.Theeightwires,Q0throughQ3andQ0’throughQ0’,neverintersect:never
toucheachotherinanyway.Theycreatea4x4grid.Attheintersectionofeachwirepair,Ihavedrawnasmallbox.Ihavezoomedinonthecontentsofbox15.Thecontentsofbox15aredisplayedatthebottomofFigure10-6:anANDgateandoneofthesixteenlatches.Thisiswhatyouwillfindineachofthe16smallboxes.Ihavealsoplacedadecimalnumbernexttoeachsmallbox.ThisnumberisthedecimalequivalentofthebinarynumberonaddresswiresA3throughA0thatactivatesthelatchinsidethesmallbox.Seethepicturebelow,aswediscusshowthiscircuitworks.
FIGURE10-7
IfFigure10-7scaresyou,let’sfirstanalyzethecircuitinFigure10-6withoutit.
AddresslinesA3andA2enableoneofthefourrowsontheoutputofDC1.Thismeansthatonlyoneoftherowshasahighvoltageonit.ThisalsomeansthatonlythefourANDgatesinthatrowhaveahighononeinput.So,forexample,ifA3andA2arebothlow,onlyrowQ0’goeshigh,soonlythetoprow’sANDgateshaveoneinputhigh.But,toactivatealatch,werequirebotharowandacolumntobeenabled.
AddresslinesA1andA0enableoneofthefourcolumnsontheoutputofDC2.Thismeansthatonlyoneofthecolumnshasahighvoltageonit.ThisalsomeansthatonlythefourANDgatesinthatcolumnhaveahighononeinput.So,forexample,ifA1andA0arebothlow,onlycolumnQ0goeshigh,soonlytherightcolumn’sANDgateshaveoneinputhigh.However,fortheoutputofa2-inputANDgatetobehigh,bothofitsinputsmust
behigh.Ifyoufollowthroughtheexampleintheprevioustwoparagraphs,youwill
findthatonlytheANDgateintheupperright-handcornerhasbothofitsinputshigh.ItistheonlyANDgatewhoseinputsaredrivenbyboththetoprow’s(Q0’)andtherightcolumn’s(Q0)highoutputs.So,whenA3throughA0are0000b,onlytheANDgatehiddeninthesmallboxlabelled0inFigure10-6hasahighoutput.Thishighoutputpullshightheenableinputofitslatch,forreadingorwritingtothatlatch.NowlookatFigure10-7.ItislaidoutinthesameorderasthegridinFigure10-
6.ThedecimalnumberatthebottomofeachsquareinFigure10-7isthesameastheoneineachcorrespondinglittleboxinFigure10-6.It’sthedecimalformoftheaddressonA3throughA0thatactivatesthelatchinsidethelittleboxofFigure10-6.Tocontinue,let’slookatjustonesquareinFigure10-7.Lookatthesquarein
thelower,right-handcorner:theonewitha12init.Youalreadyknowthat12disthedecimalformoftheaddressonA3throughA0thatactivatesthelatchinsidethelittleboxofFigure10-6.Thesecondrowofthesquareis1100b,thebinaryformof12d.1100bdescribestheactualvoltagelevelsonA3throughA0.Directlyaboveeachdigitin1100b,youwillfindthecorrespondingA3,A2,A1,orA0wirethatdrivesthatvoltagelevel.Youwillfindthat1100bissplitinhalf,anddisplayedas11bthenaspace,then00b.That’sbecauseA3andA2generateaQ’output,andA1andA0generateaQoutput,throughtheircorrespondingbinarydecoders.Inthisspecificcase,the11bsendsQ3’high,andthe00bsendsQ0high.ThesetwohighsmeetattheANDgatethatactivateslatchnumber12d.
CHAPTERELEVENTHECONTROLBUS
Atthispoint,wehavecoveredthedevicesandprogramofoursimple
microprocessorsystem,inFigure8-1;theexternaladdressdecoderinvolvedindeviceselection,inFigure10-4;andtheinternaladdressdecoder,hiddenineachdevice,inFigure10-6.Youhavelearnedhowtheaddressanddatabuswork.There’sanotherbus,involvedinallthis.It’scalledthecontrolbus.Onceagain,I’llhidethepreviousconnectionsfromFigures8-1and10-4thatmightconfuseyou.Seethepicturebelow:
FIGURE11-1ThenewitemsaretheALEandR/WoutputsfromtheCPU.Theymakeupthe
simplecontrolbusforoursimplesystem.Thename,“controlbus,”isself-explanatory.ThecontrolbusisthesignalsthattheCPUusestocontrolcommunicationwithsubsystems.Thenewitemsherearenotreallynewtoyou.Youalreadyknow,fromFigure7-
22,thatbi-directionallatchesrequireanR/Winputtocontrolwhetherdataisbeinginputtooroutputfromthem.TheCPUprovidesthisvoltage.Remember,ahighonR/Wmeans“read.”TheCPUreadsthelatch,sodatacomesoutofthelatch.AlowonR/Wmeans“write.”TheCPUwritestothelatch,sodatagoesintothelatch.InFigure11-1,IdrewR/Wcontrolintoallfoursubsystems.Ifanyofthemareunidirectional,theydon’tneedanR/Wline.
YoualsoknowfromFigure7-22thatlatchesrequireahighontheirEline(enableline)toturnthemon.Wehavealreadycoveredthatcontrolprocessabove.However,ifyoulookbackattheaddressdecoderwedesignedinFigure10-1,youwillseethatthereisnowaytoturnallfouroutputsoff,simultaneously.Oneofitsoutputshastobehigh:eitherE0,E1,E2,orE3.This,inturn,meansthatoneofthefoursubsystemshastobeon.Thissituationisaproblem.Nosubsystemshouldbeon,unlesstheCPUisdeliberatelyaccessingit.Datacorruptioncanresult.OurCPUprovidesacontrollinetohelpovercomethisproblem.Thelineis
named“ALE,”for“addresslatchenable.”TheCPUpullsthislinehighwhenithasputanaddressontheaddressbus.OnlywhentheALElineishighshouldoneofthesubsystemsbeon.OnlywhentheALElineishighshouldoneoftheaddressdecoderoutputsbehigh.WhentheALElineislow,allfouraddressdecoderoutputsshouldbelow.InFigure11-1,youwillseethattheALElinegoestotheaddressdecoder.The
addressdecoderofFigure10-1obviouslyneedsaminorchange.ThefourANDgatesneedtobecome3-inputANDgates.Allofthenew,thirdinputstotheAND’sshouldbeconnectedtogether,andthenconnectedtotheALEsignal.Thepicturebelowreflectsthesechangesinouraddressdecoder:
FIGURE11-2
Differentmicroprocessormanufacturershaveslightlydifferentwaysof
implementingacontrolbus.Forexample,somemicroprocessorssplitourR/Wlineintotwoseparatelines:anRlineforreading,andaWlineforwriting.SomemicroprocessorshaveoneEnable(E)lineformemory(RAM,ROM)andaseparatelineforinput/output(I/O)devices(keyboard,video).InterruptandDMAcontrol,ifimplemented,requirecontrolbuslines.Whateverthedesign,propertimingofthearrivalofinformationontheaddress
anddatabusesiscritical.IfamicroprocessoronlycontainstheCPU,butnotthesubsystems(peripherals),thatmicroprocessor’smanufacturerwilloftensellperipheralsdesignedspecificallytoworkwiththemicroprocessoranditscontrolbus.Thishelpstopreventtimingbugs,andmakeslifeeasierfordesigners.
CHAPTERTWELVETHESYSTEMCLOCK
Now,let’slookatsomeothersecretsthatmaketheCPUwork.First,let’s
considerthesequentialnatureofthesystem.Isaidthatthemicroprocessordoesthreethings,overandover:fetch,decode,andexecute.Thisimpliesanorderedsequenceofevents.Firstthishappens;thenthishappens,laterintime.Noneofthegatesorlatcheswehavestudiedsofarchangeovertime.Becauseofthisrequirement,allmicroprocessorsystemshaveaclock.Thisis
notthekindofclockthattellsthetimeofday.Rather,itisasquare-waveoscillator.Itisadevicethatcreatesadigitalvoltagethatishighforabriefperiodoftime,thenlowforabriefperiodoftime,thenhighforabriefperiodoftime,etc.Itneverstopsthisceaselessrepetition,untilthepowersupplyisturnedoff.Ifweweretoplotagraph,withvoltageontheverticalaxis,andtimeonthehorizontalaxis,itwouldlooklikethis:
FIGURE12-1
TheclockpicturedinFigure12-1ishighfor.5nanoseconds,thenlowfor.5
nanoseconds,thenrepeats.Afullcycleisahighfollowedbyalow,soafullcycletakes1nanosecond.Ananosecondisonebillionthofasecond.Inonesecond,thisclockrepeatsthecycleabilliontimes.Inelectronics,weliketosay“mega-,”insteadofmillion,and“giga-,”insteadofbillion.So,thisfiguredescribesa1gigahertz(1billioncyclespersecond)clock.Wereferto1gigahertzastheclock’sfrequency.Thinkoffrequencyashowfrequentlytheclockrepeatsitscycleinonesecond.Howdoesonebuildaclocklikethis?Ifwewanttobuilduponcircuitswehave
alreadystudied,thenwemaybuildoneliketheoneshowninthefollowingpicture:
FIGURE12-2
Thecircuitshownabovewilloscillateinasquare-wavepattern.Itsfrequency
canbecalculatedwiththefollowingequation:f=1/(2.3xR2xC)[whereR1ischosentobe10xR2]Weareveryfamiliarwithinverters(U1andU2)andwithresistors(R1andR2).
Thiscircuitintroducesanewcomponent:thecapacitor.Thecapacitorisonthefarright,labelledC.Itscircuitdiagramisthestraightlineandthecurvedline.(Sometimes,itisrepresentedastwoparallellines.)Let’sfigureoutwhythiscircuitoscillates.We’llstartbylookingattheleftside
only.Seethepicturebelow:
FIGURE12-3Thinkaboutthiscircuit,forawhile.Haveyounoticedsomethingstrange?
Assumetheinputishigh.Thatmeans,asaninverter,theoutputmustbelow.Butthelowoutputfeedsbacktotheinput.But,wejustsaidtheinputwashigh.Howcantheinputbebothlowandhigh?Doesthelowoutputturnthehighinputtolow,causingthelowoutputtoimmediatelygohigh?Butthen,doesthenewhighoutputgobackaroundtoreplacetheoldlowinput,causingtheoutputtoinvertbacklow?Doesthisgoonforever?IsthislikeKrypto,Superman’ssuper-dog,chasingitstailatlightningspeed?Yes,thisisanout-of-controloscillator,ifiteveroscillatesatall.Whatisneeded
issomethingtoslowitdown,togetitincontrol.Wheneverweneedsomethinginelectronicstoslowthingsdown,weturntocapacitors.Capacitorsintroducetheelementoftimeintoelectronics.Inductorsdo,too.Butinductorsalsohavethenastyhabitofcausingsparks.Inductorsaregoodforcausingsparksacrossyourcar’ssparkplugs,butarebadformostelectroniccircuits.So,capacitorsaremorepopular.Let’slookatFigure12-2attheexactmomentwhenpointWswitchesto5volts,
pointXswitchesto0volts,andpointYswitchesto5volts.Theseoppositerelationshipshavetohold,duetotheinvertingnatureofinverters.What’stopreventthe0voltsatXfromfeedingbackimmediatelytoW,andcausingthewholenastyrunawayproblemmentionedabove?ThevoltageatpointZpreventsthisproblem.Theinstantbeforethisnewstate,
pointYwasinitsoldstate,0volts.PointZwasat5volts;ithadtobeat5voltstogivepointWits5volts,toinitiatethecurrentstate.But,atthemomentthenewstateoccurs,whenthevoltageofpointYjumpsto
5volts,thevoltageatpointZjumpsto10volts!Voltagesacrosscapacitorstaketimetochange;wewillexplorethislater.Attheendoftheoldstate,therewasa5voltdifferencebetweenthetopandbottomofthecapacitor,C.Thetop,pointY,was0volts;thebottom,pointZ,was5volts.Acapacitor’spotentialdifferencecan’tchangeimmediately:ittakestimetochange.So,ifthetopofthecapacitorgetsinstantlyraisedupbypositive5volts,thenthebottomofthecapacitorgetsraisedupbypositive5volts.Thebottomofthecapacitorinstantlyjumpsfrom5voltsto10volts.Thoughvoltagesatbothendsofthecapacitorchangeinstantly,thepotentialdifferencedoesnotchangeinstantly.Attheinstantofstatechange,thevoltagedifference,endtoend,onthecapacitoriskeptthesameastheinstantbeforethestatechange.So,the0voltsatpointXisblockedfromgettingtopointWbythe10voltsat
pointZ.But,howdoesthecircuitoscillatetothereversestate?Thecapacitorcausesthis,too.Voltagesacrosscapacitorsdon’tchangeinstantly,buttheydochangeeventually.Overtime,thevoltageatthepointZendofthecapacitorsettlestothevoltagelevelpointXwants,0volts.Whenitarrivesat0volts,thatvoltage,appliedtopointW,initiatesanewchangeofstate,sothatW=0volts,X=5volts,andY=0volts.Let’stracethenextsequenceofevents.Let’scalltheinstantbeforethenew
stateT-,andtheinstantafterthenewstate,T+.AtT-,therewasa5voltsdifferenceinvoltagefromoneendofthecapacitortotheother.AtT-,pointYwasat5volts,andpointZwasat0volts.AtT+,pointYdropsdownby5volts,to0volts.So,thevoltageatpointZhastodropdownby5volts,too.Itdropsfrom0voltsto-5volts!Ofcourse,the-5voltsatpointZismorethanenoughtopreventthe5voltsat
pointXfromreachingpointW,tostarttherunawayoscillation.Overtime,however,the-5voltsatpointZgraduallyreachesthevoltagelevelsoughtbypointX,5volts.Afterthislengthoftime,that5voltsreachespointW,tostartthenextstate,whichiswherewebeganthisdiscussion.
CHAPTERTHIRTEENCAPACITORS
OnceagainIhavechosentoworkbackwardsinmypresentation.Ihave
chosen,above,toshowthecapacitorinaction,beforeexplainingthedetailsofhowitworks.Hopefully,ithasintriguedyou,andwhettedyourappetitetolearnmoreabouthowthisamazingdeviceworks,asdescribedbelow.If,however,youareimpatienttolearnabouthowmicroprocessorswork,you
canskipoverthenextsectiononcapacitors.Missingoutonitshouldnotpreventyoufromunderstandinghowmicroprocessorswork.Youcanalwayscomebacktothissectionlater,andtreatitasabonuslearningsession,asAppendixD.Ihaveincludedthissectiononcapacitorssoyoucanbetterunderstandhowclockcircuitswork,becauseamicroprocessorhastohaveaclock.Understandinghowcapacitorsworkwillalsohelpyoutounderstandhowcrystal-basedoscillatorswork,inthenextchapter.Capacitorsareveryimportantcomponentsinelectronicscircuits.Withoutthem,
wewouldhavenoelectroniccommunicationsystemssuchasradio,television,andWi-Fi.Theyareusedtocreateandreceivetransmittedsignals,selectivelytunethemin,filterthemfortrebleandbass.Theyprotectourhighspeeddigitalcircuits,likemicroprocessors,fromunwantednoise(radiofrequencyinterference[RFI]).Itbehoovesustogivethemsomeattention.Togetafeelingofhowcapacitorswork,let’sreturntoourwaterfaucetpressure
analogy.Lookatthepicturebelow:
FIGURE13-1Wesaidearlierthatacapacitorslowsdownthechangeinvoltageacrossit.The
simplestanalogywouldbeinthepictureabove.Ihavechangedourwatersystemsothatthevalveopensintoaverylarge,closedvat.Imaginethevatbeingasdeepintothepageasitiswideacrossthepage.Inpart(a),thevalveisclosed.Allthepressurefromthepump,transmittedthroughthewater,pressesagainsttheclosedvalve.Let’scallthepumppressure40psi.Suddenly,inpart(b),someoneopensthevalve.Pressureisnolongeronthe
valve.Iftherehadbeenaplugunderthevalve,attheendofthefaucet,thewaterwouldimmediatelyhaveencounteredtheplug,andthe40psiwouldbeappliedtotheplug.Butthereisnoplug,sothewaterstartstoflowintothevat.Asyoucanseefromparts(b),(c),and(d),ittakestimeforthewatertoflow
intothevat.Bythetimewegettopart(d),thevatisfull.Thepressureonthevatinthepart(d),whenitisfull,is40psi.Acapacitorbehavesalotlikethisvat.Insteadofwaterflowing,currentflowsin
acapacitor.Insteadofwaterpressurebuildingup,chargebuildsupacrossacapacitor,creatingelectrical“pressure.”Inbothsystems,flowcontinuesuntiltheyare“full.”Lookatthefollowingfigure,toseeapictureofacapacitor:
FIGURE13-2
Thecapacitorisontheright,inFigure13-2.Itisridiculouslysimple,andyet
ridiculouslycomplex,atthesametime.Itismathematicallycomplex.TheDCcircuitequationforitis:
VC=Vinx(1-e-t/(RxC))
whereeistheexponentialfunction.InsteadofthesimpleV=IxRequationthatdescribesaresistor,thecapacitorrequiresanequationbasedoncalculus.TheACcircuitequationsforitusethecomplexnumbersystem.Andyet,thecapacitoritselfissosimple.AsseeninFigure13-2,itconsistsof
twometalplates(conductors),separatedbyaninsulator.(Thethreepartsofacapacitorareoftenformedintoaninnerconductivecylinderandanouterconductivecylinder,withaninsulatingcylinderbetweenthem.)Rememberthataconductorislikeawire:currentflowssoeasilythatitoffersnoresistancetocurrentflow.Aninsulatoristheopposite:itpreventscurrentflow;theinsulatoroffersinfiniteresistancetocurrentflow.Acapacitorisanenigma.Ifyoustareatthecircuitabovelongenough,you
eventuallyrealizethatitisanopencircuit!Inaway,it’snota“circuit”atall,becausecurrentcannotmakeacomplete“circle.”Itcan’tgetthroughthe
capacitor,becausethecapacitorhasaninsulatorinthemiddle.Thecapacitorlooksmorelikeanopenswitch,andanopenswitchissomethingweusetostopcurrentflow.Infact,currentneverflowsthroughacapacitor;itonlyflowsuptoitsplates.Currentflowsthroughotherelectronicdevices,butnotthroughacapacitor.Andyet,capacitorscanbeusedlikeresistorsinAC(voltagesinewave)circuitstocontrolcurrentflow.Perhapstheplacetobegininunderstandingacapacitoriswithanopenswitch.
Lookatthepicturebelow:
FIGURE13-3
Hopefully,yourememberthecapacitorsymbolfromFigure12-2,whereyoufirst
sawit.It’sinthelowerrighthandofpart(b).Itlookslikearealcapacitor:twometalplatesseparatedbyaninsulator.Justliketheopenswitchcircuitinpart(a),thecapacitorcircuitinpart(b)arrives
atthesameendresult.Boththeopenswitchandthecapacitorwindupwith5voltsacrossthem:thesame5voltsasthebatteryhas.Bothresistorswindupwith0voltsacrossthem,because,intheend,nocurrentflowsthrougheitherone.Nocurrentmeansnoworkbeingdonemovingelectronsthroughtheresistor,whichmeansnovoltage,sincevoltageisworkpercoulombofcharge.So,whatisthedifferencebetweentheswitchandthecapacitor?Thedifference
issize.Thesizeoftheswitchconnectionstothecircuitissmall.Thesizeofthecapacitor’sconnectiontothecircuitisrelativelyhuge:itisthebigmetalplatesthatmakeupthebodyofthecapacitor.Now,wearegettingsomewhere.Lookatthepicturebelow:
FIGURE13-4
Figure13-4isthecapacitorversionofFigure13-1,thewatervalve.InFigure
13-4,thebatteryandtheresistoraredrawnwithcircuitdiagrams,whilethecapacitorisdrawnasaphysicalcapacitor.Part(a)showstheinstantoftimewhenthebatteryhasjustbeenconnectedtotherestofthecircuit,byattachingawireatpointA(Icould,instead,havedrawnaswitchbeingclosed).Beforethispointintime,chargewasbuiltuponbothbatteryplates,tryingtogetawayfromlikecharges.Electronsonthenegativeplateswanttogetawayfromotherelectrons.Positivelychargedatomsontheotherplateswanttogetawayfromotherpositivelychargedatoms.Attheinstantoftimeinpart(a),thechargesfirstgettheirchance.The
electronsonthenegativebatteryplate,repulsedbyeachother,moveoutintotheattachedwire.Thecapacitor,atthispointintime,isneutraloneachplate:allitsatomsareexactlyinbalancewithnoexcesspositiveornegativecharge.So,ithas0voltsacrossit.But,currentisflowinginthisopencircuit!
Currentisthemovementofelectrons.Theelectronsonthenegativeterminalofthebattery,repulsedbyeachother,leavetheterminal,andheadtowardthebottomplateofthecapacitor.Thebottomplateofthecapacitoris“attractive”tothenegativecharge,sincezerochargeisbetterthanthenegativechargeonthebatteryterminal.Theelectronsinthewireheadthatway,too,forthesamereasons,andtogetawayfromthenegativechargeheadingtheirway.Meanwhile,onthetopcapacitorplate,thenegativelychargedelectronsinthe
neutralatomsfeeltheattractiontothepositivelychargedatomsonthepositivebatteryplate.Theystartmovingtowardthepositiveplate.Theelectronsinthewireheadthatway,too,forthesamereasons,andtogetawayfromthenegativechargeheadingtheirway.FocusonFigure13-4,part(a).Remember,thisisthefirstinstant,whenthe
batteryatpointAisfirstattachedtothecircuit.Theminussignsinsidecirclesaretheelectronsinmotion;thearrowspointinthedirectionofcurrentflow.Inpart(a),noticethevoltagesaroundthecircuit:5voltsacrossthebattery,5
voltsacrosstheresistor,and0voltsacrossthecapacitor.WeneedtounderstandthisintermsoftheLawofConservationofEnergy,whichwediscussedinFigure5-5.OurelectronicsversionofthislawiscalledKirchhoff’sVoltageLaw.Itstates
thatthesumofallthestoredenergyinourcircuitatanyinstantoftime,mustequalthesumofalltheworkdoneatthatinstant.Weknowthatthe5voltsacrossthebatteryisanenergyinputthatremains
fixed.Itisduetotheseparationofchargestoredonitsplates,constantlyreplenishedbytheinternalchemicalreaction,evenwhenchargeleaves.Thecapacitorisnotaresistor:noworkiseverdoneingettingcurrentthrough
it,becausecurrentcan’tgothroughitsopencircuit.Inpart(a),noenergyisstoredinthecapacitoryet.So,sinceinpart(a)thecapacitoraccountsfornoenergyorwork,itsvoltageis0volts.Thisimpliesthatthevoltageacrosstheresistormustbe5volts.Thisis“work
done”voltage.Alltheenergyinthebatteryisappliedtotheresistorasworktomovecurrentthroughit.SinceI=V/R=5/50=.1,then.1ampsofcurrentflowsinthisopencircuit,attheinitialinstantdepictedinpart(a).Now,thingsgetevenmoreinterestingashorttimelater,asshowninpart(b).
Excesselectronshaveenteredthelowercapacitorplate.Therearemoreelectronsthanatoms,sowehaveatomsthatarenegativeions.Thelowercapacitorplatetakesonanegativecharge,likethenegativechargeonabatteryplate.Alsoinpart(b),theuppercapacitorplatetakesonapositivecharge,likethe
positivechargeonabatteryplate.Thisoccursbecausesomeelectronshaveexitedforthepositivebatteryplate,leavingbehindatomsontheuppercapacitorplatethataremissinganelectron(positiveions).
HaveyounoticedthatthewordsIhaveusedtodescribethecapacitorsoundlikethewordsIhaveusedtodescribethebattery?It’strue.Thecapacitorisbecominglikethebattery.Recallourdefinitionofabattery’svoltageas,“aseparationofcharge.”Aseparationofchargeis,indeed,buildinguponthecapacitor’splates.Thedifferenceis,thesourceofthechargeseparationisexternalforthecapacitor:itcomesfromthebattery’scurrent.Thesourceofthebattery’schargeseparationisinternal:itcomesfromitschemicalreaction.Figure5-5hadonebattery(B)andtworesistors(R1andR2),connectedin
series.WecandescribethevoltageacrossthebatteryasVB,thevoltageacrossR1asVR1,andthevoltageacrossR2asVR2.UsingKirchhoff’sVoltageLaw(KVL),wedescribedthatcircuitmathematicallyas:VB=VR1+VR2.
Weputthevoltagefromtheenergyinputdevice,thebattery,totheleftoftheequalsign.Weputthevoltagefromtheworkdonegettingthroughthetworesistorstotherightoftheequalsign.Howdowecreateasimilarequationtohandlethecapacitor?Ihavealready
saidcurrentneverisforcedthroughacapacitor,sonoworkisdonetoit.Itisabsorbingchargeonitsplates.Itisbecominglikeabattery.So,itsvoltagebelongsontheleftsideoftheequation,withthebattery,anenergy(charge)storagedevice.Beforeweputitthere,though,lookbackatFigure13-4.Ifyoutracethroughthe
circuit,youwillfindthatthechargeonthecapacitorpointsintheoppositedirectionasthechargeonthebattery.Thepositiveendofthebatteryisclockwiseofthenegativeend.Thepositiveendofthecapacitoriscounter-clockwiseofthenegativeend.So,thecapacitor’svoltagebelongsontheleftsideoftheKVLequation,butwithanegativesign,asinVB-VC=VR,whereVCisthevoltageacrossthecapacitor,VRisthevoltageacrosstheonlyresistor,andVBisthebatteryvoltage.Usually,though,wemovetheVCtotherightsideoftheequationusingalgebra,toarriveattheequationforthecircuitinFigure13-4:VB=VR+VC.
Comparingthisequationtopart(b)ofFigure13-4,weseethatthevoltagedistributiondoes,indeed,obeytheequation:2voltsacrossthecapacitor(VC)plus3voltsacrosstheresistor(VR)doesinfactequalthevoltageacrossthebattery(VB).Thecapacitorisactinglikeananti-battery.
Withthisinmind,lookatthenumberofmovingelectronsIhavedrawninpart(b)comparedtopart(a).Ihavedrawnlessmovingelectronsinpart(b).Inthelatertimedepictedbypart(b),lesscurrentisflowingthanintheinitialtimedepictedbypart(a).Whyisthistrue?Becausetheamountofcurrentflowinginthiscircuitis
controlledbytheresistor.Ohm’sLawstatesthatI=VR/R.But,VRhaschanged
sincepart(a).VRwas5voltsatthetimeofpart(a),butnowVRisonly3voltsatthelatertimeofpart(b).So,thecurrentnowisonly3/50=.06amps.Before,inpart(a),itwas.1amps.Therisingvoltageacrossthecapacitorsubtractsfromthefixedvoltageacrossthebattery,leavinglessnetenergy(3volts)todrivecurrentthroughtheresistor.Thecurrentflowrateisslowlybeingchokedoff.Wecallthefillingupwithcharge,andtheriseofvoltageacrossthecapacitor,
“chargingthecapacitor.”Inthiscircuit,thecapacitor“charges”morequickly,atfirst,thenmoreslowly,astimegoesby.It’sasifthecapacitorisabucket,andwater(current)isflowingintoit.Carryingthisanalogyfarther,it’slikesomeoneisholdingthehose,andgraduallyputtingmoreandmoreofakinkinthehose,untiliteventuallychokesoffallwaterflow,completely.Inpart(c)ofFigure13-4,theprocesscontinues.Thecapacitorhaschargedup
to4volts,thebatteryisfixedat5volts,soonly5-4=1voltnetenergyislefttoappearastheworkvoltageacrosstheresistor.ThisproducesevenlesscurrentflowthoughR.Consequently,Ihavedrawnevenlesselectronsmovinginpart(c).Thisprocessendswhenthecapacitorisfullycharged.Whendoesthat
happen?Whatdoes“fullycharged”evenmean?Well,theprocessendsinpart(d)ofFigure13-4.Thecapacitorisfullychargedwhennomorecurrentisgoinginoroutofitsplates.NoticethatIhavedrawnnomovingelectronsinpart(d).Theendofcurrentflowhappenswhenthevoltageacrossthecapacitorexactlyequalsthebatteryvoltage.Sincethecapacitorvoltageasanenergysourcesubtractsfromthebatteryvoltageasanenergysource,5-5=0,andzeroenergyisavailabletodotheworkofpushingcurrentthroughtheresistor.Hence,thereis0voltsacrosstheresistor.SinceI=VR/R=0/50=0,thereis0ampsofcurrentflowing.Thecapacitorisfullychargedorasfullofstoredcurrentasitcanget,inthiscircuit.Hopefully,younoticedthatIdrewmoreandmorechargesymbolsoneither
sideofthecapacitoraswemovedfrompart(a)throughpart(d).Ofcourse,thisrepresentsthecapacitorfillingupwithcharges,positiveandnegative,asitbecomesmoreandmorelikethebattery.Withtheseplusandminussymbolsonthecapacitor,andthecapacitorfully
chargedto5volts,perhapsnowisagoodtimetoconsiderwhatitmeansforthecapacitorbeat5volts?Howisitdifferentfromthecapacitorbeingat2volts?Thisbringsustotheessenceoftheconceptofvoltage.Voltageisdirectlyrelatedtochargedensity.So,onboththebatteryandthe
capacitor,ahighervoltagecorrelatestomorechargebeingcrammedclosertogether.Theclosertogether(density)chargecanbecrammed,thestrongertheforcetheyexertontryingtogetapart,onproducingcurrentflow.So,whenthecapacitorreaches5volts,ithasreachedthesamechargedensityasthebattery.Canwemakethatthechargedensitythatwedescribeas5voltsharderto
reach?Stateddifferently,canwedoanythingtoincreasethetimeittakestogetthechargedpackedtogetherthisclosely?
Thinkbacktotheanalogyofwaterflowingthroughahose,intoabucket.Whataretwowaystoincreasethelengthoftimeittakestofillupthebucket?Onewayistomakethewaterflowmoreslowly.WecandothatbyincreasingthevalueofR,theresistorinthecircuit.Currentwillflowmoreslowly.Itwilltakealongertimeuntilthecapacitorreachesfullychargedat5volts.Thesecondwayistogetabiggerbucket.Allotherthingsbeingequal,abigger
buckettakeslongertofillthanasmallerbucket.Thecapacitorislikethebucket.Acapacitorcanbemadebiggerbyincreasingtheareaofthecapacitor’splates.So,ifwegetabiggercapacitor,therewillbemoreroomforthechargestokeeptheirdistancefromeachother.Itwilltakemoretime,andmorecurrentwillhavetoflow,untilthechargesarepackedtogethercloselyenoughtobecalled5volts.Theseconceptsareembeddedinthestrangeequationwereferredtoabove:
VC=Vinx(1-e-t/(RxC)).Theesymbolisafunctionthatdescribeshowthecapacitorchargesupquicklyatfirst,thenmoreslowlyastimegoesby.TheRxCdescribeshowbothRandC,theresistor(R)inohmsorthecapacitance(C)infarads,controlthechargingrate.Howlongdoesittakeforthecapacitortobefullycharged?Fromtheabove
equation,weknowthatthecapacitorreaches63%offullycharged,or3.15volts,inRtimesCseconds.Inourcircuit,RtimesCis50x.000010,or.0005seconds.Butremember,capacitorschargequicklyatfirst,andthenthechargerategraduallyslowsdown.Ittakesamuchlongertimetofinishthelast37%or1.85voltsofcharging.Infact,ittakes5timesRtimesCforthecapacitortogofromnochargetofullycharged.Thatcalculatesas5x.0005,or.0025seconds.Ifyouwantthe10microfaradcapacitortotakeawholesecondtoreachfullycharged,justreplacethe50ohmresistorwitha20,000ohmone.Youcanactuallydisconnectthechargedcapacitorfromthecircuitandwalk
aroundwithit.Itwillholdthechargeforagoodwhile,untiltheelectronsslowlysneakthroughtheinsulator.Insulatorsarenotperfect,notinfiniteohmsofresistance.Theaboveexperimentofcarryingaroundachargedcapacitorisnotagood
idea.Capacitorscanholdenoughenergytokillyou.That’swhycomputerpowersuppliessometimeshavelabelsonthemwarningpeoplenottoopenthem,evenwhendisconnectedfrom120voltlinevoltage.Peopledon’tknowthatcapacitorscanstorevoltageevenwhentheexternalinputvoltageisoff.Youcandischargeacapacitor.Ifyouputaresistoracrossachargedcapacitor,
itwillbehavelikeabatterywitharesistoracrossit.Theelectronsbuiltuponthenegativeplatewillscurrythroughtheresistor,overtothepositivecapacitorplate.Thishappensbecausetheelectronsonthenegativeplatepushawayfromeachother,andarepulledtowardtheoppositelychargedpositiveionsonthepositiveplate.There’sonebigdifferencebetweenthecapacitorandthebattery,though.The
batteryhasitsinternalchemicalreactiontoreplenishtheseparationofchargeonitsplates.Thecapacitordoesnot.Wheneachatomonthecapacitor’splatesgoesfrombeinganiontobeinganeutralatom,itisdone.Nointernalchemicalreactionrestoresthecapacitor’sneutralatomstoanionicstate.Thewholecapacitorreturnstoneutral,to0volts.Howlongdoesthiscomplete
dischargetake?Usethesamecalculation:5timesRtimesC.Ifyouwanttodischargethecapacitorquickly,justputawireacrossit.(Remembertheearlierwarningabouttouchingchargedcapacitors,though.)Sinceawire’sresistanceis0ohms—and5timesRtimesCis0xC,or0seconds—thecapacitorwilldischargeinstantly,probablywithaspark.Thecapacitor’sdischargeratethrougharesistorisanexponentialfunction,just
likethechargerate.Thismeansthatthecapacitordischargesmorequicklyatfirst,thenmoreslowly,untilitiscompletelyemptyofcharge.Theequationtodescribeallthisis:
VC=VTxe-t/(RxC)
AsImentionedearlier,capacitorsareveryimportantincommunications
electronics,becausesound,video,andradiofrequencyallhavetodowithsinewaves.OurACvoltagethatweaccesswheneverweplugintoanelectricalwalloutletisalsoasinewave.Capacitorsworkstrangelywellwithsinewaves.Asinewaveofvoltagecauses
currenttoflowfromoneofthecapacitor’splatestotheother,inonedirection.Butthen,thesinewaveofvoltageswitchespolarity,sucksthechargeoutofthecapacitor,andcausescurrenttoflowfromplatetoplateintheoppositedirection.Thisforwardandreversedirectionofcurrentflowinacapacitorislikethe
forwardandreversedirectionofcurrentflowofaresistorexcitedbyACvoltage(sinewaves).Fromthepointofviewofthewiresandtheothercomponentsinthecircuit,theyhavenoideathatthecurrentflowingintoandoutofthecapacitorbranchisnotgoingthroughthebranch.Thecapacitorisanopencircuit,sothecurrentisjustgoingbackandforth,intotheplates,thenbackout.Theonlydifferenceisaphaseshift.Theadvantageofthecapacitorovertheresistoris:thecapacitorconsumesnopower.Itdoesn’tgethot.Oneotherstrangethingaboutacapacitoristhatwecanincreaseits
capacitancevalue—thusincreasingitschargingtime—bychangingitsinsulatormaterial.Theoppositechargeonthetwoplatescreateanelectricalfieldofattractionfromoneplatetotheother.It’sliketwomagnetswiththenorthpoleofonepullingtowardthesouthpoleoftheother.Inthecapacitor,theinsulator(calledthedielectric)isinbetween;asolidinsulatorstopsthetwoplatesfrompullingtogetheruntiltheytouch.Theelectricalforcefieldproducesastrangeeffectontheinsulator.Itcauses
theindividualmoleculesintheinsulatortoturn,andevenstretch.Theinsulator’smoleculesbecomemorepositiveonthesideclosertothenegativeplate,andmorenegativeonthesideclosertothepositiveplate.Themolecules,inturn,createacounter-fieldproducedinsidetheinsulator.Thepositivechargeintheinsulator’sturnedandstretchedmoleculescreatesapositiveelectricalfieldthatreachesintothenegativeplateandcancelsoutsomeofitsnegativestrength.Thenegativechargeintheinsulatorcreatesanegativeelectricalfieldthatreachesintothepositiveplateandcancelsoutsomeofitspositivestrength.Witheachplate’srepulsiveenergyweakened,morechargeisneededforittoreach5volts(inourexample).Agreaterchargedensityisneededtoarriveatanetmutualchargerepulsionwhichwecall5volts.Someinsulatormaterialsaresimplybetterthanothersatcreatingtheabove
effect.Themoleculesinsomeinsulatorsstretch,turn,andalignbetterthanmoleculesinotherinsulators.Witha“better”insulator,currenthastoflowlonger,tofillthecapacitor.Lesssubtly,thecapacitor’splatesthemselvescausethissameeffectoneach
other.Thepositiveplate’spositiveelectricfieldsubtractsfromthenegativeplate’snegativeelectricfield,andviceversa,allowingmorecurrenttoflowbefore5voltsisreached.Furthermore,positiveandnegativeelectricforcesofattractionandrepulsionincreasewithlessdistancebetweencharges(aninversesquarelaw).So,bringingthepositiveandnegativeplatescloserintensifiesthiseffect,increasingcapacitanceandchargingtime.
CHAPTERFOURTEENTHECRYSTALCLOCK
Whilewearelookingatstrangeeffects,let’slookatsomethingevenmore
strange:thepiezo-electriccrystal.Thepiezo-electriccrystalisthestrangestcomponentyouneverheardof.Firstofall,thereasonwewilldiscussthepiezo-electriccrystalisthatitisused
tomakeabettersystemclock.TheclockinFigure12-2issufficientinsomemicroprocessordesigns.Itisveryinexpensive.Butithassomeshortcomingsthatmakeitundesirableinsomeapplications.First,heataffectsthecircuitinFigure12-2.So,astemperatureschangearound
thecomponents,theirvalueschange,whichchangestheoscillatoryfrequency.Also,designingthecircuittoaspecificfrequencyisdifficult,becausetheaccuracyofcapacitorvaluesisnotverygood.A10microfaradcapacitormightbeplusorminus20%ofitsratedcapacitancevalue.So,weoftenuseclocksdesignedaroundpiezo-electriccrystals:crystalclocks,
astheyarecalled.Thoughnotperfect,theytendtobelesstemperature-sensitiveandmoreaccuratethanclocksliketheonesinthecircuitofFigure12-2.Here’swheretheweirdnessstarts.Thepiezo-electriceffectisthecreationof
voltagebypressingonacrystal.Quartzcrystalsworkwellforthis.Weknowthatvoltageisaseparationofcharge.Well,ifyoucutacrystaljustright,andapplyapressuretoit,chargegetsseparated,andasmallvoltageisproducedacrossthecrystal.But,theweirdnessdoesnotendhere.Theoppositeeffectalsoexists.Thatis,if
youapplyavoltageacrossacrystal,itwillcompress.So,whatwehaveistwooppositeweirdnesses,whichwecombinetogetherto
createanoscillator:1.)Voltagemakescompression2.)Compressionmakesvoltage
Here’showitworks.Avoltagesourceisappliedtooppositesidesofthecrystal.Let’susetheexampleofabatteryconnected,throughwirestothecrystal.Nowthatyouunderstandaboutcapacitors,thinkofthecrystalasifitwerea
capacitor.Apositivechargebuildsuponthesideofthecrystalconnectedtothepositivebatteryplate.Anegativechargebuildsuponthesideofthecrystalconnectedtothenegativebatteryplate.Aswiththecapacitor,anelectricfieldofattractionbuildsupfromthepositivetothenegativesideifthecrystal.Theytrytomovetowardeachother.Ofcourse,thecenterpartofthecrystalisintheway.So,thecenterpartofthecrystalgetssqueezedbytheouterpartsofthecrystal.Thisexplainshowstep1works:howvoltagemakescompression.Wedon’t
squeezethecrystalwithavice.Wesqueezeitwithanelectricfield,whichtriestopullthesidesofthecrystaltowardseachother.
Step2saysthatthiscompressioncausesaseparationofchargeinthecrystal.Negativechargeinthecrystalmovestowardthepositivesideofthecrystal,andpositivechargeinthecrystalmovestowardthenegativesideofthecrystal.Thischargefromwithinthecrystalcancelsoutthechargefromoutsidethecrystalsuppliedbythebattery.Tosummarize,thebatteryputschargeonthesidesofthecrystal;thecrystalcompresses;thecompressioncreateschargethatcancelsthechargeonthesidesofthecrystal.Ofcourse,withthechargegoneonthesidesofthecrystal,theelectricfieldof
attractionisalsogonebetweenthetwosidesofthecrystal.Theystopsqueezingtheinsidesofthecrystal.Thecrystalrelaxestoitsnatural,unsqueezedstate.Theseparationofchargethatresultedfromthesqueezingisgone,too.Infact,everythinghasgoneaway.Everythinghasreturnedtowherewestarted.
But,thebatteryisstillthere,andthebatteryisstillconnectedtothecrystal.So,theentireprocessstartsallover.Steps1and2startallover.Thebatteryonceagaincausesaseparationofchargeonthesidesofthecrystal,etc.Thepicturebelowsummarizestheexplanation:
FIGURE14-1
Part(a)isthevoltageapplied.Part(b)istheelectricfieldfromthecharge
separationcausingthecompressionofthecrystal.Part(c)isthecompressioncreatingacounter-voltage.Part(d)isthedecompressionanddischargeofthecrystal,readytorestartthecycle.Thepictureletsyouseetheoscillation.InFigure14-1part(a),currentflows
counter-clockwise;inpart(c),itflowsclockwise.Inpart(b),thecrystalhasmaximumpositivechargeontopontopandnegativechargeonthebottom;inpart(c),thecrystal’scounter-voltageisneutralizingthechargeontheplates.Aclockbuiltwithaquartzcrystalneedssomeextracircuitrytosupportthis
magic.IfyouimaginearesistorinthepathofcurrentflowinFigure14-1,youmayrealizethatavoltagemoreakintoanACsinewaveappearsacrossit.So,additionalcircuitryturnstheoscillationintoadigital,orsquarewave.Thecircuitryalsohelpssustaintheoscillation.
CHAPTERFIFTEENTHEFLIP-FLOP
Let’sreturntoourmicroprocessorsystemofFigure8-1.Remember,wejust
addressedthequestionofhowamicroprocessordoesthingssequentially.Weshowedthatamicroprocessorusesadigitalclock,tobreakstepsdownintoticksofasquarewavecycle.But,howdoweconvertthisstringofvoltagechangesononewire,theclockoutput,intoseparatevoltagesthatenable—inorder—fetch,thendecode,thenexecute?Toanswerthatquestion,firstlookbackatfigures10-1through10-3.They
depictour2-to-4binarydecoder.Whatifwehadadevicethatcouldcountourclockpulses,andoutputthatcountvalueinbinary?Wecouldfeedthatbinaryoutputasaninputtoour2-to-4binarydecoder.Wewouldgetsequentialpulsesoutofour2-to-fourbinarydecoder:Q0,thenQ1,thenQ2,thenQ3,thenbacktoQ0,etc.We’llexplorethatdesignlater,butthenameforthedeviceweneedisthe
binarycounter.Wehaveanotherneedforabinarycounter.InourreviewofourmicroprocessorsysteminFigure8-1,wereferredtotheprogramcounter.Thiswasabinarycounter,too.Itlookslikeanunderstandingofabinarycounterisanimportantpartofunderstandinghowamicroprocessorworks.Tocreateabinarycounter,wemustfirstintroduceare-designofourDlatch.
OurcounterwillrequireconnectingtheNOTQoutputbackintotheDinputwhenEisenabled.Thattrickjustwon’tworkwithaDlatch.IfyoureviewtheDlatchcircuitwaybackinFigure7-10,youwillfindthe“dogchasingitstail”effect,again.AlowNOTQfedbacktoDimmediatelymakesNOTQhigh;which,feedingbacktoDimmediatelymakesNOTQlow,etcetera,adinfinitum.WemustturnourDlatchintoaDflip-flop.What’sthedifference?Inalatch,as
longastheE(enable)inputishigh,theQoutputreplicatestheDinput.IftheDinputchangesahundredtimes,theQoutputchangesahundredtimes.WhatevervaluewasontheDinputandQoutputwhentheEwindowcloses(goeslow)isthevaluestoredattheQoutput.Fortheflip-flop,wegetridoftheE(enable)inputandreplaceitwiththeclock,
orCLK,input.Soundslikeitwasdesignedspecificallyasthedestinationforthedigitalclockwejuststudied,doesn’tit?Next,wedecideifitwillbepositiveedgetriggeredornegativeedgetriggered.Wechoosepositiveedgetriggered.Ournew,positiveedgetriggeredflip-floponlyallowsthevalueattheDinputto
transferandbestoredattheQoutputatoneinstantoftime.Thatinstantis:everytimethevoltageatCLKrisesfrom0voltsto5volts.NotransferorstoragehappenswhileCLKsitshigh;alatchdoesthat,andthisisnotalatch.NotransferorstoragehappenswhileCLKsitslow.NotransferorstoragehappenswhenCLKfallsfrom5voltsto0volts.
It’scalled,“positiveedgetriggered”becauseapositive-goingCLKvoltageinitiatesthechange.Neitheranegativenorapositivevoltageinitiatesthechange.AvoltageleavingnegativeandgoingtowardpositiveinitiatesatransferandstorageoftheDinputvalueintotheQoutput.Thepicturebelowwillhelpclarifyallthis,ifitisstillunclear:
FIGURE15-1
Figure15-1showsthelogicsymbolfortheDflip-flop.NoticetheCLKlabelthat
replacestheEsymbolweusedforthelatch.Also,noticethelittlewedgenexttotheCLKlabel.Thiswedgeletsusknowthatthisdeviceisedge-triggered.Iftherewasalittlebubbletotheleftofthewedge,thatwouldtellusthisdeviceisnegativeedgetriggered.Thisoneispositiveedgetriggered.LookcarefullyatwhatiscomingintotheCLKinput.Readtheinputasvoltage,
vertically;with0voltsatthebottom,and5voltsatthetop.And,readitastime,horizontally;withpasttofuturefromlefttoright,respectively.Thus,earlyintime,
thevoltageis0volts.Atransitionfromlowtohighhappens,alongtheup-arrow.Laterintime,afterthetransition,thevoltageis5volts.NoticehowIhavetheup-arrowcircled.Thisisthekeyinstant,theexactand
onlytimetheDflip-flopisopenedupforstorage.Followthecurvingarrows.Theyindicatethat,atthecriticaltimeofthepositive-goingvoltageedgeonCLK,the1onDtransferstotheQoutput.Asalways,theNOTQoutputbecomestheoppositelogiclevelofQ,soitbecomes0.ThevaluescrossedoutaretheoldvaluesofQandNOTQ,frombeforetherisingedgetriggeredtheirchanges.ThepicturebelowshowshowtoputNANDgatestogethertocreateaDflip-
flop:
FIGURE15-2
Iwon’tgothrough,step-by-step,howtheDflip-floptriggersonlyontherising
edgeoftheCLKinput.Itwouldtaketoolong,andyoucandoitforyourself,ifyoulike.Noticeafewthings,though.Thecross-coupledNANDpairs(1and2,3and
4,and5and6)areRSlatches.Thistime,theyaremadefromNANDgatesinsteadofNORgates.Theyfunctionthesameway,excepttheNANDpairshavetheSinputsacrossfromtheQoutput,whereastheNORpairshavetheRinputsacrossfromtheQoutput.Withthisinmind,Figure15-2almostsimplifiestothreeinterconnectedRS
latches.Isay“almost,”becauseNANDgate3isalittledifferent.Itisa3-inputNANDgateinsteadofa2-inputNAND.
CHAPTERSIXTEENCOUNTERS
So,IsaidweneededthisDflip-flopsothatwecanconnecttheNOTQoutput
backtotheDinput.Itwillbecomeanessentialpartofourbinarycounter,anditovercomesthe,“dog-chasingits-tail,”problem.Let’smakethisconnection,andseewhatweget:
FIGURE16-1
Let’sgetcomfortablewiththisfigure.AtthetopisourDflipflop,withtheNOT
QoutputconnectedbacktotheDinput.Atthebottomarethreevoltagewaveforms.Thesearereferredtoas,“timingdiagrams.”Iwillusethisterm,becauseitemphasizesthefactthatthehorizontalaxisrepresentstime.Earliertimestartsontheleft.Later—orfuture—timemovestotheright.Also,thethreewaveformsalignvertically.Youcanputyourfingeronanyonewaveform,thenmoveitupordowntoseetheexactvoltagestateoftheothertwowaveformsatthesameinstantoftime.Youcanalsocallthisavoltagewaveform,becausetheverticalaxisrepresents
voltage.Sincethisisdigitalvoltage,wereallyonlyhavetwopossiblevoltages.Thetopofeachsquarewaveis5volts(logical1,orhigh),andthebottomofeachsquarewaveis0volts(logical0,orlow).Thethickarrowsshowfromwhereeachwaveformoriginates.Remember,the
waveformsareverticallyalignedsothatwecanobservewheneventshappeninrelationtoeachother,atthesameinstantoftime.WewanttoseetheeffectoftyingtheNOTQoutputbacktotheDinput.Becauseofthisconnection,thebottomwaveformislabelledbothasDandasNOTQ.Weknowthataflip-floptransfersthevoltageontheDinputtotheQoutput,but
onlyduringtheinstantoftransition,therisingedge,ofvoltageontheCLKinputfromlowtohigh.ButwhatisontheDinputistheNOTQoutput.And,theNOTQoutputisalwaysoppositeoftheQoutput.So,everyrisingedgeontheCLKinputforcestheQoutputtoitsoppositelogicstate.Wecallthisstate-flippingoneveryclockedge,“toggling.”Thetimingdiagramshowsthis.LookatthelinelabelledCLK.Thenlookatthe
rising(lowtohigh)edgesofCLK.Ihaveplacedthin,verticalalignmentmarkersundertheseedges.NoticehowQonlychangesstateduringtheseinstantsoftime.WatchhowthestateofNOTQbeforethisinstantbecomesthestateofQafterthisinstant.SeehowwhenQgoestoonelogicstate,NOTQalwaysgoestotheoppositestate.ThisensuresthatQwillalwayschangetoitsoppositelogicstate,ateachrisingCLKedge.What’sthepointofallthis?Followtheskinnyarrows,leadingfromeachrising
edgeofCLK.Readinglefttoright,theskinnyarrowsaretellingusthatthefirstedgemakestheQoutput0,thesecondedgemakestheQoutput1,thethirdedgemakestheQoutput0,etc.Theflipflopiscounting!It’sonlya1-bitcounter,liketheleastsignificantbitina
largercounter.Butremember,availablebinarynumbersendat1.Thenextnumber,after1,is:resetto0,thencarrya1tothenextmoresignificantbit.Wehavejustaccomplishedthe“countupto1”part,andthe“resetto0”part.Allwe
needtodonowisaccomplishthe“carrytothenextmoresignificantbit”task.Solet’sdothat.Seethenextpicture:
FIGURE16-2
NowwehavetwoQoutputs,soIhavelabelledthemQ1andQ0.A2-bitbinary
countercountslikethis:00,01,10,11.Thenitgoesbackto00,andcountsthesamesequence.Thesebinarynumberscorrespondtodecimalnumbers0,1,2,3.Q1isourmostsignificantbit,andQ0isourleastsignificantbit.Itiscounting!Proveittoyourself.LookattheQ1andQ0linesofthetiming
diagram.Readfromlefttoright,andreadQ1beforeQ0.Youwillseethatthecountsare:00,01,10,11,00,01,10,11.Toaccomplishthisdesign,weaddedasecondDflip-flop,ontheright.Its
outputisQ1,ourmostsignificantbit.WeconnecteditsQ1outputalongwiththeunchangedoutputofouroriginalflip-flop(re-labelledQ0)asinputstoan
exclusive-ORgate.Wethenconnectedtheoutputoftheexclusive-ORgatetotheinputofthenewflip-flop.Weknowthecircuitcountsproperly,buthowdoesitwork?Perhapsthepicture
belowwillhelp:
FIGURE16-3
Part(b)ofFigure16-3isthetruthtableforanexclusive-ORgate.Wewillneed
torefertoit,sincetheQ0andQ1outputsbothenterit.Part(a)showstheconsecutivecountsofthecounter,outofQ1andQ0.Inpart(a),weknowthattheQ0columnalternatesina0-1-0-1…etc.pattern.
Wecalledittoggling,andlearnedaboutitinFigure16-1.Whatwemustdoisexplainthenewpart,theQ1column.Lookatthefirstrowofpart(a).Itis0-0,theoutputofQ1-Q0.0-0isfedintotheexclusive-ORgate(XOR).Thefirstrowofpart(b)tellsusthattheoutputoftheXOR—thustheDinputtotheQ1flip-flop—is0.Thismeansthat,uponthenextrisingclockedge,a0willcomeoutofQ1.That’swhyinpart(a)Ihaveabigcirclearound0-0inrow1,withanarrow
pointingtoasquareinrow2witha0insideit.The0-0(pertheXORtruthtable)makesQ1equal0inthenextrow,onthenextclockpulse.Inrow2ofpart(a),the0-1(pertheXORtruthtable)makesQ1equal1inrow3,onthenextclockpulse.Inrow3ofpart(a),the1-0(pertheXORtruthtable)makesQ1equal1inrow4,onthenextclockpulse.Inrow4ofpart(a),the1-1(pertheXORtruthtable)makesQ1equal0inrow1,onthenextclockpulse.Nowthatyougettheideaofwhatcountersareandhowtheywork,I’llskipthe
detailedexplanationsofthenextones.Amicroprocessor’sprogramcountercanbeprettybig.Forabigaddressablememoryspace,a64-bitcounterisnotuncommon.I’llshowyouacircuitdiagramfora4-bitcounter,below:
FIGURE16-4
Theabovecounterrepeatedlycountsfrom0000to1111,soithas16distinct
counts:24.Thetoptwoflipflops,forQ0andQ1,arethesameasinFigure16-2.Toexpandthiscountertomorethan4bits,justfollowthesamepattern.AddmoreAND’s,XOR’s,andDflip-flopswiththesamewiringpatternasinFigure16-4.Forourfetch-decode-executesequence,weneedacounterthatcountslike
this:00-01-10.Forthat,wecanusethefollowingcircuit:
FIGURE16-5
Wehavebeenreferringtoourcountersinfigures16-1,16-2,and16-4as1-bit,
2-bit,and4-bitcounters,respectively.IfwecallthecounterinFigure16-5a2-bitcounter,peoplewilltendtothinkithas22=4distinctcounts.Butitdoesn’t.Ithas3distinctcounts:00-01-10.Weshouldinsteadcallitamodulo-3counter.Acounter’smodulusnumberisthenumberofdistinctcountsithas.Wecould,forexample,havecalledour4-bitcounterinFigure16-4amodulo-16counter.Becarefulifyoudecidetofigureouthowtheabovemod-3counterworks.Its
weightedbit-valuesarebackwardsfromourpreviouscounters.Thecircuitflowisfromlefttoright,buttheleastsignificantbit,Q0,isontheright,andthemostsignificantbit,Q1,isontheleft.
CHAPTERSEVENTEENSEQUENCERS
Nowwecanpickupthethreadweleftwhenwedecidedweneededadigital
counter.Weaskedhowwecouldconvertastringofvoltagechangesononewire,aclock,intoseparatevoltagesthatenable—inorder—fetch,thendecode,thenexecute.Oursolutionispicturedbelow:
FIGURE17-1
Let’sskipdirectlytothebottomthreelinesofthetimingdiagraminFigure17-1:
theoneslabelled0,1,and2.Theyaretheoutputsofthelinesoutofthe2-to-4binarydecoderlabelled0,1,and2.Thesethreelinesarethefruitsofourlabor:ourgoal.Makesureyouunderstandwhatthesethreelinesaccomplish.Rememberthat
thehorizontalaxisistime,andtheverticalaxisisvoltage.Aswemoveforwardintime(left-to-right),weencounterthe0linegoingfrom0voltsto5volts.Thislineissenttothefetchcircuitrytoenableitsaction.Aswemovefurtheraheadintime,the0linegoesto0volts,disablingthefetchcircuitry.
Next,the1linegoeshigh.Thislineissenttothedecodecircuitrytoenableitsaction.Aswemovefurtheraheadintime,the1linegoeslow,disablingthedecodecircuitry.Finally,the2linegoeshigh.Thislineissenttotheexecutecircuitrytoenable
itsaction.Aswemovefurtheraheadintime,the2linegoeslow,disablingtheexecutecircuitry.Goingfartheraheadintime,weobservethispatternrepeatingitself,overandover.The2-to-4binarydecoderisalreadyfamiliartoyou.Wesawitin10-3,andwe
useditasouraddressdecoder.Inthiscase,wearenotusingtheoutputmarkedas3,soitsoutputislabelledN/A,for“notapplicable.”(Forefficiency,wecouldhavedesigneda2-to-3binarydecoder.)Theinputtothe2-to-4binarydecodercomesfromtheoutputofthemod-3
counter.Youknowthiscounter’scircuitfromFigure16-5.WehaveencapsulatedFigure16-5intoaboxthatonlyrevealstheinputsandoutputs,andlabelledit,“Mod-3Counter,”here.Thelogicsymbolsforthemod-3counterandthe2-to-4binarydecodermeannothingunlessyouunderstandhowthework,internally.But,youdounderstandthem.Themod-3countergetsitsinputfromoursystemclock,whichwecoveredin
Figure14-1.Remember,itisasquaredigitalwave,asseeninthetoplineofthetimingdiagraminFigure17-1,labelledCLK.Feedingtheclockintothemod-3counterproducesitsQ0andQ1outputs.We
knowthatthemod-3countercountsinthepattern,00-01-10-00-01-10,repeatedly.YoucanseethecountingpatterninthesecondandthirdlinesofthetimingdiagraminFigure17-1,labelledQ0andQ1.IhavelabelledtheQ0andQ1timingdiagramlineswith0’sand1’s,sothatyoucanmoreeasilyobservethemcounting.NoticehowthingsinlinesQ0,Q1,0,1,and2ofthetimingdiagramonlychangeduringtherisingedgeoftheCLKline.Wealreadyknowalloftheabovethings,separately.Let’strytounderstandhow
allofthisworkstogether.Wehavethreesubsystems,whenyoucounttheclock.Theclockcreatestimeincrementsforus,inourdigitalworld.Themod-3countercountstherisingedgesoftheclock,turningitintoa2-bitpatternof00,then01,then10(likeadigital0,1,2),thenbackto00,torepeatthecycle.Then,whenthe00isfedintothe2-to-4binarycounter,its0outputgoeshigh.
Whenthe01isfedintothe2-to-4binarycounter,its1outputgoeshigh.Whenthe10isfedintothe2-to-4binarycounter,its2outputgoeshigh.Youcanseethisclearly,intheabovetimingdiagram.The2-to-4binarycountertakesthe2-bitcountsthatchangewithtime,and
convertsthemintosinglepulsesthatchangewithtime.Onlyonepulseishigh,ortrue,atatime.Thepulsesaresequential,intime.Eachoneturnsononeactionatatime:fetch,thendecode,thenexecute.Ifwelike,wecanencapsulatethesequencerinFigure17-1.Wewouldhidethe
mod-3counterand2-to-4binarydecoderinsideabox,labelit,“3-bitsequencer,”andshowonlytheinputsandoutputs.Apictureofthisisshownbelow:
FIGURE17-2
Let’sagaintakeamomenttoappreciatehowdigitalelectronicsbuilds
complexityoutofsimplicity.Atthehighestlevel,westartwithonebox—onelogicdiagram—withmanyinputsandoutputs.Thisboxistheextremelycomplexmicroprocessor.Openthatbox,andyouseeanumberofsubsystem,oneofwhichisthis3-bitsequencer,whichgeneratesthefetch-decode-executesequence.Openthe3-bitsequencerbox,andyoufindamod-3counterboxanda2-to-4binaryencoderbox,connectedasinFigure17-1.
Let’sfollowthemod-3counterpathfirst.Openthemod-3counterbox,andyoufindtwoDflip-flopsandanANDgate,connectedasinFigure16-5.OpenaDflip-flopbox,andyoufindsixNANDgates,connectedasinFigure15-2.OpenupanANDbox,andyoufindthreeofoursimple,fundamentalbuildingblocks,thetransistor/resistorcircuit,connectedasinFigure6-23.OpenupaNANDbox,andyoufindfiveofoursimple,fundamentalbuildingblocks,thetransistor/resistorcircuit,connectedasinFigure6-27.Toseethetransistor/resistorcircuit,lookatFigure6-7.Let’sfollowthe2-to-4binaryencoderpathnext.Openthe2-to-fourbinary
decoderbox,andyoufindtwoinvertersandfourANDgates,connectedasinFigure10-1.OpenupanANDbox,andyoufindthreeofoursimple,fundamentalbuildingblocks,thetransistor/resistorcircuit,connectedasinFigure6-23.Openuptheinvertertriangle,andyoufindourtransistor/resistorcircuit.Toseethetransistor/resistorcircuit,lookatFigure6-7.Beforewemoveon,takeonemorelookatFigures17-1and17-2.Inthese
circuits,wehaveclaimedthat,simplybybeinginthehighstate,anyoneoftheoutputsofthesequencerallowsaneventtohappen.Thatis,ahighoutputturnsonsomeothercircuitrytoallowafetch,oradecode,oranexecute.Let’smakesureyouunderstandandappreciatethis.Actually,youalreadyunderstandthis.Wehavebeen“enabling”circuitryall
along.Wehavebeendesigningcircuitsthatdonothingunlessanenablelineispulledhigh.Forexample,ourDlatchinFigure7-10hadanenableinput.Ourtri-statebuffer
(Figure7-20)andtri-stateinverter(Figure7-19)alsohadenablelines.Sodidourbi-directionallatchinFigure7-22.Onelookatoursimplemicroprocessor-basedsystemwithitsaddressdecoder(Figure10-4)shouldprovetoyouthatonevoltagepulledhighcanselectoneofseveralsubsystems.Or,gobacktothepass/blockcircuitofFigure7-11.ItshowsasimpleAND
gate,actingasanon/offswitchforaclock.TheclockcomesoutoftheANDiftheenableinputoftheANDishigh;theclockdoesnotcomeoutiftheenableinputislow.Realizethat,ifwewantedtoenable/disableanyofourcountersinfigures16-1,16-2,16-4,16-5,17-1,or17-2,allwewouldneedtodoismaketheinputclockfirstpassthroughanANDgate,controlledbyanenablevoltageononeinput,asinFigure7-11.Alltheabovedesigntechniquesallowustoturnonoroffentiresubsystems
withonewire—usuallycalled“enable”—settohighforenableorlowfordisable.It’slikealightswitch,turningcircuitsofforon.Rememberthisaswemoveintothenextsection,inwhichmultiplesubsystemswillbeonoroff.
CHAPTEREIGHTEENINSTRUCTIONDECODING
Now,let’sreturntoourbasicmicroprocessorsystemofFigure8-1.Weshall
nextconsiderhowourmicroprocessordecodesandexecutesacommand.Wesaythatdigitalelectronicssystemsarewonderful.But,weclaimthatthedigitalelectronicssystemcalledamicroprocessorisevenmoreamazing,becauseitis“programmable.”And,itis“re-programmable.”Inotherwords,asimpledigitalsystemperformsonefunction,andactsasone
machine.Amicroprocessorcanrunoneprogramwhichmakesitperformonefunction,asonemachine.Then,itcanrunanotherprogramcausingittoperformadifferentfunction,asifitwereadifferentmachine.Theoretically,itcanrunaninfinitenumberofprograms,soitcanbeaninfinitenumberofmachines.Haveyouusedacellphone,recently?Itdoesallthisbecauseitcandecodeandexecutecommands.Eachcommand,
inasense,makesthemicroprocessoraslightlydifferentmachine.Iwillshowyouhowitdoesthis,shortly.Let’sstartwithananalogy.Thinkofaverybigcorporation,likeGM.Theymake
transportationvehicles:cars,trucks,SUV’s,minivans,etc.Theystockalotofsubsystems:transmissions,drivetrains,suspensionsystems,exhaustsystems,engines,wheels,gears,lights,etc.Noteveryoneoftheirvehiclesis100%unique.BythisImeanthat,
hypothetically,thesameignitionswitchcouldbeintheAvalanche,theSilverado,theEscalade,andtheSierra,butnotinotherGMvehicles.So,GMcancreateacarcalledtheGoofmobilebyusingsubsystem348forthe
transmission,subsystem59forthedrivetrain,subsystem678forthesuspension,subsystem12fortheexhaust,etc.TheycanthencreateadifferentcarcalledtheDaffyTruckbyusingsubsystem322forthetransmission,subsystem72forthedrivetrain,subsystem611forthesuspension,subsystem18fortheexhaust,etc.Thetwovehiclesmighthavesomesubsystemsincommon,likethelights,seatbelts,airbags,etc.Thepointofthisanalogyis,oncethevehicleisdesigned,itisdone.Itisone
vehicle,onedesign.Everyvehicleofthesamemakeandmodelisthesame.Ifyouwantadifferentkindofvehiclewithadifferentdesign,madefromdifferentsubsystems,youhavetobuyadifferentvehiclebasedonadifferentdesign,madefromdifferentsubsystems.Thisiswherethemicroprocessorisdifferent.Whenthemicroprocessor
decodesacommand,itactuallyinterconnectsdifferentsubsystemstogether,onthefly!Thesesubsystemsthenworktogethertoexecutethecommand’stask.Thisistrulyamazing.It’sasifGMcouldredesignandrecreateanewvehicle
foryoueverynanosecond,madefromdifferentcombinationsofsubsystems,whileyouaredrivingit!Howdoesthemicroprocessordothis?Lookatthepicturebelow:
FIGURE18-1
ThetopofFigure18-1showsthemicroprocessor’s10-1instructionregister,with
aninstructioninside.Theinstructionisthereduetothefetchprocess,wherebythecommandwascopiedtotheinstructionregisterfromcommandmemory.Thenextstepisthedecodeprocess.Thecommandintheinstructionregisteris0000111000110001.Remember,the
0’sarereally0volts,andthe1’sarereally5volts.Theyarestoredina16-bitlatchcalledtheinstructionregister.Individualbitsfromtheinstructionregisterbecomeinputsintodifferent
decoders.(Youarefamiliarwiththe2-to-4decoderfromfigures10-1and10-3.)Each2-to-4decoderhastheabilitytoenableoneoffoursubsystems.Notevery2-to-4decoder’ssubsystemisrequiredforeverycommand.Forexample,fewcommandswillusethe2-to-4decoderthatactivatesADC0,ADC1,ADC2,orADC3.The6-to-64decoderisonlypartiallyshown.Ituses6bitsfromtheinstruction
registertochoose1of64circuitstoexecutespecificcommands.Ihaveonlyshown6ofthe64outputs:theonesthatenabletheMOVE,ROTATE,BRANCH,COMPARE,INCREMENT,andCLEARcircuits.Eachofthesespecificcircuitsexecutesthecommandbyaccessingthedatafromthecircuitsenabledbythe2-to-4decoders.Let’ssaythatthedesignerofthecircuitryforthismicrocontrollercreateditso
thatthebinarycommand0000111000110001executesasfollows:
SUBTRACTthecontentsofADC3fromthecontentsofUSART2,storingtheresultsinACCUMULATOR2.Whatdoesthisevenmean?Well,theprogrammightbemonitoringthe
temperatureofachemicalmixturethatisbeingheated.AnADCisananalog-to-digitalconverter,builtintomanymicrocontrollers.Atransducer—likeathermocouple—canconverttemperatureintoananalog(manylevel)voltage.IfthatanalogvoltageisinputintoanADC,theADCchangesitintoabinarystringofvoltages—abinarynumber—thatthemicroprocessorunderstands.Thehigherthetemperature,thehigherthebinarynumber.Inshort,theADC’svalueisthetemperatureofthechemicalmixture.Thereasontheprogrammightbemonitoringthetemperatureisthatitmight
wanttocompareittoashut-offtemperature.Wherewillitgetthisshut-downvalue?Well,fortotalflexibility,theuserofthismicroprocessorshouldbeabletochoosetheshut-offtemperatureatanytime.Theusercouldenteritintoakeyboardthatattachestooneoftheserialinputports.Thekindofintegratedcircuit(IC)thatconvertsaserial(onebitatatime)binaryinputintoaparallelbinaryoutput(thinkofan8-bitlatch)iscalledaUSART(universalsynchronous/asynchronousreceiver/transmitter).Manymicrocontrollershavebuilt-inUSARTs.Inshort,theUSART’svalueistheshut-offtemperature.Ofcourse,whenthetemperatureofthechemicalmixturereachestheshut-off
temperature,themicroprocessorwillneedtoturnofftheheatsourcetothechemicalreaction.Howdoesthemicroprocessorknowthatthetemperatureofthechemicalmixturehasreachedtheshut-offtemperature?Onewayistosubtractthetemperatureofthechemicalmixturefromtheshut-
offtemperature.Iftheansweriszero,thechemicalmixtureisattheshut-offtemperature,soit’stimetoshutofftheheatsource.Intermsofthedevicesavailabletotheinstructionregisterthroughthe2-to-4decoders,it’stimetoshutofftheheatsourcewhensubtractingthecontentsofADC3fromUSART2equalszero.Let’sgothroughthiscommand,bitbybit:
Bits1and0oftheinstructionregisteraresetto0and1,respectively,therebyenablingthesubtractioncircuitry.Bits3and2oftheinstructionregisteraresetto0and0,respectively,therebyenablingtheaccumulator0circuitry.Bits5and4oftheinstructionregisteraresetto1and1,respectively,therebyenablingtheanalog-to-digitalconverter3circuitry.Bits7and6oftheinstructionregisteraresetto0and0,respectively;however,thisinstructiondoesnotuseanymemorycircuitry.
Bits9and8oftheinstructionregisteraresetto1and0,respectively,therebyenablingtheuniversalsynchronous/asynchronousreceiver/transmitter2circuitry.Bits15,14,13,12,11,and10oftheinstructionregisteraresetto0,0,0,0,1,and1,respectively,therebyenablingthecomparecircuitry.Thisisafineexampleofthemicroprocessorbuildinga“car”(circuit)onthefly.
Becauseofwhichbitsareintheinstructionregister,USART2andADC3areenabled,theircontentssubtractedintheenabledsubtractioncircuitry,andtheanswerstoredintheenabledaccumulator2.Outof84subassemblies(circuits)availabletothemicroprocessor,theinstructionregisterhasassembled5ofthemtomakeasubtractionmachine.Adifferentcommandbuildsadifferent“car”(circuit).Incaseyouarecurious,here’swhatcanhappennext(dependingonthe
microprocessordesign)towrapupthetaskofleavingtheheateronorturningitoff.(It’sanadvancedtopic,butIputithereforasenseofcompleteness,andforthecurious.)Ifyoulookclosely,youwillseethatthiscommanddoesalittlemorethanjustsubtraction.Italsoactivatesthecomparecircuitry.Ifthevalueintheaccumulator2isallzeroes,thecomparecircuitrysetsa1-bitflip-flopcalled“zero”to1.Ifthevalueintheaccumulator2isnotallzeroes,thecomparecircuitrysetsthe“zero”flip-flopto0.Thenextcommandcanbeaconditionalskipcommand.Thiscommandtests
the“zero”flip-flop.Ifthe“zero”flip-flopcontainsa0,theskipcircuitryaddsanextracounttotheprogramcounter.Otherwise,ifthe“zero”flip-flopcontainsa1,theskipcircuitrydoesnotaddanextracounttotheprogramcounter.Thislittletrickmakesthemicroprocessorskipthefetchingofthenextcommand
fromprogrammemoryifthechemicalmixtureisnotuptotheshut-offtemperature.Normally,themicroprocessorfetchesthenextcommandfromprogramcounter+1.(Remember,theprogramcounterautomaticallyincrementsbyoneaftereveryfetch.)Theskipcircuitrymakesthenextcommandfetchcomefromprogramcounter+2,ifthevalueinaccumulator2isnotallzeroes.However,ifthevalueinaccumulator2isallzeroes,thatmeansthechemical
solutionhasreachedtheshut-offtemperature.Theskipcircuitrydoesnotaddanextracountof+1totheprogramcounter.Thenextcommand,fromprogramcounter+1,getsfetched.Thiscommandwouldloadatotallynewvalueintotheprogramcounter,redirectingthemicroprocessortofetchthenextcommandfromanareaofcodethatturnsofftheheater.Whatisinprogramcounter+2?Itprobablycontainscodetoloopbackaround
totestthetemperatureagain,waitingforthetimetoshutofftheheater.Computerprogrammersmayrecognizethatthisasthebasisfortheway
computersactuallyaccomplishtheFORloop.Anaccumulatorregistercanbeloadedwithnumber,decremented(subtractone),andtestedasabovetoseeifithasreachedzero.
Youwillnoticemyfrequentuseoftheword,“might,”asin,“here’swhatthecomparecircuitrymightdo.”That’sbecauseIammakingupmicroprocessorcircuitsandprogramsasIgoalong.Iamtailoringthemtobegooddesignsforteachingyouhowmicroprocessorswork.Therearemanywaystodesignamicroprocessor,buttheyallhaveasimilarbasicdesign.Thus,Ihavetriedtomakeagenericmicroprocessorforyoutolearn.
Remember,ourgoalisforyoutounderstandhowmicroprocessorswork,nottobecomeamicroprocessordesigner.Infact,therearenotthatmanyjobsfordesignersofmicroprocessors.Mostcomputerengineersdesignsystemsbaseduponoff-the-shelfmicroprocessors:microprocessorsalreadydesignedandsoldbythemillionsorbillions.Thecomputerengineerhasageneralknowledgeofhowmicroprocessorswork,thenappliesthatknowledgetolearnthespecificsofhowthatparticularoff-the-shelfmicroprocessorworks,thendesignsaproductbasedonthatdesign.Thatbeingsaid,let’slookatanotherwaythatamicroprocessordesigner
“might”createcircuitrythatdecodesthecontentsoftheinstructionregister.Let’sassume(tofitthedesignononepage)thatthecommandisonly8bitswide,sotheinstructionregisteris8bitswide.LikeinFigure18-1,6higherorderbitsselect1of64circuitsspecifictothecommand.Theremaining2lower-orderbitsassemble,on-the-fly,somecombinationof3reusablesub-circuitsthatanycommandmightuse.Thefigurebelowdepictsthisscenario:
FIGURE18-2Whatmakesthedecoderlabelledwithaquestionmark(Figure18-2)different
fromthedecodersinFigure18-1?Theoutputsofthe“questionmark”decodercanenablemorethanonecircuitatthesameinstantoftime.Each2-of-4decoder—seeninFigure18-1—canenableonlyonecircuitatatime.Thenewcircuitry—seeninsidethequestionmarkencoder—thoughsimple,cangrowratherlarge.That’swhyIlimitedthisonetobeingonlyabletoselectcombinationsof3sub-circuits.Let’sfirstmakeupatruthtable,toseewhatweareaskingthe“?”encoderto
do.
FIGURE18-3
TheIR1andIR0columnsofthetruthtablecontainthefourpossiblepairsof
valuesthatcanbeintherightmost2bitsoftheinstructionregister:00,01,10,and11.Foranygivenrow,a1inaCIRcolumnmeansthatCIRcircuitistobeenabled.So,forexample,lookatrow1.Itsays:ifthelast2bitsofthecommand(IR1
andIR0)are00,thensub-circuitsCIR2andCIR1shouldbeenabled(1),whilesub-circuitCIR0couldbedisabled(0).Anycommandcanbuilddifferentsub-circuitsbyusingdifferentvaluesof1’sand0’sinIR1andIR0.A1enables;a0disablesthesub-circuit.Weneedtodesignthreeseparatecircuits:onefortheCIR2output,oneforthe
CIR1output,andonefortheCIR0output.Theprocedureforeachcircuitissimilar,soIwillonlyexplainhowtodesigntheoneforCIR0.LookatthethingscircledinFigure18-3.First,IhavecircledtheentireCIR0
column,becausewearedesigningtheCIR0enablecircuit.Second,intheCIR0column,Ihavecircledthe1’s,becausea1indicateswhenCIR0shouldbeenabled.Third,intherowswhereIhavecircledthe1’s,IhavecircledtheIR1andIR0inputs,becausethesearetheinputvaluesthatmusttriggertheCIR0circuitrytoturnon.(Theymayalsotriggerothersub-circuitstoturnon,butthatwillbepartofthedesignforCIR2andCIR1.)Next,let’stryputtingintowordswhatourdesignshoulddo.Usingthewords,
“and”or“or”isofteninevitable,andleadsustotheANDorORgatesweuse.InthecircledpartsofFigure18-3,wefindthatCIR0mustbeenabled(high)whenIR1ishighANDIR0islow,ORwhenIR1ishighANDIR0ishigh.Well,thatwaseasy!Thelastsentencedescribesexactlythecircuitweneed.
WeinputIR1andinvertedIR0intoanANDgate;thenputIR1andIR0intoanotherANDgate;thenputtheoutputsofthetwoANDgatesintoanORgateto
produceCIR0.Thisiscalled,“designingbytruthtable.”YoucanseetheCIR0enablecircuitinthetopthirdofthepicturebelow.ThecircuitsforCIR1andCIR2aredesigneddirectlyfromthetruthtable,justlikeCIR0.
FIGURE18-4Designingbytruthtableisquick,andrequireslittlethought.But,itoften
producesacircuitthatisneedlesslycomplex.Thereisawholebranchofstudythatreducestheseresultantcircuitsintomorecompactformsthatrequirelesscircuitry.Thesetechniqueshavefancynames,like,“Karnaughmapping”and“Booleanalgebrasimplification.”Inaway,theyarefun,likesolvingpuzzles.However,forsimplecircuitsliketheoneinFigures18-3and18-4,alittleextrathoughtisoftenallyouneedtosimplifythecircuit.ThecircuitbelowisamuchsimplerreplacementforthecircuitinFigure18-4.
FIGURE18-5
IderivedthissimplercircuitfromcloseexaminationofthetruthtableinFigure18-3.Fromthattruthtable,noticethattoproduceahighoutputoutofCIR0,thelogicstateofIR0doesn’tmatter;allthatisrequiredforCIR0tobehighisforIR1tobehigh.Next,lookingatthetruthtable’sCIR1column,weseethatitisthesameastheNANDgate’struthtable;so,allwereallyneedforCIR1isaNANDgate.Finally,lookingatthetruthtable’sCIR2column,weseethattheonlytimeCIR2islowiswhenIR0ishighandIR1islow;thatleadstotheCIR2circuitwiththeNANDgateandtheinvertedIR1.TheabovecircuitFigure18-5,belongsintheboxwiththequestionmarkinit,inFigure18-2.Whatiftheselectedsub-circuitschosenbyCIR0,CIR1,CIR2,andCIR3
don’tallinteractsimultaneously?Thatis,whatiftheresultsfromCIR3mustfirstbeproduced,beforeCIR1canoperateuponit?WhatifCIR2musthappenbeforeCIR1,whichmusthappenbeforeCIR3?Thisremindsusofoursequencercircuit,fromFigure17-1(takealookatit,
now).But,thedemandsonthatsequencerweremuchlessstringent.Usingdecimal,forsimplicity,itonlyhadtocountinaverypredictableorder—0,1,2,0,
1,2,0,1,2,etc.Weneedasequencerthatcountsindifferentorders.First,itmaybeaskedto
count3,1,2,0.Next,itmaybeaskedtocount2,3,0,1.Butwearebeingevenmoredemandingofournewsequencer.Weareaskingit
docountsofdifferentlengths.First,wemayaskittocount3,2,1,0.That’s4counts.Next,wemightaskittocountonly1,0.That’s2counts.
FIGURE18-6
Figure18-6,above,isonesolution.Inshort,wehavetakenoursequencerfrom
Figure17-1andplacedafixed-programROMmemorychipbetweenthetwoparts.(Themod-3counterisnowamod-4counter.)TheROMactsasatranslationdevice,orasanencoder.Themod-4counter
stillcanonlycountinthe0,1,2,3pattern.It’stheROMthatconvertsthepatterntowhatevercountsequencewewant:3,1,2,0or0,3,2,1,etc.TheROMisinthecenterofFigure18-6.Thefirst4bitsineachrowisthe
addressoftheROMlocation.Thelast2bitsineachrowarethecontentsoftheROMlocation.Thoselast2bitsarewhatpotentiallycomeoutoftheROMandactivatethedecoder,andhencetheCIRsub-circuit.IhavemarkedofftheROMintogroupsof4rows.The2bitsintheinstruction
registermarked“offset”selectwhich4-rowgroupisbeingchosen.TheirA3andA2labels—foraddress3andaddress2—meanthattheyarephysicallyconnectedtoROMpinsrepresentedbythetwoleftmostbinarynumbersineachrow:thetwohighestorderaddressbits.Thetwolowestorderaddressbits—thethirdandfourthnumbersineachrow—
areprovidedbythemod-4counter.Thus,“offset,”intheinstructionregisterselectsa4-rowROMgroup,andthemod-4countermovesthoughthatgroup,onerowatatime.WhatevercontentstheROMdesignerhasplacedinthe2bitsof
eachrowcomesout,translatedfromtheoriginal2bitscominginonA1andA0.Let’sdoanexample.Let’ssaytheinstructioncontainsabinary00inits“offset”
bits.ThatmeansA3andA2oftheROM’saddressbitsareboth0.Lookingthroughthe2leftmostcolumnsofROM,wefindamatchof00inthefirst4rowsofROM.Themod-4countercyclesthroughthosefirst4rowsofROM.Itscount
sequencecanbeseenasthecounts00,01,10,and11inthe3rdand4thcolumnsofROM.Looknowatthe5thand6thcolumnofrows1through4.Thesebitscontainthe
outputsequenceforourcurrentexample.Whenthemod-4countercounts00,theROMoutputs01tothe2-of-4decoder,thereby“translating”thefirstcountfrom00into01.Stillfocusedonthefirst4rows,asthemod-4countercounts00,then01,then
10,then11,theROMoutputs01,then00,then11,then10,respectively.The2-of-4decoder,insteadofsequencingthroughCIR0,thenCIR1,thenCIR2,thenCIR3withouttheROM,nowcountsCIR1,thenCIR0,thenCIR3,thenCIR2withtheROMtranslator.If“offset”intheinstructionregistercontainsadifferentvalue,adifferent
translationoccurs,henceadifferentsequenceorderoutofCIR0throughCIR3.Forexample,if“offset”contains01,thenthesecondgroupof4rowsisselectedfromROM.Noticethat,inthatsecondgroupof4rows,Ihavelistedthetranslatedcount
orderas11,then00,thenxx,andthenxx.Inbinarylistings,xstandsfor,“don’tcare.”InFigure18-6,wedon’tcareaboutthosexxmemorylocations,becausetheyareneverread.Theylivein4-rowROMareasinwhichnotall4CIRsub-circuitsareenabled.Inthesecondgroupof4ROMrows,onlyCIR3(from11)andthenCIR0(from00)areenabled.Themechanismtopreventthesememorylocationsfrombeingselectedbegins
withthe“count”bitsintheinstructionregister.The“count”bitscontainthebinaryrepresentationofhowmanysub-circuitsareselected(forthatinstruction)withinthe“offset”ROMarea.The“count”bitsbecomethe“A”inputstoacircuitnewtous.It’scalledabinary
comparator.Thechangingcountbitsofthemod-4counterbecomethe“B”inputstothebinarycomparator.Thebinarycomparator’senableoutputgoeslowwhenA1,A2equalsB1,B2.Thislowsignalstopsthemod-4counterfromcountingbeyondthelimitimposedby“count”intheinstructionregister.So,forthesecondgroupof4rowsinROM,“count”musthavea01init.This
makesthemod-4counterstopatacountof01.Now,01isthe2ndbinarynumber.And,00isthefirstbinarynumber.So,CIR3isselectedwhenA1-A0is00;CIR0isselectedwhenA1-A0is01;thentheexecutionofthecommandisdone.Thebinarycomparatorstopsthecounterfromgoingtothenextcount:A1-A0equals
10.Circuitryspecifictothecommandwouldberesponsibleforclearing(CLR)the
mod-4countertozeroatthestartofthecommand,andforenablingtheclockinput.Command-specificcircuitrywould,ofcourse,alsoberesponsiblefortyingtogetherthesequentialresultsfromtheCIRsub-circuits.IfitbothersyouthatthisdesignwastessomememorylocationsinROM(thexx
areas),thatproblemcanbefixed.Wewouldmakethe“offset”areaintheinstructionregisterbigger,toincludethetotaladdress(all4bits)ofthebeginningoftheoffsetareaintoROM.Wewouldkeepthe“count”andbinarycomparatorfunctionalityunchanged.However,wewouldchangethewaywecreatetheaddressbitsoftheROM.We
wouldperformabinaryadditionofthe“offset”valuewithmod-4counter’schangingvalues,tostepthoughtheROM,withnowastedaddressspace.Iwillshowyouacircuitdesignforabinaryadder,shortly.ThemicroprocessordesignusingthecircuitinFigure18-6mightbeusedto
accomplishmorewithonecommandthanamicroprocessorusingthesimplerdesignsinFigures18-1or18-2.MicroprocessorarchitecturesdesignedwithmorecomplexcircuitsthataccomplishmorewitheachcommandarecalledCISC(complexinstructionsetcomputer)microprocessors.MicroprocessorarchitecturesdesignedwithsimplercircuitsthatdolesswitheachcommandarecalledRISC(reducedinstructionsetcomputer)microprocessors.BothRISCandCISCstylesaccomplishthesamethings.TheCISCmicroprocessorstakeslongertoperformonetask.TheRISCbreaksthetaskdownintomoresteps,buteachsteptakesashortertime.SomepeoplefeelthattheRISCapproachisthebetterofthetwo.Ifbothtaskstakethesametime,theRISCadvantageislesscircuitry,savingonsiliconspaceandpowerconsumption.What’sthepointofdelvingintoallthesecircuitsinvolvedindecodingand
executingmicroprocessorinstructions?Thepointis,asalways,togiveyouafeelforhowthemicroprocessorworks.Wehavedonethatonmanydifferentlevels:howelectronicsworks;howtransistorswork;howdigitalvoltagesaremovedaround,copied,andstored;etc.Now,wehaveshownhowmicroprocessorsworkonamuchdeeper,broader,
morecomplexlevel.Hopefully,youhavebeenimpressedbythepowerandflexibilityofthemicroprocessor.Youhaveseenthat:1.)Anyone,specificcommandcanbeconfigured(Figure18-1)inmanyways;andeachwayrebuildsandreconnectscircuitstogethertomakeanewelectronicmachine.2.)Therearemanycommands,eachonewithdifferentpowers,capabilities,andpurposes;eachoneusingdifferentinternalcircuits.3.)Puttingcommandstogether,sequentially,makesaprogram;therebyincreasingthepowerofasinglecommand,sincethecurrentcommandcanbuild
upontheresultofpreviouscommands.4.)Themicroprocessorcanrunmanyprograms,eachonedifferent,leadingtoinnumerablecombinationsofinternalcircuitsandcountlesstasksitcanperformforus.
CHAPTERNINETEENTHEBINARYADDER
Imentionedtheneedforabinaryadder,severalparagraphsago.Abinaryadderisacircuitthataddstwobinarynumberstogether,toproducetheirsum.Forexample,1001plus0101equals1110.Iwouldnotgointoanydetailaboutcircuitryforabinaryadderiftheadderwas
simplyusedaspartofacalculatorapplication.Butthefactis,theadderisusedasanintegralpartofthebasicoperationofthemicroprocessor.Forexample,thenormalflowofaprogramissequential.Acommandisfetched
fromacommandmemoryaddress.Let’scallthataddress“A“.ThenextcommandisfetchedfromaddressA+1,becausetheprogramcountergotclockedtothenextcount.Wedon’tneedanaddertoincrementby1.Acounterwilldo.But,sometimeswewanttogetournextaddressfromadifferentareaof
memory.Programmersknowthat“if”statements,“for”loops,andfunctioncallscausetheexecutionofcodetoberedirectedtootherpartsoftheprogram,insteadoftothenextlineofcode.Often,abinaryadderisusedtocalculatetheaddressofthisnew,non-
sequential,sectionofcode.Thecontentsoftheprogramcounterwillbeaddedtoanoffsetnumberbuiltintoacommand.Theresultingsumwillbeputintotheprogramcounter.Thenextcommandwillbefetchedfromthisnew,non-sequentiallocation.Forexample,saytheprogramcounter,pointingtoaddress68,fetchesa
commandcalledBRANCH_IF_ACCUMULATOR_EQUALS_ZERO,20.(Numbersindecimal,forsimplicity.)Whenthefetchisdone,theprogramcounterincrementsby1,becoming69.Here’showthiscommandworks.Ifthevalueintheaccumulatorregisterisnon-zero,thenextfetchcomesfromaddress69.But,ifthevalueintheaccumulatoriszero,20(fromthecommand)isaddedto69(fromtheinstructionregister).Abinaryadderdoesthis.Thesum,89,goesbackintotheprogramcounter,replacingthe69.Hence,thenextcommandisfetchedfromadifferentareaofcode,ataddress89,whenthecontentsoftheaccumulatoriszero.Programmerswillrecognizetheabovedescriptionasthebasisforthe“if”
statement.The“if”statementteststhevalidityofacomparisonbetweentwovalues.Ifthecomparisonistrue,asin“doesxequal0?”,thenthenext-in-linecommandtakesplace.Ifthestatementnottrue,thenacertainnumberoflinesofcodeisskipped,sothatadifferentcommandisexecuted.Thepicturebelowshowsthecircuitryfora1-bitbinaryhalf-adder:
FIGURE19-1
Thecircuitaboveiscalledahalf-adderbecausethereissomethingincomplete
aboutit:itdoesnotaccommodateacarryinputbit.Binary,likedecimal,addsnumberscolumn-by-column,sendingacarrytoaddtothenextmoresignificantcolumnwhenthesumexceedsthebaseofthenumbersystem.(SeeChapterNine.)Thehalf-adderisusedforadditionoftheleastsignificantbitsoftwobinarynumbers.Forexample,whenaddingbinarya3a2a1a0tob3b2b1b0,thehalf-adderhandlestheadditionofb0toa0,andprovidesacarrybittotheb1anda1column.Onceagain,digitalelectronicsamazesuswithhoweasyitistocreatethe
circuitsweneed.Ofcourse,thispresupposesalltheworkittooktolearnbasicelectronics,transistors,andthecircuitsunderlyinggatesandlatches.Oncewegetcomfortablewiththese,puttingtogethercircuitswithgatesandlatchesoftenseemsnaturalandsimple.Theabovehalf-adderisagoodexampleofthissimplicity.Lookatthetruth
tablefortheANDgate,inFigure6-22,part(a);andfortheXORgate,inFigure6-29,part(a),tounderstandhowthehalf-addercircuitinFigure19-1,part(b),producesthebehaviorshowninthehalf-adder’struthtableofpart(a).Inthetruthtable,youneedtoknowthattheSoutputisthesumoutput,andthe
Coutputisthecarryoutput.Reviewingyourbasicbinaryaddition,youshouldalreadyknowthat0+0=0,0+1=1,and1+0=0.Allthreeoftheseadditionsproducea0foracarrybit.However,1+1=0,witha1foracarrybit.Weneedaslightlymorecomplicatedcircuitforthebinaryadditionofanybits
withhigherweightthantheleastsignificantbinarybit.Thesecircuitsdifferinthattheymustaccommodatethecarry-in,providedbythecarry-outfromtheadditioninthepreviouscolumn.LookatFigure19-1,part(b),above,toseethecarry-outbit.Thatcarryoutbitmustbehandledbyacarry-incircuit.Thisslightlymore
complicatedcircuitiscalledafull-adder,andisshowninthepicturebelow:
FIGURE19-2Tounderstandhowthefull-adderimplementsitstruthtable,refertothetruth
tablesfortheORgate(Figure4-16,part(a)),theANDgate(Figure6-22,part(a)),andtheXORgate(Figure6-29,part(a)).Thefull-adder’struthtableandcircuitnowincludeCin(carryinput)tohandlethecarryoutputfromtheprevious,lesssignificantbit.Thefirst7rowsofthefulladder’struthtablearenotreallydifferentfromthehalf
adder.Whenanextrazeroispartofasummation,itdoesn’tchangetheanswer.So,theanswerdoesn’tchangeifyouadd0+1comparedtoadding0+0+1;youstillgetananswerofzero.The8throwisdifferent,though.Theanswerisasumof1andacarryoutof1,
somethingwenevergotwiththehalf-adder.Weareadding1plus1,plusacarryinof1.1plus1givesasumof0(aresetto0)andacarryoutof1.Butwethenhavetoaddthecarryinof1totheoldsumof0,producinganewsumof1.
Onceyouhavememorizedthetruthtablesforthebasicgates,youcandrawtheabovecircuitonpaper.Then,goline-by-linethroughthetruthtable,pencilinginthethreebinaryinputvalues,A,B,andCIN.Useyourknowledgeoftruthtablestopencilinallthebinaryvaluesinthecircuitforeachsetofinputs.Provetoyourselfthatthecircuitproducesthecorrectoutputvalues,SandCOUT,predictedbythetruthtable.IfyouwanttocreateacountertoaddXbitstogether,simplychainX1-bit
adderstogether.Forexample,tomakea4-bitadder,chainfour1-bitadderstogether,asinthefollowingpicture:
FIGURE19-3Theaddersareputtogetherright-to-left,justlikeournumbersystems,withthe
leastsignificantbitontheright,andthemostsignificantbitontheleft.AsImentionedbefore,theleastsignificantbitcanbeahalf-adder.Thecarriesworktheirwayfromrighttoleft;acarryoutcomesoutofanadderandbecomesthecarryinfortheadderonitsleft.Thistypeofadderiscalledaripple-carryadder.Justbeawarethatthereare
addersthatworkfaster,butaremorecomplicated.Onecanalsodesignacircuitthatwilleitheraddorsubtract.
CHAPTERTWENTYTHESTACKANDSTACKPOINTER
Twicewehavemadereferencetotheoccasionalneedtochangethenormal
behaviorofthemicroprocessor,initsfetchingofitsnextcommandsequentially.Remember,themicroprocessor’sprogramcounterautomaticallybumpsupbyonecountafterafetch.Thenumberinitisreadytobeplacedontheaddressbus,tofetchthenextcommandfromthenexthigheraddressinprogrammemory.Wehavenotedthat,afteratestingtypeofcommand,thecontentoftheprogramcountermaybereplacedwithadifferentnumber,causingthenextcommandtobefetchedfromelsewhereinprogrammemory.Wepointedouttoprogrammersthatthiswasthephysicalimplementationoftheir“if”and“for”programmingstructures.Sometimesthough,themicroprocessorneedstheabilitytoreturntotheplace
whereitstoppedexecutingitssequentialcode.Say,forexample(usingdecimalnumbersforclarity),afetchtakesplacefromprogrammemoryaddress25.Theprogramcounterbumpsupautomaticallyto26.Butthecommandfrom25executes,andreplacesthecontentsoftheprogramcounterwith175.So,thenextcommandisfetchedfrom175,thenfrom176,thenfrom177,thenfrom178,thenfrom179,thenfrom180,etc.Sometimes,whenthemicroprocessorisdoneexecutingtheblockof
commandsthatstartedataddress175,itneedstheabilitytoreturnwhereitleftoff,ataddress26.Perhapscontainedinmemorylocation180isacommandthatsays,“RETURN,”whichmeans,“Gobacktowhereyouleftoff.”Itwon’tcontainthereturnaddresslocationof26.Itwilljustsay“RETURN.”Thepicturebelowillustratesthisprocedure:
FIGURE20-1
Intheabovefigure,followthearrowstoseetheprogramredirectionandflow.
Startatmemorylocation25,totheleftoftheprogrammemorybox.(Remember,thereisonlyoneprogramcounter;don’tletthefigurefoolyouintothinkingtherearefourofthem.)TheCALL125commandreplacesthe26intheprogramcounterwith175.Followingthearrowontheright,programfetchesareredirectedtothe175-180areasofprogrammemory.Next,lookatmemorylocation180.TheRETURNcommandcausesthe
programcountertobereplacedwith26.Followingthearrowontheleft,programfetchesareredirectedbacktoaddress26,inthemainprogramthread.Whywouldthatcommandfromaddress25makethemicroprocessorstart
fetchingcodefromaddress175,insteadoffromsequential26?Theblockofcodefrom175to180mightbecodethattheprogrammerusesoverandover,manytimes,throughouttheprogram.(NoticeinFigure20-1thatCALL175isusedasecondtime,ataddress28.)Wouldn’titbegreatiftheprogrammercouldmakeonecopyofthecodeanduseit50times,insteadofhaving50copiesofthesamecode,scatteredthroughouttheprogram?Thenameforthat“onecopy”ofrepeatedlyusedcodethatlivesatouraddress
175through180isa“function.”Thenameforthecommandataddress25,thatredirectsprogramexecutiontothefunction,isa“functioncall.”Thenameforthecommandataddress180,thatredirectstheprogramexecutionbacktothemainprogramthread,isa“functionreturn.”Let’scalculatetheefficiencyofthistechniqueinmakingtheprogrammore
compact.First,let’slookatthenumberoflinesofcodeneededifwedon’tusefunctions.Therepeatedcode,asfoundinthefunctionis5lines,from175through179.Ifwerewrotethatcode50times,itwouldcostus5x50=250linesofcode.Now,let’slookatthenumberoflinesofcodeneededifwedousefunctions.
Thefunctionrequires6linesofcode,sinceitincludesanextraline:the“RETURN”command.Eachofthe50timeswecallthiscommand,wecallitwith1lineofcode,thefunctioncall.Now,itwouldcostus50+6=56linesofcode.Obviously,56linesofcodeusingfunctionsismuchbetterthan250linesof
codewithoutfunctions.Now,thesameblockofcodemaynotnecessarilybeusedasmanyas50times.But,afunctionisusuallymuchbiggerthan5linesofcode.Itcaneasilybehundreds,ifnotthousandsoflinesofcode.Theefficiencyofusingfunctionsbecomesenormous.Youmayalsowonderhowoftenaprogramwouldneedtoruntheexactsame
code.Ifevertheprogrammerneedstodoevenonethingdifferentfromthefunction,heorshecouldnorre-usethefunction.
And,youwouldberight.Except,thefunctionhasbuilt-incapabilitiestoovercomethisshortcoming.Thecircuitryaccommodatessendingdifferentbinaryvaluestothefunctioneachtimethefunctioniscalled.Thecircuitryalsoaccommodatessendingbinaryvaluesfromthefunction,backtothemainprogramthread,whenthe“RETURN”commandiscalled.Thisaddedflexibilityallowsthefunctiontorundifferentlyeachtimeitiscalled.
Itcan,forexample,doadifferentcalculationeachtimeitiscalled,bysendingitadifferentsetofnumberstocalculate.Eachtime,thefunctionwouldsendadifferentanswerbacktothemainprogramthread.There’sstillamysterytobesolvedbytheabovedescriptionofthefunctioncall
andreturnprocess.WhentheRETURNcommandexecutes,wheredidthe26comefrom,tobeplacedintheprogramcounter?Weknowwherethe175camefrom,thatwasputintotheprogramcountertostartthefunction;itwasbuiltintothecommand,CALL175.ButtheRETURNcommanddoesn’tsay,RETURN26,itjustsaysRETURN.Itcan’tsayRETURN26,becauseitdoesn’talwaysreturnto26.WhenweCALL175ataddress28,ithastoRETURNto29,notto26.Theanswertothismysteryinvolvestwonew,relatedtopics:the“stack”andthe
“stackpointer.”ThestackisaspecialareaofRAMmemory,usedtotemporarilystoretheaddresswhereyourprogramleftoffwhenitgotredirectedtorunthefunction.Inourexample,thestackstoresthe26.WhenthefunctionisdoneandRETURNiscalled,the“remembered”addressinthestack,26,isputbackintheprogramcounter,soyourprogramcanpickupwhereitleftoffinthemainprogramthread.Thisisanintuitiveprocess.It’slikewhatyouwoulddoifyouhadajobinwhich
youwereconstantlybeinginterrupted.Youwouldwriteyourselflittlenotestohelpyourememberwhereyouleftoff,beforetheinterruption.Ifyouwereabouttodostep26inyourmaintask,youwouldwritethatdownonanote,thendosubtaskA.WhensubtaskAwasdone,youwouldrefertoyournote,torememberthatyouneedtogobacktothemaintask,step26,topickupwhereyouleftoff.But,whatif,whileyouwereinthemiddleofsubtaskA,yougotinterrupted
again?Youwouldwriteanothernote,sayingwhatyouwereabouttodonextinsubtaskA.Youwouldputthenewnoteontopofthefirstnote.(Thisisa“stack”ofnotes,getit?)Then,youwouldproceedtothenewsubtaskB.WhensubtaskBiscomplete,youwouldrefertothetopnoteonthestack,
whichwouldtellyouwheretopickupwhereyouleftoffinsubtaskA.Youwouldthrowawaythatnote(don’tputitbackonthestack),andfinishsubtaskA.UponsubtasksA’scompletion,youwouldrefertothenoteonthetopofthe
stack.Thatnotewouldtellyouwheretopickupwhereyouleftoffinthemaintask.ThestackmemoryareainRAMislikeaplacetopilenotesofwheretoreturn,
tofinishinterruptedtasks.However,sinceaninterruptingtaskcanitselfbeinterrupted,weneedamechanismtokeeptrackofwhereweareonthestack.
Thatmechanismisaregistercalledthestackpointer.Iwillgiveanexampleofastackthatgrowstowardloweraddresses,althoughstacksthatgrowtowardhigheraddressesalsoexist.Seethepicturebelow:
FIGURE20-2
IhavedividedFigure20-2intothreesections,part(a),part(b),andpart(c).
Let’sfirstgetcomfortablelookingatthefigure.Thestackpointerisaregister—asetofflip-flops—arrangedasacounter.ItscontentsareusedtoselecttheaddressofthestackareaofRAMmemory.Inthis,itismuchliketheprogramcounter,withwhichyouarealreadyfamiliar.Alsoliketheprogramcounter,thestackpointerlivesintheCPU(centralprocessingunit)areaofthemicroprocessor.Thestackpointerdiffersinthatitcancountupordown.IhavedrawnthestackmemoryontherightsideofeachsectionofFigure20-2.
ThestackmemoryisadedicatedpartofRAM,reservedforkeepingtrackofreturnaddresses.“XX”insideanystacklocationmeanswe“don’tcare”what’sinside.IneachsectionofFigure20-2,Ihavedrawnanarrowfromthestackpointertotheaddressinthestackit“pointsto”.(“Pointsto”impliesanaddressdecoder,notshown.)Finally,“ProgCounter”ineachsectionreferstotheprogramcounter.The
programcounterisoneregister,nottwo.Ishowtwoboxessoyoucanseethecontentsoftheprogramcounterduring(old)andafter(new)thecommand.Let’sstartwithpart(a).Thestackisempty.Weareinthemainprogram.We
haven’treachedtheCALL175command,yet.Thestackpointerpointstostacklocation10001.Thestackisfullof“don’tcare”values.Movingtopart(b),theCALL175commandisfetchedfromprogrammemory
25.Whenthefetchisdone,theprogramcounterbumpsupto26.CALL175executes,andourmysteryissolved.Here’swherethereturnaddress,26,issafelyhidden.Followthecircled26’sandthearrowsconnectingthem.DuringCALL175’sexecution,threestepshappen,inthisorder:1.)Thestackpointercountsdownby1(decrements),to1000.2.)Thecurrentcontentsoftheprogramcounter(26)iswrittentothestackaddresspointedtobythestackpointer(1000).(Again,followthecircled26’sandthearrowsconnectingthem.)3.)Thecontentsoftheprogramcounterarereplacedwiththeaddress(175)ofthefunctionreferredtoinCALL175.26istheaddressthemicroprocessormustreturntowhenthefunctionhas
finishedexecution.Wehaveseenthatitisnowsafelytuckedawayinthestack.Now,let’sseehowthereturnprocessworks,inpart(c).Themicroprocessor
fetchestheRETURNcommandfromthefunction’saddress,180.Whenthefetchisdone,theprogramcounterbumpsupto181.DuringRETURN’sexecution,twostepshappen,inthisorder:
1.)Thecontents(26)ofthestacklocationpointedtobythestackpointer(1000)arewrittenbackintotheprogramcounter(Again,followthecircled26’sandthearrowsconnectingthem.)2.)Thestackpointercountsupby1(increments),to1001.Thestackisonceagainempty.RealizethatifanotherCALLhadhappened
beforetheRETURN,thestackwouldhavegrowndownintoaddress999.Here’sanexample.Figures20-1and20-2willhelpyouvisualizethis.Let’snamethefunctionataddress175the“A”function.Ataddress177ofthe“A”function,acalltoa“B”functionoccurs.Address178issavedatstackaddress999.Whenthe“B”functionfinisheswithaRETURNcommand,the178addressis“popped”offthestack,andputintheprogramcounter.Then,whenthe“A”functionfinisheswithitsRETURNcommand,the26addressispoppedoffthestack,andputintheprogramcounter.Wearebackinthemainprogram,whereweleftoffbeforethe“nested”functions:thefunctionwithinafunction.Doyouseehowmuchofthemicroprocessor’sbehaviorisbasedonmoving
informationaround?RememberbackinthebeginningofthisbookhowIstressedhowamazingandimportantitisthatagroupofbinaryvoltagescanbemovedfromonelocationtoanother?Withthisinmind,let’stakeamomenttoappreciatetheballet-likebeautyofthe
aboveprocess.Thinkoftheprogramcounterchanging,commandsmoving,thestackpointerchanging,addressesmovinginandoutofthestack.Allofthisaccomplishedwithprecisionandakindofbeauty,andatthemicroscopicscale.It’slikethebeautyoftheinternalcombustionengine.
CHAPTERTWENTY-ONEINTERRUPTS
There’sanother,similarsituationinwhichtheabovestackandstackpointermechanismisused.Above,wecoveredtheneedtorememberandreturntoanaddresswhenafunctioniscalled.Sometimes,themicroprocessormustrememberandreturntoanaddresswhena“hardwareinterrupt”occurs.Here’sthebasicconceptbehindahardwareinterrupt.Themicroprocessoris
surroundedbysubsystemsthatmayneedthemicroprocessor’sattention.Apersonmaybepressingakeyonakeyboard.TheUSBportmayhavejustreceivednewpositioninformationfromthemouse.TheEthernetportmayhavejustreceivedthewebpageyourequested.Theprintermaybereadyforanotherpageofthedocumentyouwanttoprint.Theharddrivebuffermaybereadywiththetextdocumentyouwanttoedit.Therearesomanythingsthatneedthemicroprocessor’sattention.Now,themicroprocessorcouldsitinamainprogramloop,andconstantly
checkonesubsystematatime,toseeifanyofthemneedsattention.Thistechniqueiscalledpolling.Itisasoftwaresolution.But,thissolutionwastestime.Sinceit’sasoftwaresolution,allofthispollingwastestimeinfetching,decoding,andexecuting.It’sawastewhenasubsystemisinnoneedoftheattention.Plus,thesubsystemthatdoesneedattentionhastowaitwhilethemicroprocessorcheckssubsystemsthatdon’tneedattention.Hardwareinterruptsareabetter,moreefficient,solution.Thinkofateacherina
classroom.Theteachergivesanassignmentthatmayrequireindividualhelp.Theteachercouldusethepollingsystem,andwalkaroundtoeachstudent,oneatatime,andsay,“doyouneedhelp?”A“yes”answerwouldgettheteacher’shelp.A“no”answerwouldbeawasteoftheteacher’stime.Thestudentthattrulyneedshelpwillhavetowaituntiltheteachercheckswitheveryotherstudent,whomayneednohelp.Obviously,thebettersolutionisahardwareinterrupt.Theteachertellsthe
students,“whoeverneedsmyhelpshouldraisehisorherhand.”Thehandisthehardware.Itisbinary:araisedhandistrue,anot-raisedhandisfalse.Theteacherdoesnotwastetimethisway.Thefirststudenttoraiseahandgetsimmediatehelp.Inamicroprocessor,hardwareinterruptsarehandledbyspecializedcircuitryin
theCPU.Thebasicideais,thatwhenasubsystemneedsthemicroprocessor’sattention,itpullsitsinterruptline(hardware)high.Themicroprocessor:1.)finishesitscurrentcommand2.)savestheaddressitmustcomebacktoonthestack3.)placestheaddressofthesubsystem-servicingcodeintheprogramcounter
4.)runsthesubsystem-servicingcodeuntilitencountersaRETURNcommand5.)restoresthereturnaddressfromthestacktotheprogramcounter,resumingthecode“interrupted”bythehardwareinterruptAhardwareinterruptisevenmoreamazingthanafunctioncall.Afunctioncall
hasalittlebitofpredictability.Thoughthemicroprocessorcan’tanticipatewhenafunctioncallwilloccur,theprogrammercan.Theprogrammerputsthecode(software)exactlywhereheorshewantsit.Neitherthemicroprocessornortheprogrammerknowwhenthehardware
interruptwilloccur.Thishasmajorimplications.Itmeansthatneitherthemicroprocessornortheprogrammerknowswhatlineofcodeisbeingexecutedwhentheinterruptoccurs.LookatthefunctioncallsinFigure20-1.Weknowtheyhappenwhenthecode
atline25andline28arefetched.Weknowthemicroprocessormustreturntolines26and29,respectively,whenthefunctionsarefinishedrunning.Perhapswecouldhavedesignedasimplermechanismthanthestack/stack
pointer,ifwehadthisamountofpredictability.Buthardwareinterruptsoccurunpredictably.Wecan’tplanforthem,incode.Wedon’tknow,inadvance,whatlineofcodewillbeexecutingwhenahardwareinterruptoccurs.Wereallyneedthestack/stackpointermechanismtohandlethem.Ifyoure-readtheabove5stepsdescribinghowthemicroprocessorhandlesan
interrupt,yourealizethatit’ssimilartohowithandlesafunctioncallandreturn.Thebigdifferencecomesinstepthree:“Themicroprocessorplacestheaddressofthesubsystem-servicingcodeintheprogramcounter.”Withafunctioncall,theaddressofthefunction-handlingcodeisbuiltrightinto
theCALLcommand.IfthecommandisCALL175,175goesintotheprogramcounter,tobeexecutednext.Thingsarenotsoeasywithinterrupts.Wehavetoputintotheprogramcounter
theaddressofthecodethathandlestheinterruptfortheparticularsubsystem.But,therearemanysubsystems,eachwithitsowninterrupt-handlingcode,eachstoredatadifferentstartingaddress.Anewmechanismisrequired,onethatallowsthecorrectaddresstobeputintheprogramcounter,toaccesstheinterrupt-handlingcodeneededbytheinterruptingsubsystem.Forexample,let’sassumethereare10subsystems,labelledAthroughJ,each
withtheabilitytointerruptthemicroprocessor.Eachofthe10subsystemsgetsservicedbyitsownuniquecode,differentfromtheother9,andstoredatadifferentstartingaddressfromtheother9.Assumethesecodeareasarealsolabelled0through9.Weneedamechanismsothat,forexample,whensubsystem2interruptsthemicroprocessor,onlythecodeincodearea2runs.Onlythestartingaddressforcodearea2getsputintheprogramcounter.Thepicturebelowdescribesthisscenario:
FIGURE21-1
Inthisfigure,youseethatonlytheinterruptforsubsystem2istrue(logical1,or
5voltsinputontheleftsideofFigure21-1).Thecodeareatoservicetheinterrupt2subsystembeginsataddress3000,andisbeingactivated,becausetheprogramcounterhasbeenloadedwithaddress3000.Differentmicroprocessorsusedifferentdesignstoputthecorrectaddressfor
theinterruptintheprogramcounter.InFigure21-1,Ihaveshownonesuchtechnique.Anareaofmemoryisreservedforuseasaninterruptvectortable.Theaddressforinterrupt0’scodeareaisstoredatthefirstaddressinthetable;theaddressforinterrupt1’scodeareaisstoredatthesecondaddressinthetable;etc.(Whenyoufirstseesomethinglikethis,itcanbedisturbing,becausetheseareaddressesbeingstoredasdatainmemory.)YoucanfindthistableintheupperrightsideofFigure21-1.Inourexample,
interrupt2occurs.Aftersavingthereturnaddressonthestack,built-incircuitryautomaticallyreadsthecontentsofaddress0002intheinterruptvectortable.
Address2,remember,holdstheaddressoftheinterrupt2codearea.Thebuilt-incircuitrythenwritesthe3000valueitfoundtheretotheprogramcounter.Codeproceedstorunfromaddress3000.Whenthecodetoserviceinterrupt2isdone,itendswithaRETURN
command,similartothewayafunctionends.Idon’tneedtogooverhowthereturnaddressisstoredtoandrestoredfromthestack.It’sthesameasforafunction.AsIhavementioned,thereareotherdesignsforhandlingthegenerationofthe
interruptaddress.Inonetechnique,thereisnointerruptvectortable.Or,perhapsit’sbettertosaytheinterruptvectortableconsistsofoneaddress.Nomatterwhichinterrupthappens,thatoneaddressgetsputintotheprogramcounter.Thatmeansthatonlyonesectionofcodestartsrunning,nomatterwhichinterruptoccurred.However,oncethatcodestartsrunning,thatcodespendssometimefiguring
outwhichinterruptoccurred.Itchecksthevoltagelevelsoftheinterruptinputlines,lookingfora1(true).Afteritfiguresthatout,itreplacesthecontentsoftheprogramcounterwiththeappropriateaddresstoservicethecorrectinterrupt.Asyoucansee,thesecondsolutiontogeneratingtheinterrupt-servicing
addressissoftware-driven.Athirdsolutionishardware-oriented.Inthistechnique,specialhardwarebuiltintoeachsubsystemsendstheinterrupt-servicingaddresstotheCPU.Thiseventoccursafterthemicroprocessoracknowledgestheinterruptsignalfromthatsubsystem.And,interruptscanbeevenmorecomplicatedandinteresting.Some
microprocessorsprioritizetheirinterrupts.ThinkofaCEO,theheadofabigbusiness.TheCEOisliketheCPU.TheCEOdoesn’tmindbeinginterrupted,butsomeinterruptionsarelessimportantthanothers.InterruptionsfromtheCFO(chieffinancialofficer)mighthavetoppriority,becauseignoringtheCFOcouldleadtofinancialdisaster.InterruptionsfromtheCIO(chiefinformationofficer)mighthavesecondhighestpriority,becauseignoringtheCIOcouldleadtodisastersfromsecuritybreaches,communicationloss,ordataloss.InterruptionsfromtheMarketingDirector,ontheotherhand,mightbelesstime-critical,andhencehavealowerpriority.TheCEOmightgivehis/hersecretaryinstructionsaboutthepriorityof
interruptions:apriorityorder:A.)“IfIamtalkingtotheCFO(interruptlevel0),don’tletanyoneinterruptus.”B.)“IfIamtalkingtotheCIO(interruptlevel1),don’tlettheMarketingDirector(interruptlevel2)interruptus,butdolettheCFOinterruptus.”C.)“IfIamtalkingtotheMarketingDirector(interruptlevel2),lettheCFOortheCIOinterruptus,butdon’tletanyoneelseinterruptus.”Prioritizinginterruptsworkssimilartonestedfunctioncalls,whichwehave
alreadycovered.That’swhere,duringtheexecutingofcodeforfunctionA,acall
foranotherfunction(functionB)occurs.Todemonstrateaprioritizedinterruptsystem,assumethatinterrupt-servicing
codeforsubsystemAisrunning.AssumeaninterruptrequestoccursfromsubsystemB.Oneoftwopossiblethingshappennext:1.)SubsystemB’sinterruptpriorityisequaltoorlessthansubsystemA’s.Inthiscase,themicroprocessorwillfinishallthecodeforsubsystemAbeforerunningthecodeforsubsystemB.2.)SubsystemB’sinterruptpriorityisgreaterthansubsystemA’s.Inthiscase,themicroprocessorwillfinishonlythecurrentcommandforsubsystemA,savethereturnaddressonthestack,thenimmediatelygotoworkontheinterrupt-servicingcodeforhigher-prioritysubsystemB.Whendonewiththat,themicroprocessorwillreturntocompletingtherestofthecodeforlower-prioritysubsystemA.LookingbackatFigure21-1,the10interruptscouldbeprioritizedsothat
interrupt0isofthehighestpriority,andinterrupt9isofthelowestpriority.(Strangely,it’susuallybackwards,likethis.)Ofcourse,withprioritizedinterruptcapability,morethanoneinterruptinputcanbeatalogic1level(true),andthemicroprocessorwouldhavenoproblemhandlingit.Digitalcircuitrywouldenableittofollowtherulesoutlinedinsteps1and2,above.You’vecomealongway,inyourquesttolearnhowmicroprocessorswork.We
havemovedfromtinyelectronstolesstinytransistors;onetransistortocombinationsoftransistors;fromsimplecircuitstocomplex.Ihopethatyouhaveenjoyedandprofitedfromthisjourney.And,Ihopeyoucannowlookuponyourmicroprocessor-controlleddeviceswithevengreaterappreciation,nowthatyouunderstandhowtheywork.
APPENDIXACODE
MachineLanguage(AppendixA-1)Isuspectthatyoumaywonderhowwemakethiswonderfuldevicedothings
forus.Youhaveseenthepiecesofthepuzzlethatfittogethertomakeamicroprocessor.Youhaveseenhowtheyworktogether.But,youmaywonder,howdoesthecodegetinsidethesethings,tomakethemwork?Howdoesapersongofrombuyingamicroprocessor,tocreatingaproductwithitthat,say,vacuumsmyfloorswhenI’matwork?Theprocessstartswiththepersonorpersonswhodesignandcreatea
microprocessor.Theircriteriaisbasedonthetargetmarketforthemicroprocessor.Doesithavetobesmallandinexpensive,forsimpletasks?Ormustitbepowerful,torunacomputerserver?Whoeverdesignsthehardwareofthemicroprocessormustalsodesignits
commandcode.Let’sassumeasimplemicroprocessor,basedon8-bitcode.Thedesignerisimmediatelylimitedto28=256binarycommands.Thefirstcommandis00000000,thesecondis00000001,followedby00000010,etc.,withthelastcommandof11111111.Thedesignersmustdecidewhateachcommanddoes.Thatis,theymust
decidehoweachcommandexecutes.Forexample,thecommand00000000mightexecutebyresettingthecontentsoftheaccumulatortoallzeroes.Thecommand00000001mightmovethecontentsoftheaccumulatortothestack(agoodwaytosendanumbertoafunction).Ifyouthinkthisthrough,youwillrealizethatanotherteamdesigningforanother
companymightcreateamicroprocessorthatexecutesthecommand00000000inacompletelydifferentway,suchasdisablingallinterrupts.Theircommandtoresetthecontentsoftheaccumulatormaybe11111111.Thishasimportantramifications,whichwewilladdresslater.Partofthedesignprocessistocreateamemorymaptodeterminethe
addressesofthesubsystems.Thecircuitry—liketheaddressdecodersthatwehavecovered—mustimplementthememorymapsothatthecorrectsubsystemsareaccessedbythecommands.Importantly,whenthefetchprocessoccurs,commandshadbetterbecomingoutofcommandmemory.Assumenextthatthecircuitryisdesignedandbuilttocarryoutthedecodingof
the256chosencommands.Thenextstepistowriteaprogram,thenputitintocommandmemory.ThefirsthomecomputerwastheAltair8800.ItusedtheIntel8080asits
microprocessor.ItusedRAMtostoreprograms.RAMisvolatile.“Volatile”meanstheprogramgoesawaywhenthedeviceisturnedoff.Lookatthesimplified(reducedto8-bit)pictureofanAltair8800,below:
FIGUREA-1
ThefirstAltairsrequiredtheusertoputthecommandcodeintoRAMprogram
memoryusingswitches.SwitchesontheoutsideoftheboxconnectedtoaddressanddatapinsontheRAMinsidethebox.Youflippedalltheaddressswitchesto0volts,toselectaddress00000000;thensetthedataswitchesinthepatternofyourfirstcommand;thenflippedtheRun/Programswitchto0voltsforamoment,tostorethecommandatthataddress.Next,youraisedtheA0switchto5volts,toselectaddress00000001;thensetthedataswitchesinthepatternofyoursecondcommand;thenflippedtheRun/Programswitchto0voltsforamoment,tostorethecommandatthataddress.Yourepeatedthisprocessuntilyourwholeprogramwasloaded.Youfinallycouldflipanotherswitchtopullyourmicroprocessoroutofreset,soyourprogramcouldrun.ImentionthisprocessbecauseIthinktracingthishistoricalprocesshelpsyour
understandingofhowyougetbinarycodeintocommandmemory.Nomatterhowthetaskisaccomplished,thebasicideaisassimpleastheoneshownabove.Youalreadyknowhowswitcheswork.Flipaswitchup,inFigureA-1,and5voltsappearsonaRAMinputline.Flipaswitchdown,and0voltsappears.Plus,youalreadyknowthatwecanreplacetheswitchesinFigureA-1with
transistors.Youalsoknowthatthesetransistorscanbebuiltintocircuitsthatcanautomatethetaskofloadingaprogramintomemory.And,ofcourse,thatishistoricallywhathappened.TheAltair8800switch-
loadingprocesswasobviouslyintolerablyslow.Thenextstepintheevolutionofgettingcommandcodeintomemorywastheinventionofthenon-volatileROMmemory.Thisintegratedcircuitwasmemorythatwasprogrammedoncewithcommandcode,theninsertedinthecircuitwherethemicroprocessorcouldreadit.Sinceitwasnon-volatile,thecodestayedtherewhenpowerwasturnedoff.Untilrelativelyrecently,ifyouneededtoupgradetheROMBIOS(thestart-up
commandcode)ofthePCpersonalcomputers,youhadtoremovetheROMfromthecomputerandreplaceit.WiththeinventionofFlashmemory,youcanreprogramthishybridRAM/ROMICwhereitlives,inthePC.UnderstandthatsomemicroprocessorshavetheFlashmemoryforcommandcodebuiltrightintothebodyofthemicroprocessor.ThereisasecondproblemwiththeAltair’sswitch-loadingprocesstoput
commandcodeintoprogrammemory.Inthatprocess,youhavetoenterthecommandsinbinary.Inouraboveexample,ifyouwantedtoenteracommandtoresettheaccumulatortoallzeroes,youhadtoknowthat00000000wasthecommandtoenter.Youhadtoeithermemorizethebinarycodeforeverycommand,orconstantlylookitupinareferencemanual.Thisnativecommandlanguageofmicroprocessorsof1’sand0’s(of5volts
and0volts)iscalledmachinelanguage.Itisobviouslytooclumsytoworkwith.
AssemblyLanguage(AppendixA-2)Hence,thedesignerofamicroprocessorwillprovidearelatedcommand
language,calledassemblylanguage.Assemblylanguageisashort,human-languagedescriptionofwhateachofthebinarymachinelanguagecodecommandsdoes.Thereisaone-to-onecorrespondencebetweenmachinelanguageandassemblylanguage.Ifthereare256machinelanguagecommands,thereare256assemblylanguagecommands.Asanexample,assumethemachinelanguagecommand00000000executes
byresettingeverybitintheaccumulatortozero.Theassemblylanguagecommandforthismightbe:CLRACC.Thiswouldbeagoodchoice,becauseitisshortfor“cleartheaccumulator,”whichisshortfor“makeeverybitofthegeneralpurposeregisternamedtheaccumulatorbecomezerovolts.”Apersoncanprogramwithassemblylanguagemuchmoreeasilythanwith
machinelanguage.It’seasiertomemorize,andeasiertotypewithoutmakingmistakesthanbinary,especiallyifthesizeofthecommandsare16bits,32bitsor64bitspercommand.Butwait:Ijustusedtheword“type.”Howdowegofromflippingswitcheson
theAltairtotypingcommands?Well,rememberwhenIsaidwecouldautomatethetaskofflippingswitches?Weautomatethetaskofgettingcommandcodeintomemorybyusinganothercomputer.Toprograminassemblylanguage,amemberofthemicroprocessordesign
teammustwriteacomputerprogramcalledanassembler.Theassemblerprogramhastheabilitytoreadasavedtextfilewritteninassemblylanguage,changeitintomachinelanguage,thensaveitasanew,machinelanguagefile.Let’selaborateonthis.Anassemblylanguageprogrammertypesalineofcode
intoatexteditorprogram,likeNotepad.AssumeNotepadcodifiestextusingASCIIcode.ForourCLRACCcommand,theCinCLRgetssavedinthetextfileastheASCIIcode01100111.TheLinCLRgetssavedinthetextfileastheASCIIcode01110110.Thisprocesscontinuesuntilthewholeprogramisfinishedandsaved.Let’ssayitissavedas,“myAssem.src.”Next,theassemblylanguageprogrammerrunstheassemblerprogram.The
assemblerneedstoknowwhichprogramtoassemble.Theprogrammerenters,“myAssem.src.”Theassemblerprogram“assembles”“myAssem.src.”ThatmeansitconvertstheASCII-encodedassemblylanguagecodeintoASCII-encodedmachinelanguagecode.Itsavesthisasanewfile:“myAssembly.obj.”NoticeIsaiditsaves“myAssembly.obj.”inASCIIcode.So,whenitconverts
CLRACCto00000000(whichis8zeroes),itdoesn’treallyconvertitto8binaryvoltages.Sinceitissavingittoatextfile,itsaves00000000inthetextfile’salpha-numericencodingformat,whichwehaveassumedisASCIIcode.TheASCIIcodeforzerois01001000.Theassemblersaves01001000eighttimes,to
savethebinarycommand00000000.(Morefrequently,toreducefilesize,itsavesthehexadecimalinsteadofbinaryversionofthemachinelanguagecode.)“myAssembly.obj,”thenewmachinelanguageversionourprogram,contains
moreinformationthanjustthecommandcode.Italsocontainstheaddresswhereeachcommandwillliveincommandmemory.Thereason“myAssembly.obj”isnotsavedinbinaryisthatwehaveonemore
steptoaccomplishinourtask.Weusedacomputertoassemblethecode.Now,weusethecomputerto“burn”thecodetotheprogrammemory.First,weneedaspecializedhardwaredevicecalledaprogrammerorburner
designedtoputthecodeintotheprogrammemory.Thisdeviceconnectstothecomputerandtothetargetmemorytobeprogrammed.Iwillcallita“burner”becausecallingitaprogrammermakesusthinkwearetalkingaboutahumansoftwareprogrammer.(“Burner”isanoldterm,frombackinthedayswhenROMcodewasliterallyburnedinbymeltingmetallinksintheIC’s.Iwillcallitaburner,evenwhenreferringtoprogrammingFlashmemory.)Wealsoneedacomputerprogramthatcantaketheassembledprogram,
“myAssembly.obj,”andsendittotheburner.Unfortunately,thissoftwareprogramisalsoreferredtoasaprogrammer.Iwillcallitburnersoftware,becausecallingitaprogrammermakesusthinkwearetalkingaboutahumansoftwareprogrammer.So,theburnersoftwaretakesthe“myAssembly.obj”codeandsendsittothe
burnerhardware.Theburnerhardwarereadsthecodeandfinallyconvertsitintotruebinaryvoltagelevelsof5volts(1’s)and0volts(0’s).Itputsthecodeintothecorrectaddressesinsidethememorychipitisburning.
High-levelLanguages(AppendixA-3)Evenbeforemicroprocessorswereinvented,thecreatorsofmachinelanguage
andassemblylanguagerealizedthatprogrammingacomputerthiswaywouldseverelylimitthenumberofpeoplewillingtocreateprogramsthisway.Evenassemblylanguagerequiresadeepknowledgeoftheunderlyinghardware(circuits)inthemicroprocessor.Assemblylanguageprogrammersmustbefamiliarwithregisternames,interrupts,thestack,addresses,anddifferentwaystogenerateaddresses.Plus,ifyouworkwithadifferentmicroprocessor,commandnames,terminology,andtechniqueschange.So,theyinventedhigh-levellanguages.Theselanguageshavenameslike
Fortran,COBOL,BASIC,C,C++,andJava.Theyarecalled,“high-level,”notbecausetheyarehardertolearnormorepowerful.Assemblylanguageishardertolearnandmorepowerful.Theyarecalled“high-level”becausetheyareastepupfromhavingtoworkatthehardwarelevel.Theyallowapersontowriteaprogramwithouthavingtoknowhowhardwareorcircuitswork,withoutneedingtoknownamesofinternalregistersortheiraddresses.Plus,ifahigh-levellanguageisstandardized(meaningthecommandsarethesamenomatterwhoprovidesthatlanguage),youshouldbeabletolearnitonce,anduseitinanymicroprocessor-basedsystem.Ahigh-levellanguageisverydifferentfromassemblylanguage.Primarily,it
abandonstherelianceontheone-to-onenatureofassemblylanguagetomachinelanguage.Thegoalisstilltocreateamachinelanguageprogram.Butonecommandinahigh-levellanguagebecomesmanycommandsinmachinelanguage.Thatonecommandnolongerresemblesmachinelanguagecommands.Gonearereferencestoregisters,addresses,etc.Forexample,let’slookatajavalanguage“if”statement:
if(x>3){y=0;}Javaisahigh-levellanguage.Theabovecodemeans,“Ifthecontentsof
variablexisgreaterthanthree,thenchangethecontentsofvariableytozero.But,ifthecontentsofvariablexisnotgreaterthanthree,thenleavethecontentsofvariableyalone.”Thisonelineofjavacode,whenreducedtoassemblylanguage,becomes
manylinesofcode.Theassemblylanguagecodereferencesregistersandaddresses,andinvolvesaknowledgeofsignedbinaryarithmetic.Thegoodnewshereisthathigh-levellanguagesreducetomachinelanguage
inmuchthesamewaythatassemblylanguageprogramsreducetomachinelanguage.Thedifferenceis,a“compiler”isthenameofthesoftwarethatconvertsahigh-levellanguagetomachinelanguage.(Iwon’tdiscuss“interpreters,”toavoidneedlessconfusion.)
Small-systemCodevs.ApplicationCode(AppendixA-4)Wehavereachedapointwherewehaveexplainedtheearlierquestionswe
posed.Theaboveparagraphsexplainhowyoucanputcodeintoprogrammemory.Theyalsoexplainhowyoucangofrombuyingamicroprocessortocreatingamicroprocessor-basedproduct.Briefly,you:1.)Buythemicroprocessor2.)Studyitsarchitecture,addressspace,andcode3.)Buildcircuitsaroundthemicroprocessorwithwhichit“interfaces”4.)Writecommandcodeforthemicroprocessor5.)Usetheburnerhardwareandsoftwaretoputthecodeintoprogrammemory6.)MakelotsofmoneyThisdescriptionimpliesknowledgeofelectronicsdesign.Youdon’thaveto
designthemicroprocessorfromthegroundup,butyoumustknowhowitworks,andhowtobuilduponit,evenifyouareusingahigh-levellanguageforstepfour.Ithelpstohaveabackgroundincomputerengineering.Thatbeingsaid,justbecauseyouarenotacomputerengineer,thatdoesn’t
meanyouareautomaticallyleftoutofallthefun.Thereisanotherpathtoworkingwithmicroprocessorsthatdoesn’trequireintimateknowledgeofhowtheywork:softwareengineering.Youmayknowsoftwareengineers—computerprogrammers—whodon’tknowhowmicroprocessorswork.Youmaybeone,yourself.Softwareengineersworkonmicroprocessor-basedsystemsinwhichtheabove
fivestepsarealreadydone.Allofthehardwaredesigniscomplete.Theproductisalreadyfunctioning.Italreadyhassomebasic,burned-incode.Itisacomplexsystem,calledacomputer,ortablet,orcellphone.Inthiskindofenvironment,aprogrammeraddsmorecodetothecodethat
alreadyrunsthecomputer.Thisnewcodeextendsthecapabilitiesofthecomputer.Let’scallthisnewcodeanapplication,or“app.”Writinganappdoesnotrequireextensiveknowledgeofthemicroprocessoror
electronichardware.Allthatworkistakencareofbybuilt-incodecalledtheBIOSandbytheoperatingsystem(I’lldefinetheoperatingsystem,shortly).Designersoftheoperatingsystemprovideprogrammerswitha“SoftwareDevelopmentKit”,sotheprogrammer’sappcodecanconnectwiththeoperatingsystem’sfunctions.TheBIOSandtheoperatingsystem’sfunctionshandlethe“dirtywork”ofcontrollingthephysicalelectronics.ThiskindofprogrammingdoesnotinvolveburnersthatputcodeintoROM.Ina
computer,anappisfetchedfromDRAM(dynamicRAM).TheabilityforlargersystemstoexecutecodefromDRAMbringsustoawholenewprogrammingandhardwareenvironment.Thefigurebelowhelpsexplainwherecommandcode
comesfrom,inaPC-stylecomputer:
FIGUREA-2
FigureA-2showsthelargemicroprocessor-basedsystemwethinkofwhenwe
talkabouta“computer.”Inthissystem,themicroprocessornormallyfetchesitscommandcodefromDRAM.DRAMischeap;andit’slargeenoughandfastenoughformostpurposes.However,itisvolatile:itlosesinformationwhenturnedoff.So,programscan’tbestoredinDRAMwhenpowerisoff.Itisemptywhenturnedon.Furthermore,evenifitwasnon-volatile,itscapacityisn’tgreatenoughtostorealltheappsandfilesamoderncomputeruserrequires.So,weneedamassivelylargestorageareathatisnon-volatile;onethatretains
appsandfileswhentheunitisturnedoff.That’sthejoboftheharddrive.(Or,solidstatedrive:flashmemoryforsmaller,lightweightunitslikenotebookcomputers.)Theproblemis,themicroprocessordoesn’tfetchcommandcodedirectlyfrom
theharddrive.Theharddriveistooslow.It’sanelectro-mechanicaldevice.Itaccessesinformationusingmotors.Toamicroprocessor,waitingformotortomoveislikeuswatchinggrassgrow.So,codestoredintheharddrivethatthemicroprocessormustexecutemust
firstbemovedtoDRAM,thenfetchedfromDRAM.FollowthearrowsandthenumberstounderstandFigureA-2.Whenthe
microprocessorwakesupatpower-up,itmustfetchcodefromwhicheveraddressithasbeendesignedtoretrieve.ThecomputercreatorsputBIOSinthataddressspace(step1).BIOS(BasicInput/OutputSystem)isinasmallmemoryspace.Itisjustlikethe
permanentcodeloadedbyaburner,thatwecoveredinourdiscussionofsmallmicroprocessor-basedsystems.Itisasmall,preliminaryoperatingsystem.TheBIOSisthenamegiventoboththeintegratedcircuitchipandthesoftware(firmware,sinceitispermanent)insideit.Anoperatingsystemisthecommandcoderesponsiblefortheoverheadofrunningacomputer:loadingprograms,savingprograms,maintainingafilesystem,inputandoutputofdata,etc.BIOSperformssomeself-testsonthecomputer.Itcheckssettingsstoredinthe
SetupIC.InSetup,itfindsthebootorder:theprioritizedlistofwheretofindtheprimaryoperatingsystem,likeWindowsorLinux.Inourexample,theBIOSfindstheprimaryoperatingsystemintheharddrive.StillfetchingfromBIOScode,themicroprocessorcopiestheprimaryoperating
systemfromtheharddriveintoDRAM(step2to3).Whenthatisdone,thecodelastcodeexecutedbyBIOschangestheprogramcountertopointtotheaddressofthefirstcommandintheprimaryoperatingsystem,inDRAM.Whentheuserusesaninputdevicetoloadanapp,sayawordprocessorapp,theoperatingsystemrespondstothatinputbycopyingthewordprocessorappfromtheharddrivetoDRAM(step3to4to5).TheoperatingsystemletssomeofthecodefetchestobefromthewordprocessingappinDRAM.Iftheuserofthewordprocessingapploadsanolddocumenttoedit,theoperatingsystemcopiesthatdocumentdatafromtheharddriveintoDRAM(step5to6to7).AnychangesmadetothedocumentaremadeintheDRAMcopy.Whentheuserwantstosavethenewlyediteddocument,theoperatingsystemcodecopiesitfromDRAMbacktotheharddrive(step7to8).Thus,whenaprogrammercreatesanappandyouinstallitinyourcomputer,
youareputtingitintotheharddrive.There,itbecomesoneofmanyotherprograms.Whenitisneeded,itgetsloadedintoDRAM.Fromthere,thecodeisfetched,tobedecodedinsidethemicroprocessor’sCPU.Asyouhaveseen,theanswertoourquestion,“Howdoyougetcodeinto
programmemory,”isnotasimpleone.Partoftheproblemisthattherearedifferentkindsofmicroprocessor-basedsystems.Somearesimpleandsmall.Othersarecomplexandelaborate.So,forexample,forasmall,simplemicroprocessor,codemaysimplyneedto
beburnedintoROM.Apersonmaychoosetoprogramitinassemblylanguage.Peoplemaydothisbecausetheylovehowmicroprocessorswork;programminginassemblylanguagemakesthemfeelclosertothe“workings”ofthemachine,tothe“machinery”ofthemachine.Or,theymaybelievethatassemblylanguageprogramsaremoreefficientandcompact.Peopledid,atonetime,alsocreateassemblylanguageprogramsforPC-stylehomecomputers.Aprogramnamed“Debug”wasusedforthispurpose.Ontheotherhand,inalarge,complexmicroprocessorsystemlikeacomputer,
somecodemuststillbeburnedintoROM.But,muchmorecode—writteninahigher-levellanguage—canbestoredinaharddrivebutrunfromDRAM.
WriteOnce,RunAnywhere(AppendixA-5)Nowthatwehavediscussedlargemicroprocessor-basedsystems—computers
—let’sgobacktomyearlierreferenceaboutthefollowingproblem.YouhavemicroprocessorA,madebyAtmel;microprocessorB,madebyIntel;andmicroprocessorC,madebyMicrochip.Youhavecreatedhigh-levellanguagecode.However,themachinelanguagecodeforeachoftheseistotallydifferent.You
can’tjustrunonecompileronetimetochangeyourhigh-levellanguagecodeintomachinelanguageforallthreemicroprocessors.ThemachinelanguageproducedformicroprocessorAwillnotworkformicroprocessorsBorC.Youwouldhavetorunahigh-levellanguage-to-microprocessorAcompiler;thenahigh-levellanguage-to-microprocessorBcompiler,thenahigh-levellanguage-to-microprocessorCcompiler.That’swhy,traditionally,codewrittenforPC-stylecomputersdidnotworkin
Applecomputers,andviceversa.PCstraditionallyusedIntelmicroprocessors,whileApplestraditionallyusedMotorolamicroprocessors.TheJavalanguagemadeabreakthroughwiththisproblem,withasolution
referredtoas,“writeonce,runanywhere.”Withjava,youcompileyourprogramonce.Theresultingcodeispartlycompiled.Itiscompiledintoanintermediatestate,called“bytecode.”Then,youinstallajavavirtualmachineonyourcomputer.Thisjavavirtualmachineissoftwaremadespecificallyforyourmicroprocessor.Whenyourunyourjavaprogram,thejavavirtualmachineconvertsthebytecodeintothemachinelanguagethatyourmicroprocessorwasdesignedtoexecute.Thus,youcandistributethesamebytecodeontheinternettoanycomputerrunbyanymicroprocessorand,assumingithasthecorrectjavavirtualmachineinstalled,itwillexecuteproperly.
APPENDIXBD/ACONVERSION
Asanotherbonus,I’dnowliketotakeyouonestepbeyondyourknowledgeof
howmicroprocessorswork.Ihaveshownyouhowmicroprocessorsinterfacewithotherdigitaldevices.Now,I’dliketoshowyouhowmicroprocessorsinterfacewithanalogdevices.Thisabilitytointerfacewithanalogdevicesisimportant,becausethe“real”
world,thehumanworld,isanalog.Therealworldconsistsoftemperature,light,velocity,color,sound,wind,andforce,tonameafew.Eachofthesecanbeincountlessstates.Acarcanmoveat10milesperhour.Also,itcanmoveat15,or20.5,or30.22,or30.222,or30.2222milesperhour.Thisqualityofbeinginmanymeasureablestatesiscalledanalog.Thequalityofbeinginonlytwomeasureablestatesiscalleddigital.Theabilityofmicroprocessorstointerfacewiththeanalogworldisexciting,
becauseitgreatlyincreasestheirpowerandusefulnesstous.Itenablesmicroprocessorstobeabletomonitor,andtosomeextentcontrol,thereal,analogworldoftemperature,light,velocity,color,sound,andforce.Beforewehadmicroprocessors,wehaddevicescalledtransducers.
Transducersaredevicesthatchangeoneformofenergyintoanother.Sometransducerschangeoneaspectofouranalogwordintovoltage.Forexample,amicrophonechangesasoundintovoltage.Athermocouplechangesheatintoavoltage.Atachometerchangesrotationalvelocityintovoltage.Othertransducersworkintheoppositedirection.Theychangevoltageintoan
elementofouranalogworld.Aheatingelementchangesvoltageintoheat.AnLEDchangesvoltageintolight.Aspeakerchangesvoltageintosound.However,thevoltage,ineachoftheabovetwotypesoftransducers,isanalog
voltage.Themicroprocessorisavoltage-baseddevice,butitsworldisoneofdigitalvoltages.Whatthemicroprocessorneedsisonetypeofdevicethatconvertsanalogvoltagesintodigitalvoltages:anA-to-Dconverter(analog-to-digital).And,itneedsanothertypeofdevicethatconvertsdigitalvoltagesintoanalogvoltages:aD-to-Aconverter(digital-to-analog).Tostatethismoreaccurately,themicroprocessorneedsadevicethatconverts
oneanalogvoltageintoagroupofdigitalvoltages.Thenitwouldbeabletosampletherealworld.Therealworldfirstgetsturned—byatransducer—intoananalogvoltage,whichgetsconvertedtoagroupofbinaryvoltagebyanA-to-Dconverter,whichgetsinputbythemicroprocessor.(Seepart(a)ofFigureB-1,below.)Themicroprocessorneedsasecondtypeofdevicethatconvertsagroupof
binaryvoltagesintooneanalogvoltage.Thenitwouldbeabletocontroltherealworldbygeneratingabinarygroupofvoltages,whichgetturnedintoananalog
voltagebyaD-to-Aconverter,whichgetsturnedintoarealworldeffectorbyatransducer.(Seepart(b)ofFigureB-1,below.)
FIGUREB-1
FigureB-1showshowonesuchsystemwouldwork.Hopefully,youare
pleasantlysurprisedbyhowmuchofthissystemyoualreadyunderstand.ItshouldgreatlyresembleFigure10-4,whichwestudiedindepth.ThemicroprocessorusestheaddressbusandaddressdecodertoenabletheA/Dconverter,andreaditsinputfromthedatabus.Also,themicroprocessorenablestheD/Aconverter,andwritesinformationtoitviathedatabus.BoththeA/DandD/AconvertershaveourfamiliarD-typelatchesbuiltintothem.Thepurposeofthiscircuitisforthemicroprocessortoreadthetemperaturein
part(a),theuppercircuit.Then,ifthetemperatureistoohigh,themicroprocessorturnsonthecoolingfaninpart(b),thelowercircuit.Followthearrowstounderstandthedirectionofinformationflow.Don’tbeconfusedbytheextra“convert”and““interrupt”linesontheA/Dconverter.Usually,youmustfirst
commandtheA/Dconvertertodoaconversion(“convert”).Whentheconversioniscomplete,theA/Dconvertermakesthe“interrupt”linetrue,sothatthemicroprocessorknowstoreadtheresultsoftheA/Dconversion.Youalreadyunderstandinterrupts,too!Thiscircuitshouldbearealeye-opener,andhelpyouseewhybillionsofsmallmicroprocessorsaresold.I’llshowyouasimpledesignforaD/Aconverter,later.Thedesigninvolvesan
op-ampintegratedcircuit,solet’sstartwiththat.Seethepicture,below:
FIGUREB-2
ThetrianglecircuitsymbolinFigureB-2istheop-amp.Don’tconfuseitwiththe
symbolforabufferoraninverter.Thosetwoarebinarydevices.Anop-ampisananalogdevice.Theop-ampcomesinanintegrated-circuitbody,withexternalpinconnectionstotheoutsideworld,sothatdifferentexternalcomponentscanbeattached.Thisgivestheop-amptheflexibilitytobecomethecoreofmanydifferentkindsofcircuits.
Op-ampsbringsgreatpowerandsimplicitytoanalogcircuitdesign.Theyusuallysimplifythemathematicsneededtocompleteadesign.Theyreducethenumberofcomponentsneededforacircuit,inlargepartbecausetheyhavemanytransistorsinsidetheirintegrated-circuitbody.Forexample,theop-ampcircuitconfigurationinFigureB-2isaninverting
voltageamplifierwithagainof10.Avoltageamplifiertakesaninputvoltageandcreatesabiggeroutputvoltage.Intruth,anamplifierisamultiplier.InFigureB-2,theinputvoltage(Vin)of1voltismultipliedby10,andoutput(Vout)as-10volts.(Yes,negative10volts.Wedidsaythisisaninvertingamplifier.Wecancreateanon-invertingamplifierwithadifferentop-ampdesign.Or,wecandouble-invertthiscircuit’soutputwithasecondinvertingamplifierwithagainof-1.)LookcloselyatFigureB-2andyouwillseethattheratioofresistorRfto
resistorRinis10kohmsto1kohms.“k”isthemetricsymbolfor“thousand.”So,10,000/1,000=10.Theirratiois10,which,notcoincidentally,isthegainofthecircuit.Thus,onecanlearntodesignamplifierswithop-ampsinamatterofminutes.Canyouchangethisdesignsothatthegainis20?(Answer,changeRfto20,000ohms.)What’sthesecretbehindthepower,yetsimplicity,ofop-amps?I’llexplainit
now,butdon’tworryifyougetlost.Justrememberthat,whilethesecretiscomplicated,theendresultissimplicity.Inthecaseoftheinvertingamplifier,forexample,thegainissimplyRfdividedbyRin,theratiooftworesistors.Thesecretstartswithanapparentabsurdity.Internally,anop-ampisa
differentialamplifier,withagainofabout100,000.Inadifferentialamplifier,asubtractiontakesplacebeforetheamplifier’smultiplication.Thevoltageinputatthepinlabelled“+”minusthevoltageinputatthepinlabeled“-”ismultipliedbyabout100,000,toproduceanoutputvoltageatVout(thetipofthetriangleontheright).Thisisridiculous.Adifferenceinvoltageof1voltfromthe“+”tothe“-”input
wouldproduceanoutputvoltageof100,000volts.That’simpossible.Themostthisop-ampcanproducefromitsVoutoutputis+15voltsor-15volts(actually,alittleless).That’sbecause,asseeninFigureB-2,weareprovidingitwith+15voltsand-15voltsaspowersupplyinputs.Infact,foranydifferenceinvoltageofgreaterthan.0001voltsbetweenthe“+”andthe“-”inputs,thisdeviceisforthemostpartuseless.Thesecondcharacteristicofop-ampsisthattheinputresistanceintothe“+”
andthe“-”inputsisabout2millionohms.Verylittlecurrentwillevergointoitsinputs.Thesecrettotheamazingthingsanop-ampcandoforusishiddeninabranch
ofengineeringthatmostpeoplehaveneverheardof.It’scalled“controlsystems.”Therelatedjobtitleis,“controlsengineer.”ControltheoryhelpstopreventeventslikethecollapseoftheTacomaNarrowsBridge,whichbrokeintohugeoscillationsandfelldownwhenthewindhititjustright.Ifyouhaveneverwitnessedthis,
watchthevideoonYouTube.Controltheoristshavedevelopedawonderfuldesigntrickcalled“negative
feedback.”Aportionofthesystem’soutputis“fedback”andsubtractedfromthesystem’scontrolinput,tobecometheactualamplifierinput.Thislittletrickhashugeimplications.Itresultsinasystemthatisself-
correcting.Thatmeans,ifanexternaldisturbancetriestochangethedesiredoutput,thesystemreactsandcompensates.Theoutputisautomaticallyrestoredtoitsdesiredstate!Negativefeedbackcontrolsystemsareusedtomakefurnacesthat
automaticallyrunlongerwhenitiscolder;motorsthatturnwithmoretorquewhenaconveyorbelthasaheavierload;andcarcruisecontrolsystemsthatmaintainaconstantvehiclespeedforuphillordownhillroads.InFigureB-2,tracethepathfromtheoutput(Vout),goingbackthroughRf,and
intotheinputlabeled“-“.Thisisnegativefeedback.TheoutputfeedsbackthroughRf.Rfstandsfor“feedbackresistor.”Itgoesintothe“-”input.Thispathiscalledthe“closedloop”.Theinput,Vin,alsogoestothe“-”op-ampinput.Thisjunctionisthepoint
wherethecurrentfromthefeedbackoutputcurrentissubtractedfromtheinputcurrent,withtheremaindergoingintothe“-”input.Here’showtheautomaticerrorcorrectionworks.Assumethatincreasedloadcurrentdemandontheop-ampmakesitsoutputvoltagedecrease.That’sabadthing.Wewantoutputvoltagetobereliablyconstant.ThisdecreasedoutputvoltagecauseslesscurrenttoflowthroughRf.LessRfcurrent,subtractedfromRin,leavesmorecurrenttogointothe“-”input.Morecurrententering“-”raisestheoutputvoltage.Outputerrorsarethusself-corrected.Aloweredoutputvoltagegetsautomaticallyraised.That’swhatnegativefeedbackcontrolsystemsdo.Furthermore,thenegativefeedbackalsoovercomestheproblemoftheinternal
gainoftheop-ampbeingtoohigh,intherangeof100,000.Whenweclosetheloop(inserttheRfpath),thevoltageandcurrentdifferencebetweenthe“+”and“-”inputsisautomaticallykeptsmallenoughtokeeptheoutputvoltageinauseablerange.Remember,it’sthedifferencebetweenthevoltageat“+”and“-”inputsthatismultipliedtoproducetheoutputvoltage.Here’showallthetrickscometogetherinthecircuitofFigureB-2.Theop-amp
turnsthenodeinthecircuitatits“-”inputintoa“virtualground.”Whatisavirtualground?Well,the“+”inputisattachedtotherealcircuit
ground.That’sthepointofreferenceforallourvoltagemeasurements,oftenthenegativeofabatteryorpowersupply.Duetonegativefeedbackandthehighinternalgainoftheop-amp,theop-ampcircuitself-balancesitselfsothatavoltageinthemicrovoltrangeispresentatthe“-”input.That’sallitneedstobe,sincethedifferentialgainissohuge(x100,000).Voltage-wise,thevoltageatthe“-”inputissocloseto0volts,itis“virtually”atgroundpotential.
However,eventhoughthevoltageatthe“-”op-ampinputispracticallyatgroundvoltage,itisnotadirectpathtotrueground.Remember,almostnocurrentcomesintothe“-”input.Ithas2millionohmsofresistance.Thebottomlineis:thejunctionwhereRin,Rf,and“-”meetiskeptat0volts,but
virtuallynocurrentgoesintothe“-”op-ampinput.VirtuallyallthecurrentgoingthroughRinwindsupgoingthroughRf.Now,theleftendofRinhas1voltappliedtoit.TherightendofRiniskeptat
virtualground,0volts,bynegativefeedbackcontroltheorymagic.So1voltisacrossRin.Ohm’sLawdemandsthattheresultingcurrentthroughRinisIin=Vin/Rin=1/1000=.001amps.
WesaidvirtuallyallthecurrentgoingthroughRinwindsupgoingthroughRf.Thatmeans.001ampsgoesthroughRf.Ohm’sLawdemandsthattheresultingvoltageacrossRfisVf=IfxRf=.001x10000=10volts.However,theconventionalcurrentflowisfromlefttoright.Currentmovestomorenegativeenergylevels.SincetheleftsideofRfis0volts,therightsidehas10voltslessenergypercoulombofcharge.So,Voutis-Vf,or-10volts.Youmayfindallthisbaffling,buttheresultisverysimple.WeknowthatIin
effectivelyequalsIf,sowecancallthemboth,“I.”BasicalgebratellsuswecansubstituteI=Vin/RinintoVout=-IxRf,togetVout=(-Vin/Rin)xRf.Re-arranging,wegetVout=-(Rf/Rin)xVin.
So,wehavecomefullcircle.Whenwebeganthisdiscussion,Ipointedoutthattheresultwouldbethissimple.ThecircuitgainissimplytheratioofRftoRin.InFigureB-2,thegainis-10.Hiddenbehindthissimplicityisaloadofcomplexity,asyouhaveseen.Now,let’sforgetaboutallthiscomplexity,andfocusonusingthesimplicity.
Let’staketheinvertingamplifierfromFigureB-2anddesignfromitaD/Aconverter.Seethedesigninthefigurebelow:
FIGUREB-3
FigureB-3,part(a),showstheD/Aconverterdesignedmoreabstractly.Fromit,
youcanseethemathematicalrelationshipofresistorvalues.Forwhatevervalueofresistorvalue,R,thatyouchoose,2RmustbearesistorvaluethatistwiceasbigasR,4Rmustbearesistorvalue4timesthesizeofR,etc.Basedonthatrelationship,IhavedesignedanactualD/Aconverterinpart(b),usingresistorvalues1kohms,2kohms,4kohms,and8kohms.“k”isshortfor“kilo”.“kilo”isametricmultiplierfor1thousand.So,8kohmsis8,000ohms.Theop-ampinFigureB-3isaweighted,summing(inverting)amplifier.Ifallthe
resistorvaluesinFigureB-3werethesame,itwouldbearegularsumming(inverting)amplifier.Theequationwouldbe:Vout=(V1+V2+V3+V4).Onceagain,wewitnessthesimplicityofop-ampdesign.Wanttoadd10
voltagestogether?Get11resistorsofequalvalueandbuildanop-ampsummingamplifierliketheoneabove.Adiscreteop-ampissmallerthanadime,andcostsaquarter.Resistorscostapenny.Nomathisinvolved.Ifyoudon’tlikethenegativesignintheoutputvoltage,invertthevoltagebacktopositive(doubleinversion:negativetimesnegativeequalspositive)byattachingthefollowingcircuittotheoutputofFigureB-3:
FIGUREB-4
Don’tworryaboutpayingmorethanaquarterifyouaddthiscircuit.Theop-ampIfoundfor25centscontains2op-ampsinone8-pinICpackage.However,theresistorsinFigureB-3arenotallthesamevalue.Theyare
“weighted,”inthesamewaythatmulti-bitbinarynumbersareweighted.Inabinarynumberlike1011,asyoumovefromtheright-mostbittotheleft-mostbit,thevalueofeachbitpositiondoubles.Representinga4-bitbinarynumberasABCD,theDbitisworthdecimal1,theCbitisworth2,theBbitisworth4,andtheAbitisworth8.Theresistorsintheop-ampcircuitinFigureB-3followthesamedoublingsequence.Thatshouldmakesense,becausewearetryingtoturna4-bitbinarynumberintoananalogvoltage.Theop-ampcircuitinFigureB-3,part(b),iseasytounderstand.Wecan
analyzeitasifitwerefourseparateop-ampcircuitsliketheoneinFigureB-2.Inotherwords,wecancoverupthe2k-,4k-,and8k-ohmresistors,andfindthegainfortheV1voltageinputtobe-1k/1k=-1.Then,wecancoverupthe1k-,4k-,and8k-ohmresistors,andfindthegainfortheV2voltageinputtobe-1k/2k=-.5.Wecancoverupthe1k-,2k-,and8k-ohmresistors,andfindthegainfortheV3
voltageinputtobe-1k/4k=-.25.Wecancoverupthe1k-,2k-,and4k-ohmresistors,andfindthegainfortheV4voltageinputtobe-1k/8k=-.125.SincetheV1,V2,V3,andV4inputsarealldigital,theywillbeeither0voltsor5
volts.Iftheyare5volts,theV1inputwilldeliver-1x5=-5voltatVout;theV2inputwilldeliver-.5x5=-2.5voltsatVout;theV3inputwilldeliver-.25x5=-1.25voltsatVout;andtheV4inputwilldeliver-.125x5=-.625voltsatVout.Alternatively,ifwedothesameanalysisonFigureB-3,part(a),wecomeup
withequationsforeachseparateinput’sgain:fortheV1input,Vout=-R/R=-1xV1;fortheV2input,Vout=-R/2R=-.5xV2;fortheV3input,Vout=-R/4R=-.25xV3;andfortheV4input,Vout=-R/8R=-.125xV4.Theeasypartisthatwecansimplyaddthesefourresultstogethertogetthe
actualbehavior—andtheequation—ofthiscircuit.Eachofthefourcircuitscontributesitsowncurrentthroughthefeedbackresistor.Thesecurrentssimplyaddtogether,thengetmultipliedbyRtocreateVout.So,addingtogetherthefourresultsfromtwoparagraphsback,weproducethis
equationforthisweighted,summingamplifier:Vout=-(V2+.5xV2+.25xV3+.125xV4),orVout=-(V1+V2/2+V3/4+V4/8).WecanseefromtheaboveresultsthattheleastsignificantbitinputmustbeappliedasV4,andthemostsignificantbitinputmustbeappliedasV1.Theanalysiswouldn’tbethissimpleformostcircuitsdesignedtoaddvoltages
together.Anyoneinputvoltagewouldinterferewiththeotherthreeinputvoltages.But,theop-amp’svirtualgroundatthe“-”inputpreventsthisinterference.(Applicationofthesuperpositiontheorem,whichIwon’tcover,coupledwithanunderstandingofthevirtualground,provesthis.)Let’smakeatablefromtheaboveresults.Wecancreatethetablefromthe
numericalresultsabove.Or,wecancreateitfromtheaboveequation,rememberingthatV1,V2,V3,andV4canonlybe0voltsor5volts.
FIGUREB-5
ThetableinFigureB-5clearlydemonstratestheD/Aconversionofthecircuitin
FigureB-3.ThevoltagesincolumnslabeledV1throughV4areallthepossiblebinaryinputvoltages,inascendingbinarynumericalorder.ThecircuitoutputvoltageisdisplayedinthecolumnlabeledVout.Thisanalogoutputvoltagestepsup(actuallydown,sinceitisnegative-going)by.625volts,foreachbinarycountincrement.Weoftendon’tcareaboutthenegativesignoftheoutputvoltage.And,we
usuallydon’tcareaboutthefactthattheanalogoutputvoltageisnottheexactnumericalvaluecorrespondingtothebinaryinputvalue.WeusuallyjustcarethattheanalogVout’sincreasesareproportionaltothedigitalVin’sincreases.However,ifthenegativepolarityandrelativeproportionalityofinputtooutput
areaproblem,youcanaddasecondop-ampcircuittotheoutputofthefirst:
FIGUREB-6Ihavedescribedthissolution,before.But,thistime,thegainofthesecondop-
amp,ontheright,istimesnegative1.6(x-1.6).Thisoutputinvertsthenegativevaluesofthefirstop-ampbacktopositive.Itsgain,x-1.6,createsanoutputvoltagethatisthedecimalanalogequivalentofthebinaryinputvoltage.ThelastcolumninthetableinFigureB-5displaystheanalogoutputvoltage,
Vout,fromFigureB-6.Forexample,inputvoltagesofV1=5v,V2=0v,V3=0v,andV4=5vcorrespondtoaninputof1001,inbinarylogic.Binary1001equalsdecimal9.NinevoltscomesoutofVoutinFigureB-6,andislistedinthetableofFigureB-5.I’llmentionafewdrawbacksinthisD/Aconverterdesign.First,you’llnotice
that,inFigureB-5,Idon’tlistoutputvoltagesabove12volts.ThecircuitinFigureB-6can’treach15volts.Maximumop-ampoutputvoltagesarelessthantheirpowersupplyvoltages.Mydesign,above,used+15voltsand-15voltspowersupplies.Specificop-ampspecificationsheetswouldtelladesignerhowcloseto15voltstheoutputcanreach.Onesolutiontothisproblemistouse+18voltsand-18voltspowersupplies.Then,ouroutputvoltagescouldreach15volts.Second,theresolutionoftheabovedesignisnotverygood.D/Aresolutionis
onedividedbythemaximumbinarycount.Inourexample,themaximumbinarycountis1111(decimal15).So,theresolutionis1/15=.066667.So,ifourmaximumoutputvoltageis15volts,theD/Aconverter’soutputstepsareall1voltapart.That’sbecause15times.066667equals1volt.Fromthiscircuit,wecan’tproduceoutputvoltagesof3.3volts,or3.7volts.Theclosestwecangetisthenearestresolutionvaluesof3voltsor4volts.ThiswouldnotsoundverygoodifweweretryingtouseD/Aconversionto
reproducesounds.Weneedthosevoltagesbetween3voltsand4volts.Thesolutionistocreateacircuitwithbetterresolution.ThatmeansourD/A
circuitmustaccommodatemorebinarybits.TheabovecircuitwasgoodtohelpyouunderstandhowD/Aconversionworks,becauseitisrelativelysimple.However,itdoesnotscalewell.Toaccommodatemorebitswiththisdesign,we
mustkeepdoublingthesizeoftheresistors.But,ifwewanttocreatea12-bitwideA/Dconverter(resolution=.00024)fromthiscircuit,someoftheresistorvalueswouldbetoobig.Op-ampsdon’tworkwellwithresistorvaluesthataretoobig.Themagic
propertiesoftheop-ampbecomenegated,andtheaccuracygetsdestroyed.Op-ampsalsodon’tworkwellwithresistorvaluesthataresmall.Thoseresistorsdrawtoomuchpower,andgethot.D/AconversionbasedupontheR/2Rdesignwouldbebettertoaccommodate
improvedresolution.Thatdesignalsobuildsaroundanop-amp,butusesresistorsthatdon’tspreadoverawiderange.It’sjusthardertoexplain,requiringfromthestudentaknowledgeofThevenin’stheorem.AtotallydifferentD/Aconversiondesignisonebaseduponfilteredpulse-widthmodulation.Iwon’tdiscussthese,here.Third,realizethatourop-ampdesignrequiresaccurateresistors.Precisionis
thetermweusetodescribehowcloseoutcomponentistoitslistedvalue.Also,the5voltsand0voltsinputvaluesneedtobeasaccurateaspossible.
Thisisnotassimpleasitsounds.Digitalspecificationsthatdefineavalidhighandavalidlowvoltagecanbesloppy.Forbetteraccuracy,voltageregulatorcircuitscanbeaddedtokeepvoltagescloseto5volts.Pleasedon’tgettoohunguponthethreedrawbacks.ThesolutionsIpointed
outaresimpletoimplement.Don’tmissthepointofthisappendix:digital-to-analogconversiongreatlyextendsthepowerofmicroprocessors.Withit,there’s
almostnoendtothenumberofthingsthemicroprocessorcancontrol:robots,cars,assemblylines,3Dprinters.Thelistgoesonandon.
APPENDIXCA/DCONVERSION
InthisbonuscircuitIwilldescribehowanalog-to-digitalconversionworks.But,
inordertodothat,Iwillfirstexplaincomparators.Acomparatorisanintegratedcircuitthatcomparestwoanalogvoltages,VaandVb.IfVaisgreaterthanVb,thecomparator’soutputbecomesahighvoltage.IfVaislessthanVb,thecomparator’soutputbecomesalowvoltage.Thus,acomparatorcomparesanaloginputvoltages,butproducesdigital(binary,2-state)outputvoltages.Refertothepicture,below:
FIGUREC-1
LookingatFigureC-1,part(a),wefindthecircuitdiagramforacomparator.
NoticethattheVaanalogvoltageinputentersthe“+”input,andtheVbanaloginputvoltageentersthe“-”input.Noticealsothattwopowersupplyvoltagesareprovided:+5voltsand-5volts.Wecandescribethecomparator’sbehaviorintermsofsignedmathematical
subtraction.WesaythatthecomparatorsubtractsVaminusVb.Iftheresultisapositivenumber,theoutputvoltagebecomesthesameasthe+5voltspowersupply.Iftheresultisanegativenumber,theoutputvoltagebecomesthesameasthe-5voltspowersupply.ThetableinFigureC-1,part(b),givesafewexamplestohelpyouseethis
moreclearly.Rememberfrommathclassthat-2isgreaterthan-3.Alsorememberthat-(-2)=+2.Inrowone,+3-(+2)=+1,whichispositive,sotheoutputgoesto+5volts.Inrowtwo,+2-(+3)=-1,whichisnegative,sotheoutputgoesto-5volts.Inrowthree,-3-(-2)=-1,whichisnegative,sotheoutputgoesto-5volts.
Inrowthree,-2-(-3)=+1,whichispositive,sotheoutputgoesto5volts.Thecomparatorbuildsuponsomethingyoualreadyknow.For,thecomparator
isanop-ampwithoutthenegativefeedbackconnection!Thatbeingsaid,whenshoppingforacomparator,don’tbuyanop-amp.Buyacomponentlabeled,“comparator.”Thecomparatorhasbeenoptimizedtoswitchfromahighoutputvoltagetoalowoutputvoltage(orvice-versa)morequicklythananop-ampusedwithoutfeedback.Ifyouremember,wesaidthatanop-ampisadifferenceamplifier.Itsubtracts
the“-”inputfromthe“+”input.Thenitamplifies(multiplies)thatdifferencebyaridiculouslyhighinternalgainoftimes100,000.Thus,evenadifferenceofgreaterthan50microvolts(.000050volts)wouldcausetheoutputvoltageoftheabovecircuittoreachits+5voltsor-5voltslimitation.Well,thecomparatortakesadvantageofthatproblem.Itdoesn’t“cure”it,by
addingnegativefeedback.Ifthevoltageonthe“-”inputisjustasmidgenmorethanthevoltageonthe“+”input,theoutputvoltagegoestoaslowasitcan,whichisinthiscaseisthe-5voltslimitationofitsnegativepowersupply.Ifthevoltageonthe“-”inputisjustasmidgenlessthanthevoltageonthe“+”input,theoutputvoltagegoestoashighasitcan,whichisinthiscaseisthe+5voltslimitationofitspositivepowersupply.(Rememberfrompreviousdiscussionsthat,duetointernallosses,outputsneverquitereachallthewayto+5voltsor-5volts.)Now,thetwopowersupplyvoltagesonthecomparatordon’thavetobe+5
voltsand-5volts.Theycanbe,forexample,+15voltsand-15volts,likeweusedforourpreviousop-ampcircuits.Somecomparatorsareoptimizedtoworkatpowersuppliesof+5voltsand0volts.Acomparatorthatonlyhastwooutputvoltages—+5voltsand0volts—
interfacesperfectlywithdigitalelectronicscircuits.Suchacomponentmakesaperfectconnectionbetweentheworldofanalogonitsinputsandtheworldofdigitalonitsoutput.WewillusesuchadeviceinourdesignofanA/Dconverter.ThepicturebelowshowsonedesignforanA/Dconverter:
FIGUREC-2
Thisisonedesign,chosenfromseveral,ofanA/Dconverter.Ihavechosen
thisoneforthesamereasonIhavechosenmanyofthepreviousdesignsinthisbook:itbuildsuponsub-circuitsyoualreadyknow.Onegoalfromthestarthasbeenforyoutoexperiencehowdigitalelectronicsandmicroprocessorcircuitsbuildgraduallyfromsimplicitytocomplexity.Eachcircuitisbuiltfrombuildingblocksofsimplercircuits.Buildingblockscontainsimplerbuildingblocks,whichcontainsimplerbuildingblocks,whichcontainsimplerblocks,etc.WhenyoulookatFigureC-2,youfindsubsystemsthatyoualreadyknow.See
Figure16-4toreviewcounters;FigureB-6toreviewD/Aconverters;andFigureC-1toreviewcomparators.SeeFigure7-13toreviewDlatchregisters.Hereweusearegistermadeofflip-flopsinsteadoflatches.But,youknowflip-flopsfromFigures15-1and15-2.Ourregisterhastri-stateoutputs,totakepartinamicroprocessorbussystem.Youknowtri-stateoutputsfromFigures7-19and7-20.Finally,refertoFigureB-1toseehowthisA/Dconvertercommunicateswithamicroprocessor-basedsystem,throughinputandoutputlinesInt,Convert,
Enable,aswellasthe8dataoutputlinesfromtheflip-flopregister.Asanoverview,considerthatthepurposeofananalog-to-digitalconverteristo
changeananalogvoltageintoamulti-bitdigitalvoltage.TheanalogvoltageentersthecomparatorasVin,onthelowerleftsideofFigureC-2.Thedigitalvoltagecomesouttheflip-flopregisterasD7throughD0,onthelowerrightsideofFigureC-2.Noticethatthepowersuppliesonthecomparatorare+5voltsand0volts.AsI
describedearlier,thislimitsthecomparatoroutputto+5voltsor0volts,perfectforthedigitallogiccircuitsitcontrols.Forsimplicity,wewillassumeVin’sanalograngeis0voltsthrough+5volts,too.Justbeawarethatthereareotheroptionsavailablethatallowforarangeofinputsfromnegativethroughpositivevoltages,toaccommodatesinewaveinputvoltages.(Onesolution:Wecanshiftinputvoltagesup,outofthenegative,withanop-ampsummingcircuit.)Next,lookatFigureB-1toseehowthemicroprocessorconnectsto,
communicateswith,andcontrolstheA/Dconverter.FocusontheConvert,Enable,andIntlines.Here’swhatthemicroprocessordoes:1.)PulsestheConvertlinehigh(thenbacklow),toclearthecounterto00000000andstarttheconversionprocess.2.)InternallyenablestheA/Dconversionhardwareinterruptrecognitioncircuitry,sothemicroprocessorcanrespondtotheA/Dconverter’sinterruptrequest(Int).3.)Doesotherstuff,whileawaitingtheA/Dconverter’sinterrupt.4.)RespondstotheA/Dconverter’sinterruptbyfirstdisablingtheA/Dconversionhardwareinterruptrecognitioncircuitry,sothatthemicroprocessortemporarilyignoresfurtherA/Dinterruptrequests.5.)AndsecondbyraisingtheEnablelinehigh,toreadtheD7throughD0linesoutofthe8-bitflip-flopregister.Toreiterate,theD7throughD0linesoutoftheflip-flopregisterarethedigitalequivalentoftheanaloginputvoltage,Vin.Step1,above,clearsthecountertoanoutputof00000000.TheD/Aconverter
receivesthisbinaryinputandconvertsittoananalogoutputvoltageof0volts.Becarefultoavoidconfusion,here.Yes,thisisaD/Aconverter,buriedintheheartoftheA/Dconverter.Confusioncanresultifyourbraindoesn’tkeeptrackofmyreferencestoA/DversusD/A.The0voltsoutoftheD/Aconverterfeedsintothe“-”inputofthecomparator.
Since0voltsislessthanthepositivevoltageonthecomparator’s“+”input,thecomparator’soutputbecomes+5volts.That+5voltsallowsthecountertocountbyraisingits“CtEn”inputhigh.Thatsame+5voltsfromthecomparatoralsoturnsofftheinterruptrequesttothemicroprocessorsinceourdesignrequiresalow(0volts)signaltorequestaninterruptontheIntline.(SignifiedbythebarovertheIntlabelandthebubbleonthemicroprocessorinput.)
Thecountercountstheexternalclockpulses,perhapsthesameclockthatrunsthemicroprocessor.Asthebinarycountrises,thevoltageoutoftheD/Aconverteralsorises.Itkeepsrisingonthecomparator’s“-”input,asitstrivestoreachtheinputvoltageonthecomparator’s“+”input.Whenthevoltageonthecomparator’s“-”inputfinallyexceedsthevoltageon
thecomparator’s“+”inputbyjustonestepupoutoftheD/Aconverter,everythingchanges.Theoutputofthecomparatorgoesto0volts.That0voltsstopsthecounterfromcounting,whilemaintainingthelastbinarycountvalue.Thatcountvalueisprecioustous.Itisthebinaryrepresentationofthevoltage
wearedigitizing,theinputvoltageVin.Howdoweknowthis?BecauseitisthebinaryvaluethatcausedtheD/AconvertertoproduceaVoutoutputvoltageequaltotheA/Dconverter’sVininputvoltage.Itmustbeso,becausethecomparatorannouncedit,whenitsoutputwentto0volts.Thecomparator’soutputgoingto0voltsdoesmore.Itsfallingedgestoresour
preciouscountfromthecounterintotheflip-flopregister.It’sstoredthereuntilthemicroprocessorisreadytoreaditfromthedatabus.Thecomparator’soutputgoingto0voltsdoesathirdthing.ItisalsotheNOT
Intsignalthat,whenlow,requestsaninterruptfromthemicroprocessor.Remember,themicroprocessorhasbeendoingotherchores,whilewaitingfortheNOTIntlinetogolow.Finally,themicroprocessorrespondstotheinterruptbyrunninginterrupt
processingcodethatreadsthetri-stateoutputsoftheflip-flopregister.ItdoesthisbygeneratingahighlogiclevelvoltageonEnable,activatingtheflip-flopregister’sOE(outputenable)line.ThemicroprocessornowhastheresultsoftheA/Dconversioninits
accumulator.TheNOTIntlineisstillactive(Low),butthat’sOK.Perstep4,above,themicroprocessorisignoringit.Themicroprocessorwon’tpayattentiontoitagainuntilafteritstartsthenextconversion,whenitpullstheConvertlinehigh,whichdeactivates(raiseshigh)theNOTIntlineandmakestheinterruptrequestgoaway.WhatdoesthisA/Dconversionvalue,nowinthemicroprocessor’saccumulator,
looklike?Let’sfigureitoutforourselves.Let’sassumethattheA/Dconverter’sinternalD/Aconverterworksonanoutputrangeof0to5volts.Fromthiswedeterminethattheresolutionofthe8-bitD/Aconverteris1/255thof5volts,or.0196volts.Fromthisinformation,wecancalculatetheexpectedvaluethatthe
microprocessor’saccumulatorholds.Let’ssaytheanaloginputvoltagefromthethermocoupleis+1volt.AfterA/Dconversion,whatvalueshouldthemicroprocessorhaveread?Well,witharesolutionof.0196volts,theleastsignificantbitontheD/A’sinput
isworth.0196volts.Thesecond-leastmostsignificantbitisworthtwice.0196,the
thirdmostsignificantbitisworthfourtimes.0196,etc.Fromthisinformation,wecanmakethefirsttworowsofthefollowingchart:
FIGUREC-3
Thebottomrowofthechartisouranswer.+1voltfromthethermocoupleis
readas00110100fromtheA/Dconverter.Toarriveatthatanswer,Isimplyusedthetrial-and-errortechniqueweusedinchapterninetosolvedecimal-to-binaryconversionproblems.Proceedingfromlefttoright,Iputa1underthefirstnumberthatislessthanthenumberweareconvertingtobinary,whichinthiscaseis+1volt..6272isthatnumber.Next,stillproceedingfromlefttoright,Iputa1underanyothernumberswhich,whenaddedtoourrunningtallyofnumberschosenfromrow2,justexceeds+1volt.Usingthistechnique,Ifoundthat.6272+.3136+.0784=1.0192.That’sthefirst
valuehigherthan+1volt.With1’sunderthosethreevalues,and0’sundertheothers,00110100isthefirstcountthatcausesthecomparatortotripwhenanalog+1voltenterstheA/Dconverterforconversion.Indecimal,00110100isequivalentto52.Whenwemultiply52times.0196weget1.0192,whichprovesoursolutiontobecorrect.So,themicroprocessorreads+1voltas00110100.Whatdoestheprogrammer
dowiththis?InourdesignshowninFigureB-1,weseethatthe+1voltscomesfromatransducercalledathermocouple.Theprogrammermustconsultthespecificationsonthethermocoupletodeterminehowvoltagescorrespondtotemperatures.Specificvoltagerangescorrespondtospecifictemperatureranges.Theprogrammer’scodecantestthebinaryvaluefromtheA/Dconvertertodeterminewhichrangeofvoltages,andhencewhichrangeoftemperatures,thebinaryvaluefallsin.Forhighertemperatureranges,theprogrammer’scodecansendproportionallyhighervaluestotheD/Aconverterthatcontrolsthecoolingfan,makingitspinfaster.Ihopeyouenjoyedexploringhowthiscircuitworks.Thereissomuchtoit,and
yetanunderstandingofitbuildsfromthingswehavepreviouslycovered.Youcanthinkitthrough,workbackwards,evendrilldowntotheleveloftransistorsandelectronstoenjoythecompletepictureofhowthiscircuitworks,inallitsgloriousdetail.