315 103 3MB
English Pages 215 Year 2004
TEAM LRN
TEAM LRN
AnalogandDigitalCircuitsfor ElectronicControlSystemApplications
TEAM LRN
This page intentionally left blank
TEAM LRN
AnalogandDigitalCircuitsfor ElectronicControlSystemApplications UsingtheTIMSP430Microcontroller by JerryLuecke
AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Newnes is an imprint of Elsevier
TEAM LRN
NewnesisanimprintofElsevier 200WheelerRoad,Burlington,MA01803,USA LinacreHouse,JordanHill,OxfordOX28DP,UK Copyright©2005,ElsevierInc.Allrightsreserved. Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,or transmittedinanyformorbyanymeans,electronic,mechanical,photocopying, recording,orotherwise,withoutthepriorwrittenpermissionofthepublisher. PermissionsmaybesoughtdirectlyfromElsevier’sScience&TechnologyRights DepartmentinOxford,UK:phone:(+44)1865843830,fax:(+44)1865853333, e-mail:[email protected].Youmayalsocompleteyourrequeston-line viatheElsevierhomepage(http://elsevier.com),byselecting“CustomerSupport” andthen“ObtainingPermissions.” Recognizingtheimportanceofpreservingwhathasbeenwritten,Elsevierprints itsbooksonacid-freepaperwheneverpossible. LibraryofCongressCataloging-in-PublicationData Luecke,Gerald. Analoganddigitalcircuitsforelectroniccontrolsystemapplications:usingtheTI MSP430microcontroller/byGeraldLuecke. p.cm. ISBN0-7506-7810-0 1.Electroniccircuitdesign.2.Electroniccontrol.3.Programmablecontrollers.I.Title. TK7867.L842004 629.8'9--dc22
2004054669
BritishLibraryCataloguing-in-PublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary. ForinformationonallNewnespublications visitourWebsiteatwww.books.elsevier.com 04050607080910987654321 PrintedintheUnitedStatesofAmerica.
TEAM LRN
ThebookisdedicatedtomywifeVelmaandourgrandchildren: FromtheLueckeside: Cameron,Graham,Andy,Alex,Alyssa, Brent,Jacob,Harper,Arielle,Emery. FromtheHubbardside: Jared,Garrett,Matthew,Ashton,Audrey.
TEAM LRN
This page intentionally left blank
TEAM LRN
Contents Foreword.......................................................................................................................................... xi Preface.............................................................................................................................................xii Acknowledgments.............................................................................................................................xiii What’sontheCD-ROM?.................................................................................................................. xiv Chapter1:SignalPathsfromAnalogtoDigital...................................................................................... 1 Introduction..................................................................................................................................................................1 ARefresher..................................................................................................................................................................1 Accuracyvs.Speed—AnalogandDigital...................................................................................................................5 InterfaceElectronics....................................................................................................................................................6 TheBasicFunctionsforAnalog-to-DigitalConversion..............................................................................................6 Summary......................................................................................................................................................................8 Chapter1Quiz.............................................................................................................................................................9
Chapter2:SignalPathsfromDigitaltoAnalog.................................................................................... 11 Introduction................................................................................................................................................................11 TheDigital-to-AnalogPortion...................................................................................................................................11 Filtering......................................................................................................................................................................13 ConditioningtheSignal.............................................................................................................................................13 TransducingtheSignal...............................................................................................................................................13 Summary....................................................................................................................................................................15 Chapter2Quiz...........................................................................................................................................................16
Chapter3:Sensors........................................................................................................................... 18 Introduction................................................................................................................................................................18 TemperatureSensors..................................................................................................................................................18 AngularandLinearPosition......................................................................................................................................21 Rotation......................................................................................................................................................................24 MagnetoresistorSensor..............................................................................................................................................24 Pressure......................................................................................................................................................................25 LightSensors.............................................................................................................................................................27 OtherSensors.............................................................................................................................................................32 Summary....................................................................................................................................................................32 Chapter3Quiz...........................................................................................................................................................32
Chapter4:SignalConditioning........................................................................................................... 35 Introduction................................................................................................................................................................35 Amplification.............................................................................................................................................................35 BipolarNPNAmplifier..............................................................................................................................................36 AmplifierFrequencyResponse..................................................................................................................................39 Coupling.....................................................................................................................................................................40 Small-Signalvs.LargeSignal....................................................................................................................................41 ClassesofAmplifiers.................................................................................................................................................42 Field-EffectTransistorAmplifiers.............................................................................................................................42 AN-ChannelJFETAmplifierDesign........................................................................................................................43 AnNPNMOSFETAmplifier....................................................................................................................................45 TEAM LRN
vii
Contents OperationalAmplifiers...............................................................................................................................................47 ConditioningtheOutputofaPressureSensor...........................................................................................................50 AMoreSophisticatedPressureSensorAmplifier......................................................................................................51 CurrentMirror............................................................................................................................................................52 ApplicationsofOpAmps...........................................................................................................................................53 Oscillators..................................................................................................................................................................53 PowerAmplifiers.......................................................................................................................................................54 ClassBAudioPowerAmplifier.................................................................................................................................56 SpecialSignals...........................................................................................................................................................56 RCTimeConstants....................................................................................................................................................58 FrequencySelection...................................................................................................................................................59 TypicalApplicationofFilters....................................................................................................................................61 Summary....................................................................................................................................................................62 Chapter4Quiz...........................................................................................................................................................62
Chapter5:Analog-to-DigitalandDigital-to-AnalogConversions............................................................ 66 Introduction................................................................................................................................................................66 DecimalEquivalentofaBinaryNumber...................................................................................................................67 DigitalCodesofADC................................................................................................................................................67 AResistorNetworkDAC..........................................................................................................................................68 ASimpleResistor-StringDAC..................................................................................................................................71 ASimpleCurrent-SteeringDAC...............................................................................................................................72 Analog-to-DigitalConverters(ADC)........................................................................................................................73 SuccessiveApproximationRegister(SAR)ADC......................................................................................................74 CapacitorCharge-RedistributionADC......................................................................................................................75 HighestSpeedConversions........................................................................................................................................78 SampleandHoldandFilters......................................................................................................................................78 Summary....................................................................................................................................................................79 Chapter5Quiz...........................................................................................................................................................80
Chapter6:DigitalSystemProcessing.................................................................................................. 82 Introduction................................................................................................................................................................82 DigitalProcessororDigitalComputer......................................................................................................................82 WhatisaMicroprocessor?.........................................................................................................................................86 WhatisaMicrocomputer?.........................................................................................................................................86 SystemClarifications.................................................................................................................................................86 DigitalSignalRepresentations...................................................................................................................................90 Clock,TimingandControlSignals............................................................................................................................90 Interrupts....................................................................................................................................................................92 StatusBits..................................................................................................................................................................92 MoreAboutSoftware.................................................................................................................................................93 SophisticatedProgrammingLanguages.....................................................................................................................95 HowPartsofaProcessorPerformTheirFunctions...................................................................................................95 MemoryandInput/Output.........................................................................................................................................97 AddressingModes.....................................................................................................................................................97 Summary....................................................................................................................................................................99 Chapter6Quiz.........................................................................................................................................................100
Chapter7:ExamplesofAssembly-LanguageProgramming.................................................................. 103 Introduction..............................................................................................................................................................103 AProcessorfortheExamples..................................................................................................................................103 AbouttheMSP430Family......................................................................................................................................103 TheCPU...................................................................................................................................................................104 TEAM LRN
viii
Contents ProgramMemoryandDataMemory.......................................................................................................................105 Peripherals................................................................................................................................................................106 OperationControlandOperatingModes.................................................................................................................106 WatchdogTimer.......................................................................................................................................................106 SystemReset...........................................................................................................................................................107 Interrupts..................................................................................................................................................................107 OscillatorsandClockGenerators............................................................................................................................107 Timers.....................................................................................................................................................................109 AddressingModes...................................................................................................................................................109 MoreonMSP430Control........................................................................................................................................110 FurtherThoughts......................................................................................................................................................114 Labels.......................................................................................................................................................................117 Instructions...............................................................................................................................................................117 Operands..................................................................................................................................................................117 HexadecimalNumbers.............................................................................................................................................117 Comments................................................................................................................................................................118 ProgrammingExamples...........................................................................................................................................118 SubprogramNo.1....................................................................................................................................................118 SubprogramNo.2....................................................................................................................................................127 SubprogramNo.3....................................................................................................................................................131 VariationofThreshold.............................................................................................................................................137 Summary..................................................................................................................................................................137 Chapter7Quiz........................................................................................................................................................138
Chapter8:DataCommunications..................................................................................................... 142 Introduction..............................................................................................................................................................142 TheDataTransmissionSystem................................................................................................................................142 ParallelandSerialTransmission..............................................................................................................................142 Protocols..................................................................................................................................................................144 High-SpeedDataTransmissions..............................................................................................................................145 SerialDataCommunicationsAdvances...................................................................................................................145 AReturntotheFormat............................................................................................................................................145 ShiftRegisters..........................................................................................................................................................147 USARTSerialCommunications..............................................................................................................................148 TheUARTFunctionwithSoftware.........................................................................................................................150 TechnologyAdvances..............................................................................................................................................150 I2CProtocol..............................................................................................................................................................150 USB..........................................................................................................................................................................152 Summary..................................................................................................................................................................156 Chapter8Quiz.........................................................................................................................................................157
Chapter9:SystemPowerandControl............................................................................................... 160 Introduction..............................................................................................................................................................160 VoltageRegulators...................................................................................................................................................161 LoadVariations........................................................................................................................................................162 ActualLinearVoltageRegulatorCircuit..................................................................................................................163 VoltageRegulation...................................................................................................................................................163 PowerDissipation....................................................................................................................................................164 SwitchingVoltageRegulators..................................................................................................................................165 SummaryofRegulators...........................................................................................................................................167 PowerSupplyDistribution.......................................................................................................................................168 PowerSystemSupervisors.......................................................................................................................................170 TEAM LRN
ix
Contents Summary..................................................................................................................................................................171 Chapter9Quiz.........................................................................................................................................................171
Chapter10:AMicrocontrollerApplication........................................................................................ 174 Introduction..............................................................................................................................................................174 ApplicationBlockDiagram.....................................................................................................................................174 SystemSchematic....................................................................................................................................................177 TheDisplay..............................................................................................................................................................177 TheMicrocontroller.................................................................................................................................................179 TheAnalogCircuitry...............................................................................................................................................180 JTAG........................................................................................................................................................................181 SummaryofSchematic............................................................................................................................................182 SystemDevelopment...............................................................................................................................................182 BreadboardConstruction—PoweredbythePC......................................................................................................185 TheDisplayBoard...................................................................................................................................................189 TheAnalogBoard....................................................................................................................................................190 TheApplicationProgram.........................................................................................................................................191 CreatingaProjectinIARWorkbench©..................................................................................................................192 CompilingtheProgram............................................................................................................................................193 LoadingtheProgram................................................................................................................................................194 Troubleshooting.......................................................................................................................................................194 TheStand-AloneBreadboard..................................................................................................................................194 ThePCBCircuit.......................................................................................................................................................195 Summary..................................................................................................................................................................197 Chapter10Quiz.......................................................................................................................................................197
AppendixA:TheMSP430InstructionSet......................................................................................... 200 AppendixB:StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers............................. 260 AppendixC:ApplicationProgramforUseinChapter10..................................................................... 273 AppendixD:ARefresher................................................................................................................. 290 Ohm’sLaw...............................................................................................................................................................290 Decibel—AQuantitytoDescribeGain...................................................................................................................291 PassiveDevices........................................................................................................................................................292 TheDiode—AOne-WayValveforCurrent.............................................................................................................294 ActiveDevices.........................................................................................................................................................294 FourCommonTypes................................................................................................................................................297
AbouttheAuthor........................................................................................................................... 299 Index............................................................................................................................................. 300
TEAM LRN
x
Foreword February2004 Theconceptofaprogrammablesystem-on-chip(SoC)startedin1972withtheadventoftheunassuming 4-bitTMS1000microcomputer—theperfectfitforapplicationssuchascalculatorsandmicrowaveovens thatrequiredadevicewitheverythingneededtoembedelectronicintelligence.Microcomputerschanged thewayengineersapproachedequipmentdesign;forthefirsttimetheycouldreuseprovenelectronics hardware,needingonlytocreatesoftwarespecifictotheapplication.Theresultofmicrocomputer-based designshasbeenareductioninbothsystemcostandtime-to-market. Morethanthirtyyearslatermanythingshavechanged,butmanythingsremainthesame.Theterm microcomputerhasbeenreplacedwithmicrocontrollerunit(MCU)—anamemoredescriptiveofatypicalapplication.Today’sMCU,justlikeyesterday’smicrocomputer,remainstheheartandsoulofmany systems.ButovertimetheMCUhasplacedmoreemphasisonprovidingahigherlevelofintegrationand controlprocessingandlessonsheercomputingpower.Theraceforembeddedcomputingpowerhasbeen wonbythededicateddigitalsignalprocessor(DSP),awidelyusedinventionofthe‘80sthatnowdominateshigh-volume,computing-intensiveembeddedapplicationssuchasthecellulartelephone.Butthe designengineer’smostusedtool,whenitcomestoimplementingcosteffectivesystemintegration,remains theMCU.TheMCUallowsjusttherightamountofintelligentcontrolforawidevarietyofapplications. TodaytherearehundredsofMCUsreadilyavailable,fromlow-end4-bitdeviceslikethosefoundina simplewristwatch,tohigh-end64-bitdevices.Buttheworkhorsesoftheindustryarestilltheversatile 8/16-bitarchitectures.Choicesareavailablewith8to100+pinsandprogrammemoryrangingfrom64KB.TheMCU’sadoptionofmixed-signalperipheralsisanareathathasgreatlyexpanded,recently enablingmanynewSoCsolutions.ItiscommontodaytofindMCUswith12-bitanalog-to-digitalanddigital-to-analogconverterscombinedwithamplifiersandpowermanagement,allonthesamechipinthesame device.Thisclassofdeviceoffersacompletesignal-chainonachipforapplicationsrangingfromenergy meterstopersonalmedicaldevices. ModernMCUscombinemixed-signalintegrationwithinstantlyprogrammableFlashmemoryandembeddedemulation.Inthehandsofasavvyengineer,auniqueMCUsolutioncanbedevelopedinjustdaysor weekscomparedtowhatusedtotakemonthsoryears.YoucanfindMCUseverywhereyoulookfromthe watchonyourwristtothecookingappliancesinyourhometothecaryoudrive.Anestimated20million MCUsshipeveryday,withgrowthforecastforatleastadecadetocome.Themarchofincreasingsilicon integrationwillcontinueofferinganevengreatervarietyofavailablesolutions—butitistheengineer’s creativitythatwillcontinuetosetapartparticularsystemsolutions. MarkE.Buccini DirectorofMarketing MSP430 TexasInstrumentsIncorporated TEAM LRN
xi
Preface Analogsystemdesignersmanytimesinthepastavoidedtheuseofelectronicsfortheirsystemfunctions becauseelectroniccircuitscouldnotprovidethedynamicrangeofthesignalwithoutseverenonlinearity,or becausethecircuitsdriftedorbecameunstablewithtemperature,orbecausethecomputationsusinganalog signalswerequiteinaccurate.Asaresult,thedesignshiftedtootherdisciplines,forexample,mechanical. Today,youngengineersrequestedbytheirsuperiorstodesignananalogcontrolsystem,haveanentirely newtechniqueavailabletothemtohelpthemdesignthesystemandovercomethe“old”problems.Thedesigntechniqueisthis:sensetheanalogsignalsandconvertthemtoelectricalsignals;conditionthesignals sotheyareinarangeofinputstoassureaccurateprocessing;converttheanalogsignalstodigital;makethe necessarycomputationsusingtheveryhigh-speedICdigitalprocessorsavailablewiththeirhighaccuracy; convertthedigitalsignalsbacktoanalogsignals;andoutputtheanalogsignalstoperformthetaskathand. AnalogandDigitalCircuitsforControlSystemApplications:UsingtheTIMSP430Microcontrollerexplains thefunctionsthatareinthesignalchain,andexplainshowtodesignelectroniccircuitstoperformthefunctions.Includedinthisbookisachapteronthedifferenttypesofsensorsandtheiroutputs.Thereisachapter onthedifferenttechniquesofconditioningthesensorsignals,especiallyamplifiersandopamps.Thereare techniquesandcircuitsforanalog-to-digitalanddigital-to-analogconversions,andanexplanationofwhata digitalprocessorisandhowitworks.Thereisachapterondatatransmissionsandoneonpowercontrol. Andtosolidifythelearningandapplications,thereisachapterthatexplainsassembly-languageprogramming,andalsoachapterwherethereaderactuallybuildsaworkingproject.Thesetwochaptersrequired choosingadigitalprocessor.TheTIMSP430microcontrollerwaschosenbecauseofitsdesign,and becauseitisreadilyavailable,itiswellsupportedwithdesignandapplicationsdocumentation,andithas relativelyinexpensiveevaluationtools. Thegoalofthebookistoprovideunderstandingandlearningofthenewdesigntechniqueavailableto analogsystemdesignersandthetoolsavailabletoprovidesystemsolutions.
TEAM LRN
xii
Acknowledgments MarkBuccini,ProductLineMarketingManagerfortheMSP430intheSemiconductorGroupforTexas InstrumentsIncorporatedandhisstaffdeservemuchcreditfortheprojectinChapter10,andforthe thoroughnessandaccuracyoftheMSP430information.SpecialthanksgotoNealFrager,anapplications expert,forwritingtheprogramfortheChapter10project,fordesigningthePCBbreadboard,arranging meetingsandforresearchingmanyinquiriesasthebookdeveloped.Othersthatdeservementionfortheir assistance:CorneliaHuellstrunk,ByronAlsbergwhohelpeddeveloptheinitialschematic,DaleWellborn, DanHarmon,RajenShah,ZackAlbus,ModupeAjibola,MikeMitchellforhisexcellentreviews,andNeal Brennerandforhelpingcleanupthelastdetails.Ahearty“ThankYou”toall!
TEAM LRN
xiii
What’sontheCD-ROM? ■ AfullysearchableeBookversionofthetextinAdobePDFformat.Itincludes:
Fulltextoftenchapters.
AppendixA—TheMSP430InstructionSet.
AppendixB—StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers.
AppendixC—ApplicationProgramforUseinChapter10.
AppendixD—ARefresher.
■ Auser’sguidetotheMSP430x1xxfamilyofmicrocontrollers. ■ LayoutwiringofPCBinterconnectionlayers.
TEAM LRN
xiv
C H APTER 1
SignalPathsfromAnalogtoDigital Introduction Designersofanalogelectroniccontrolsystemshavecontinuallyfacedthefollowingobstaclesinarrivingat asatisfactorydesign:
1. 2. 3. 4.
Instabilityanddriftduetotemperaturevariations. Dynamicrangeofsignalsandnonlinearitywhenpressingthelimitsoftherange. Inaccuraciesofcomputationwhenusinganalogquantities. Adequatesignalfrequencyrange.
Today’sdesigners,however,haveasignificantalternativeofferedtothembytheadvancesinintegrated circuittechnology,especiallylow-poweranaloganddigitalcircuits.Thealternativenewdesigntechnique foranalogsystemsistosensetheanalogsignal,convertittodigitalsignals,usethespeedandaccuracyof digitalcircuitstodothecomputations,andconverttheresultantdigitaloutputbacktoanalogsignals. Thenewdesigntechniquerequiresthattheelectronicsystemdesignerinterfacebetweentwodistinctdesign worlds.First,betweenanaloganddigitalsystems,andsecond,betweentheexternalhumanworldandthe internalelectronicsworld.Variousfunctionsarerequiredtomaketheinterface.First,fromthehumanworld totheelectronicsworldandbackagainand,inasimilarfashion,fromtheanalogsystemstodigitalsystems andbackagain.AnalogandDigitalCircuitsforControlSystemApplicationsidentifiestheelectronicfunctionsneeded,anddescribeshowelectroniccircuitsaredesignedandappliedtoimplementthefunctions, andgivesexamplesoftheuseofthefunctionsinsystems.
ARefresher Sincethebookdealswiththeelectronicfunctionsandcircuitsthatinterfaceorcoupleanalog-to-digital circuitsandsystems,orviceversa,ashortreviewisprovidedsoitisclearlyunderstoodwhatanalogmeans andwhatdigitalmeans.
Analog Analogquantitiesvarycontinuously,andanalogsystemsrepresenttheanaloginformationusingelectrical signalsthatvarysmoothlyandcontinuouslyoverarange.AgoodexampleofananalogsystemistherecordingthermometershowninFigure1-1.TheactualequipmentisshowninFigure1-1a.Aninkpenrecordsthe
a. Recordingthermometer
b. Plotofdailytemperaturevariations
PhotocourtesyofTaylorPrecisionProducts
CourtesyofMasterPublishing,Inc.
Figure1-1:Arecordingthermometerisanexampleofananalogsystem TEAM LRN
1
ChapterOne temperatureindegreesFahrenheit(ºF) andplotsitcontinuouslyagainsttimeon aspecialgraphpaperattachedtoadrum asthedrumrotates.Therecordofthe temperaturechangesisshowninFigure 1-1b.Notethatthetemperaturechanges smoothlyandcontinuously.Thereareno abruptstepsorbreaksinthedata. Anotherexampleistheautomobilefuel gaugesystemshowninFigure1-2.The electricalcircuitconsistsofapotentiometer,basicallyaresistorconnected acrossacarbatteryfromthepositive terminaltothenegativeterminal,which Figure1-2:Thesimplecircuitforanautomobilefuelgauge isgrounded.Theresistorhasavariable demonstrateshowanelectricalquantity,avoltage,isananalog tapthatisrotatedbyafloatridingonthe ofthefuellevel.CourtesyofMasterPublishing,Inc. surfaceoftheliquidinsidethegastank. Avoltmeterreadsthevoltagefromthevariabletaptothenegativesideofthebattery(ground).Thevoltmeterindicatestheinformationabouttheamountoffuelinthegastank.Itrepresentsthefuellevelinthetank. Thegreaterthefuellevelinthetankthegreaterthevoltagereadingonthevoltmeter.Thevoltageissaidto beananalogofthefuellevel.Ananalog ofthefuellevelissaidtobeacopyofthe Light bulb Key fuellevelinanotherform—itisanalogous Original was a Transmitter Receiver totheoriginalfuellevel.Thevoltage(fuel Separated by a clicker considerable distance or level)changessmoothlyandcontinuously buzzer sothesystemisananalogsystem,butis alsoananalogsystembecausethesystem a.Electricalcircuit outputvoltageisacopyoftheactualoutputparameter(fuellevel)inanotherform.
Digital Digitalquantitiesvaryindiscretelevels. Inmostcases,thediscretelevelsarejust twovalues—ONandOFF.Digitalsystems carryinformationusingcombinationsof ON-OFFelectricalsignalsthatareusually intheformofcodesthatrepresentthe information.Thetelegraphsystemisan exampleofadigitalsystem. ThesystemshowninFigure1-3isa simplifiedversionoftheoriginaltelegraph system,butitwilldemonstratetheprincipleandhelptodefineadigitalsystem. Theelectricalcircuit(Figure1-3a)isa batterywithaswitchinthelineatoneend andalightbulbattheother.Theperson
b.InternationalMorsecode
c.Digitalinformation Figure1-3:Thetelegraphisadigitalsystemthatsends informationaspatternsofswitchedsignals TEAM LRN
2
SignalPathsfromAnalogtoDigital attheswitchpositionisremotelylocatedfromthepersonatthelightbulb.Theinformationistransmitted fromthepersonattheswitchpositiontothepersonatthelightbulbbycodingtheinformationtobesent usingtheInternationalMorsetelegraphcode. Morsecodeusesshortpulses(dots)andlongpulses(dashes)ofcurrenttoformthecodeforlettersor numbersasshowninFigure1-3b.AsshowninFigure1-3c,combiningthecodesofdotsanddashesfor thelettersandnumbersintowordssendstheinformation.Thesenderkeepsthesameshortertimeinterval betweenlettersbutalongertimeintervalbetweenwords.Thisallowsthereceivertoidentifythatthecode sentisacharacterinawordortheendofaworditself.TheTisonedash(onelongcurrentpulse).TheHis fourshortdots(fourshortcurrentpulses).TheRisadot-dash-dot.AndthetwoEsareadoteach.Thetwo statesareONandOFF—currentornocurrent.Thepersonatthelightbulbpositionidentifiesthecodeby watchingtheglowofthelightbulb.Intheoriginaltelegraph,thispersonlistenedtoabuzzeror“sounder” toidentifythecode. Codedpatternsofchangesfromonestatetoanotherastimepassescarrytheinformation.Atanyinstantof timethesignaliseitheroneoftwolevels.Thevariationsinthesignalarealwaysbetweensetdiscretelevels, but,inaddition,averyimportantcomponentofdigitalsystemsisthetimingofsignals.Inmanycases,digitalsignals,eitheratdiscretelevels,orchangingbetweendiscretelevels,mustoccurpreciselyattheproper timeorthedigitalsystemwillnotwork.Timingismaintainedindigitalsystemsbycircuitscalledsystem clocks.Thisiswhatidentifiesadigitalsignalandtheinformationbeingprocessedinadigitalsystem. Binary Thetwolevels—ONandOFF—aremostcommonlyidentified as1(one)andzero(0)inmodernbinarydigitalsystems,and the1and0arecalledbinarydigitsorbitsforshort.Sincethe systemisbinary(twolevels),themaximumcodecombinations2ndependsonthenumberofbits,n,usedtorepresentthe information.Forexample,ifnumbersweretheonlyquantities represented,thenthecodeswouldlooklikeFigure1-4,when usinga4-bitcodetorepresent16quantities.Torepresentlarger quantitiesmorebitsareadded.Forexample,a16-bitcodecan represent65,536quantities.Thefirstbitattherightedgeofthe codeiscalledtheleastsignificantbit(LSB).Theleft-mostbit iscalledthemostsignificantbit(MSB). BinaryNumericalQuantities
Decimal (XX10) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Most significant bit (MSB) Binary (XXXX2) 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
Least significant bit (LSB)
Ournormalnumberingsystemisadecimalsystem.Figure1-5 Figure1-4:4-bitcodestorepresent Figure 1-4: 4-bit codes to represent 16 quantities. isasummaryshowingthecharacteristicsofadecimalandabi- 16quantities narynumberingsystem.NotethateachsysteminFigure1-5has specificdigitpositionswithspecificassignedvaluestoeachposition.Onlyeightdigitsareshownforeach systeminFigure1-5.Notethatineachsystem,theLSBiseither100inthedecimalsystemor20inthebinary system.Eachofthesehasavalueofonesinceanynumbertothezeropowerisequaltoone.Thefollowing exampleswillhelptosolidifythecharacteristicsofthetwosystemsandtheconversionbetweenthem.
TEAM LRN
3
ChapterOne
a. Decimal
b. Binary
Figure1-5:Decimalandbinarynumberingsystems CourtesyofMasterPublishing,Inc.
Example1.IdentifyingtheWeightedDigitPositionsofaDecimalNumber Separateouttheweighteddigitpositionsof6524. Solution: 6524=6×103+5×102+2×101+4×100 6524=6×1000+5×100+2X10+4×1 6524=6000+500+20+4
Canbeidentifiedas652410sincedecimalisa base10system.Normally10isomittedsince itisunderstood.
TEAM LRN
4
SignalPathsfromAnalogtoDigital
Example2.ConvertingaDecimalNumbertoaBinaryNumber Convert103toabinarynumber. Solution: 10310/2 = 51witharemainderof1 51/2= 25witharemainderof1 25/2= 12witharemainderof1 12/2= 6witharemainderof0 6/2= 3witharemainderof0 3/2= 1witharemainderof1 1/2= 0witharemainderof1(MSB) 10310 = 1100111
Example3.DeterminingtheDecimalValueofaBinaryNumber Whatdecimalvalueisthebinarynumber1010111? Solution: SolvethisthesameasExample1,butusethebinarydigitweightedpositionvalues. Sincethisisa7-bitnumber: AndsincetheMSBisa1,thenMSB= 1×26 = 64 and (nextdigit) 0×25 = 0 and (nextdigit) 1×24 = 16 and (nextdigit) 0×23 = 0 and (nextdigit) 1×22 = 4 and (nextdigit) 1×21 = 2 and (nextdigit,LSB) 1×20 = 1 87
0 1 0 1
1 1 0 0 1 1
0 0 0 0 1 1 1 1
0 0 1 1 1 1 1 1 1 1
D E F G H I J K L M N O
R S T U V W X Y Z [ \ ] ^ _
a b c d e f g h i j k l m n 0
q r s t u v w x y z { | } ~ DEL
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
0 sp ! " # $ % & ’ ( ) * +
Figure1-6:AmericanStandardCodefor Figure 1-6: American Standard Code for Information Interchange—ASCII code. InformationInterchange—ASCIIcode TEAM LRN
5
, . /
0 0
NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI
0 ............................................................................................................
1
0
1
0
C
Q
p
0
1 0
............................................................................................................
0
0
1
0
B
‘
1
0 1
............................................................................................................
1
1
1
0
A
P
1
0 1
............................................................................................................
0
1
1
0
@
1
1 1
............................................................................................................
1
0
0
0
1
1 1
............................................................................................................
0
0
0
7
0 0
............................................................................................................
1
1
0
6
............................................................................................................
0
1
5
1 0
......
1
0
4 0
0 .............
0
3 0
.................................................................................................................................
Quantitiesinnatureandinthe humanworldaretypicallyanalog.Thetemperature,pressure, humidityandwindvelocityinour
1
2 0
.................................................................................................................................
Accuracyvs.Speed— AnalogandDigital
1 0
.................................................................................................................................
Ifalphanumericcharactersareto berepresented,thenFigure1-6,the ASCIItabledefinesthecodesthat areused.Forexample,itisa7-bit code,andcapitalMisrepresented by1001101.Bit#1istheLSB andbit#7istheMSB.Asshown, upperandlowercasealphabet, numbers,symbols,andcommunicationcodesarerepresented.
Bit Position .................................................................................................................................
BinaryAlphanumericQuantities
DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US
ChapterOne environmentallchangesmoothlyandcontinuously,andinmanycases,slowly.Instrumentsthatmeasure analogquantitiesusuallyhaveslowresponseandlessthanhighaccuracy.Tomaintainanaccuracyof0.1% or1partin1000isdifficultwithananaloginstrument. Digitalquantities,ontheotherhand,canbemaintainedatveryhighaccuracyandmeasuredandmanipulatedatveryhighspeed.Theaccuracyofthedigitalsignalisindirectrelationshiptothenumberofbitsused torepresentthedigitalquantity.Forexample,using10bits,anaccuracyof1partin1024isassured.Using 12bitsgivesfourtimestheaccuracy(1partin4096),andusing16bitsgivesanaccuracyof0.0015%,or 1partin65,536.Andthisaccuracycanbemaintainedasdigitalquantitiesaremanipulatedandprocessed veryrapidly,millionsoftimesfasterthananalogsignals. Theadventoftheintegratedcircuithaspropelledtheuseofdigitalsystemsanddigitalprocessing.The smallspacerequiredtohandlealargenumberofbitsathighspeedandhighaccuracy,atareasonableprice, promotestheiruseforhigh-speedcalculations. Asaresult,ifanalogquantitiesarerequiredtobeprocessedandmanipulated,thenewdesigntechniqueis tofirstconverttheanalogquantitiestodigitalquantities,processthemindigitalform,reconverttheresult toanalogsignalsandoutputthemtotheirdestinationtoaccomplisharequiredtask.ThecompleteprocedureisindicatedinFigure1-7,andtheneedforanalogcircuits,digitalcircuitsandtheconversioncircuits betweenthemisimmediatelyapparent. Input could be a temperature, pressure, air flow, linear motion, rotation, etc.
Output could be a solenoid, heater, motor, cooler, etc.
ANALOG-TO-DIGITAL INPUT
Sensing the signal
Conditioning the signal
This signal will be an electrical signal — either a voltage or a current.
Converting the signal — Analog-to-Digital
DIGITAL-TO-ANALOG Digital System Processing
Converting the signal — Digital-to-Analog
Digital Signals
Conditioning the signal
Transducing the signal to useful output
OUTPUT
This signal will be an electrical signal — either a voltage or a current.
Figure1-7:Atypicalsystemdescribingthefunctionsin theanalog-to-digitalanddigital-to-analogchain
InterfaceElectronics ThesystemshowninFigure1-7showsthemajorfunctionsneededtocoupleanalogsignalstodigital systemsthatperformcalculations,manipulate,andprocessthedigitalsignalsandthenreturnthesignalsto analogform.Thischapterdealswiththeanalog-to-digitalportionofFigure1-7,andChapter2willdeal withthedigital-to-analogportion.
TheBasicFunctionsforAnalog-to-DigitalConversion SensingtheInputSignal Figure1-8separatesouttheanalog-to-digitalportionoftheFigure1-7chaintoexpandthebasicfunctions inthechain.Mostofnature’sinputssuchastemperature,pressure,humidity,windvelocity,speed,flow rate,linearmotionorpositionarenotinaformtoinputthemdirectlytoelectronicsystems.Theymustbe changedtoanelectricalquantity—avoltageoracurrent—inordertointerfacetoelectroniccircuits. TEAM LRN
6
SignalPathsfromAnalogtoDigital ADC Bits
Conditioning Output Signal Sensing
1.4 1.2 1.0 0.8 0.6 0.4 0.2
Volts
Millivolts
Output Signal
0
1
2
3
1.4 1.2 1.0 0.8 0.6 0.4 0.2
4
0
1
time
INPUT (Physical quantity) Example: Pressure
2
3
time
2
1
1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0
1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
Samples input analog voltage at set intervals of time
Conditioning
Sample-
Analog-to-
the
the
and-Hold
Digital
Signal
Signal
Circuits
Conversion Timing
In this case, amplifies signal amplitude by 1,000
3
4
Sensing
Takes a physical pressure and converts it to a millivolt signal
4
In this case, converts analog voltage into a 4-bit code Times the sampleand-hold and the A to D conversion
Sample
Value
Digital Code
0
0.8V
1000
1
1.1V
1011
2
0.9V
1001
3
0.65V
0110
4
1.05V
1010
5
1.25V
1100
Figure1-8:Thebasicfunctionsforanalog-to-digitalconversion
Thebasicfunctionofthefirstblockiscalledsensing.Thecomponentsthatsensephysicalquantitiesand outputelectricalsignalsarecalledsensors. ThesensorillustratedinFigure1-8measurespressure.Theoutputisinmillivoltsandisananalogofthe pressuresensed.Anexampleoutputplottedagainsttimeisshown.
ConditioningtheSignal Conditioningthesignalmeansthatsomecharacteristicofthesignalisbeingchanged.InFigure1-8,the blockisanamplifierthatincreasestheamplitudeofthesignalby1,000timessothattheoutputsignalis nowinvoltsratherthanmillivolts.Theamplificationislinearandtheoutputisanexactreproductionof theinput,justchangedinamplitude.Othersignalconditioningcircuitsmayreducethesignallevel,ordoa frequencyselection(filtering),orperformanimpedanceconversion.Amplificationisaverycommonsignal conditioningfunction.Someelectroniccircuitshandleonlysmall-signalsignals,whileothersareclassified aspoweramplifierstosupplytheenergyforoutputsthatrequirelotsofjoules(wattsarejoules/second).
Analog-to-DigitalConversion Inthebasicanalog-to-digitalconversionfunction,asshowninFigure1-7,theanalogsignalmustbe changedtoadigitalcodesoitcanberecognizedbyadigitalsystemthatprocessestheinformation.Since theanalogsignalischangingcontinuously,abasicsubfunctionisrequired.Itiscalledasample-and-hold function.Timingcircuits(clocks)setthesampleintervalandthefunctiontakesasampleoftheinputsignal andholdsontoit.Thesample-and-holdvalueisfedtotheanalog-to-digitalconverterthatgeneratesa TEAM LRN
7
ChapterOne digitalcodewhosevalueisequivalenttothesample-and-holdvalue.ThisisillustratedinFigure1-8asthe conditionedoutputsignalissampledatintervals0,1,2,3,and4andconvertedtothe4-bitcodesshown. Becausetheanalogsignalchangescontinually,theremaybeanerrorbetweenthetrueinputvoltageandthe voltagerecordedatthenextsample.
Example4.AtoDConversion Fortheanalogsignalshownintheplotofvoltageagainsttimeandthe4-bitcodesgivenfortheindicatedanalogvoltages,identifytheanalogvoltagevaluesatthesamplepointsandtheresultantdigital For the analog signal shown and the 4-bit code for analog voltages at various codesandfillinthefollowingtable. levels, identify the analog voltage values and the resultant digital codes.
1.6 1.4
Volts
1.2 1.0 0.8 0.6 0.4 0.2 0
1
Sample Interval
2
3
4
Signal Value
5
4
ADC Bits 3 2
1
1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0
6
4
Digital Code 3 2
1
0 Answer:
1
Signal Interval 0 1 2 3 4 5 6
2 3 4 5 6
Signal Value 0.3V 0.7V 1.5V 1.25V 0.95V 0.8V 1.1V
4 0 0 1 1 1 1 1
Digital Code 3 2 0 1 1 1 1 1 1 0 0 0 0 0 0 1
1 1 1 0 0 1 0 1
Obviously,onewouldliketoincreasethesamplingratetoreducethiserror.However,dependingonthe codeconversiontime,ifthesamplerategetstolarge,thereisnotenoughtimefortheconversiontobe completedandtheconversionfunctionfails.Thus,thereisacompromiseintheanalog-to-digitalconverter betweenthespeedoftheconversionprocessandthesamplingrate.Outputsignalaccuracyalsoplaysa part.Iftheoutputrequiresmorebitstobeabletorepresentthemagnitudeandtheaccuracyrequired,then higher-speedconversioncircuitsandmoreofthemaregoingtoberequired.Thus,designtime,cost,andall thedesignguidelinesenterin.Chapter5isacompletechapterontheconversiontechniquestoexplorethis functionindetail.AsshowninFigure1-8,thebitsofthedigitalcodearepresentedallatthesametime(in parallel)ateachsamplepoint.Otherconvertersmaypresentthecodesinaserialstring.Itdependsonthe conversiondesignandtheapplication.
Summary Thischapterreviewedanaloganddigitalsignalsandsystems,digitalcodes,thedecimalandbinarynumber systems,andthebasicfunctionsrequiredtoconvertanalogsignalstodigitalsignals.Thenextchapter willcompletethelookatthebasicfunctionsrequiredtoconvertdigitalsignalstoanalogsignals.Itwillbe importanttohavethesebasicfunctionsinmindastheelectroniccircuitsthatperformthesefunctionsare discussedintheupcomingchapters. TEAM LRN
8
SignalPathsfromAnalogtoDigital
Chapter1Quiz 1. 2. 3. 4. 5. 6. 7. 8.
Anewdesigntechniqueavailabletoanalogsystemdesignersis: a. Sensetheanalog,computeusinganalog,outputanalog. b. Sensetheanalog,converttodigital,computedigitally,converttoanalog,outputanalog. c. Sensetheanalog,converttodigital,computedigitally,outputdigitally. d. Sensedigitally,computedigitally,outputdigitally. Analogquantities: a. varysmoothly,thenchangeabruptlytonewvalues. b. consistofcodesofhigh-levelandlow-levelsignals. c. varysmoothlycontinuously. d. haveperiodsofhigh-levelandlow-levelsignals,thenchangetocontinuoussignals. Digitalsignals: a. varysmoothly,thenchangeabruptlytonewvalues. b. consistofcodesofhigh-levelandlow-levelsignals. c. varysmoothlycontinuously. d. haveperiodsofhigh-levelandlow-levelsignals,thenchangetocontinuoussignals. Electronicsystemdesignersmustinterfacebetween: a. thehumanworldandtheelectronicworld. b. thewholesaleworldandtheretailworld. c. theprivatebusinessworldandthegovernmentbusinessworld. d. theanalogworldandthedigitalworld. e. aanddabove. f. noneoftheabove. Inanalogelectronicsystems,analogquantitiesare: a. notanalogoustotheoriginalquantity. b. arenotacopyoftheoriginalquantityinanotherform. c. areoutputindigitalform. d. areacopyoftheanalogphysicalquantityinanotherform. Binarydigitalsystems: a. havetwodiscretelevels—1or0,highlevelorlowlevel. b. havethreeormorediscretelevels. c. havealevelthatvariescontinuouslywithtime. d. havebinarydigits,orbitsforshort. e. noneoftheabove. f. dandaabove. Decimalnumberingsystemshave: a. weighteddigitpositionsthatvaryrandomly. b. weighteddigitpositionsvaryingbypowersof10. c. weighteddigitpositionsvaryingbypowersof2. d. weighteddigitpositionsthatremainconstantatonevalue. Decimalnumberingsystemshave: a. weighteddigitpositionsthatvaryrandomly. b. weighteddigitpositionsvaryingbypowersof10. c. weighteddigitpositionsvaryingbypowersof2. d. weighteddigitpositionsthatremainconstantatonevalue. TEAM LRN
9
ChapterOne 9. Physicalquantitiesinthehumanworldaretypically: a. digitalandanalog. b. analoganddigital. c. digital. d. analog. 10.Digitalsystemsrepresentquantities: a. usingcombinationsofbinarydigitsincodes. b. usingmorebitsinitsbinarycodesasthequantityvalueincreases. c. usingmorebitsinitsbinarycodeasmoreaccuracyisrequired. d. usingbinarycodeswithjusttwolevels–1or0,highlevelorlowlevel. e. noneoftheabove. f. alloftheabove. 11.Analogquantities: a. usuallyhaveslowresponseandlessthanhighaccuracy. b. canbemaintainedatveryhighaccuracyatveryhighcomputingspeeds. c. areimpossibletocompute. d. eitherhaveslowresponseorveryhighaccuracy. 12.Digitalquantities: a. usuallyhaveslowresponseandlessthanhighaccuracy. b. canbemaintainedatveryhighaccuracyatveryhighcomputingspeeds. c. areimpossibletocompute. d. eitherhaveslowresponseorveryhighaccuracy. 13.ThebasicfunctionsforA-to-D(analog-to-digital)conversionsare: a. Sense,computedigitally,converttoanalog. b. computeasanalog,sense,converttodigital. c. converttodigital,sense,conditiontoanalog. d. sense,condition,converttodigital. 14.Sensing: a. computesanalogquantitiesinnature. b. separatesoutanalogquantitiesintodifferentcategories. c. changesquantitiesinnaturetoelectricalsignals. d. detectsanalogquantitiesbytheirmagnitude. 15.Conditioningsignals: a. meansthatthesignalsarebeingexercised. b. meansthatsomecharacteristicofthesignalisbeingchanged. c. meansthattheinputsignalmaybeincreasedordecreasedinamplitude,filteredorits impedancechanged. d. meansthatnothingisdonetotheinputsignal. e. bandcabove. f. aanddabove.
Answers:1.b,2.c,3.b,4.e,5.d,6.f,7.b,8.c,9.d,10.f,11.a,12.b,13.d,14.c,15.e. TEAM LRN
10
C H APTER 2
SignalPathsfromDigitaltoAnalog Introduction ReferbacktoFigure1-7.InChapter1,thebasicfunctionsusedfortheanalog-to-digitalportionofFigure 1-7werediscussed.Inthischapter,thebasicfunctionsofthedigital-to-analogportionwillbediscussed.
TheDigital-to-AnalogPortion Thedigital-to-analogportionisseparatedoutfromFigure1-7inFigure2-1.Afterthedigitalprocessing systemcompletesitsmanipulationofthesignal,theoutputdigitalcodesarecoupledtoadigital-to-analog converterthatchangesthedigitalcodesbacktoanequivalentanalogsignal.Fromtheoutputofthedigitalto-analogconverter,theanalogsignaliscoupledtoasignalconditionerthatchangesthecharacteristicsof thesignal.JustasinChapter1,astheapplicationdemands,theamplitudeofthesignalmaybeincreased withamplification,ordecreasedwithattenuation.Ormaybethepowerlevelofthesignalischanged,or theremaybeanimpedancetransformationtofitthetransducertowhichtheoutputsignalcouples. Theoutputofthesystemistosomereal-worldquantityexternaltotheelectronicsystem.Asshownin Figure2-1,theoutputmightbeameter,agauge,amotor,aleverarmtoproducemotion,aheater,orother similaroutput.
Changes the digital signal back to analog.
Digital System Processing
Digital-toAnalog Conversion
Changes characteristics of analog signal, such as amplitude, impedance or power level.
Conditioning the Signal
Adapts the signal to couple to a human world parameter.
Transducing the Signal to Useful Output
Figure2-1:Digital-to-analogportionofthesignalchain Figure 2-1: Digital-to-Analog portion of the signal chain.
Output may be a meter, a gauge, a motor, a lever, a heater, etc.
Digital-to-AnalogConversion Figure2-2illustratesthebasicdigital-to-analogfunction.Thedigitalprocessingsystemoutputsdigital informationintheformofdigitalcodes,andasshown,thedigitalcodesareusuallypresentedtotheinput ofthedigital-to-analogconverterinoneoftwoways. ParallelTransferofData Thefirstway—parallelbittransfer—meansthatallbitsofthedigitalcodeareoutputtedatthesametime. InFigure2-2,a4-bitcodeisusedasanexample.The4-bitcodesarecoupledoutinsequenceastheyare processedbythedigitalprocessor.Theyarriveatapresetdatainterval.InFigure2-2,the4-bitcode1000is outputtedfirst,followedby1011,1001,0110,1010,and1100,respectively.Thedigital-to-analogconverter TEAM LRN
11
ChapterTwo Data Interval all bits at same time Data flow Clock rate
OR
Serial 1100 1010 0110 1001 1011 1000
1.4 1.2 1.0 0.8 0.6 0.4 0.2
Data Interval
Volts
1 0 0 0
Filtered Output of DAC
Output of DAC
Volts
1 1 0 0
Parallel 1 0 1 1 0 1 0 0 1 1 0 1 0 0 1 1
0
1
2
3
4
1.4 1.2 1.0 0.8 0.6 0.4 0.2
0
5
1
time
Digital System
to-Analog
Processing
Conversion
3
4
5
time
F I L T E R
Digital-
2
Conditioning the Signal
For this example, data is in 4-bit codes.
Figure2-2:Thebasicfunctionofdigital-to-analogconversion
acceptsallbitsatthesametime.Itmusthavefourinputlines,thesamenumberofinputlinesasthe4-bit code.Inmostmoderndaydigital-to-analogconvertersthe4-bitcodesofFigure2-2arereally8-bit,ormost likely16-bitcodes.
Example1.ParallelOutput RefertoFigure2-2.Iftheoutputofthedigital-to-analogconverterwerean8-bitcode,whatwouldthe parallelbitcodesbethatarecoupledoutinsequence.Usethesamevalueofanalogsignal. Solution: Theanalogvaluesandthe4-bitcodesarelistedfirst.Sincean8-bitcodecanrepresent256segments, itscodesforthesameanalogvalueareshownwiththemaximumanalogsignalof1.5Vequalto255. Noticethatthe8-bitcodeistwogroupsof4-bitcodes,whicharealsoexpressedinhexadecimalform.
Analogvalue 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4 1.5
4-bitcode 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
Hex 0 1 2 3 4 5 6 7 8 9 A B C D E F
8-bitcode 0000 0000 0001 0001 0010 0010 0011 0011 0100 0100 0101 0101 0110 0110 0111 0111 1000 1000 1001 1001 1010 1010 1011 1011 1100 1100 1101 1101 1110 1110 1111 1111 TEAM LRN
12
Hex 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
SignalPathsfromDigitaltoAnalog SerialTransferofData Thesecondwayisserialtransferofdata.AsshowninFigure2-2,the4-bitcodesareoutputtedonebitata time,eachfollowingtheotherinsequence,andeachgroupoffourbitsfollowingeachotherinsequence.A clockratedeterminestherateatwhichthebitsaretransferred.Thedigital-to-analogconverteracceptsthe bitsinsequenceandreassemblesthemintotherespectivebitgroupsandthenactsonthem.
Example2.BitRate RefertoFigure2-2.Iftheclockthatoutputsthebitsinaserialoutputis1MHz,whataretheserialbit transferrateandtheparallelbittransferratefora4-bitandan8-bitcode? Solution: Clock(Hz) 1MHz
Serial 4-bit 8-bit 1MHz 1MHz
Parallel 4-bit 8-bit 4MHz 8MHz
TheConversion Thedigitalcodesreceivedbythedigital-to-analogconverterareequivalenttoaparticularanalogvalue.As showninFigure2-2,theinputcodeisconvertedtoandoutputtedastheequivalentanalogvalueandheld asthisvalueuntilthenextcodeequivalentvalueisoutputted.Thus,asshown,theoutputofthedigital-toanalogconverterisastair-stepoutputthatstaysconstantataparticularleveluntilthenextinputdigitalcode isreceived.Theoutputresemblesananalogsignalbutfurtherprocessingisrequiredinordertoarriveatthe finalanalogsignal.
Filtering Abasicfunctionrequiredafterthedigital-to-analogconversionisfiltering,orinmoregeneralterms, smoothing.AsshowninFigure2-2,suchfilteringproducesananalogsignalmoreequivalenttoananalogsignalthatchangessmoothlyandcontinuously.Thefilterphysicallymaybeinthedigital-to-analog converterorinthesignalconditionerthatfollowsitasshowninFigure2-2.Itwasplacedinthesignal conditionerinFigure2-2becauseitreallyisasignalconditioningfunction.
ConditioningtheSignal Thefunctionofconditioningthesignalforthedigital-to-analogportioncanbethesameasfortheanalogto-digitalportion.Amostcommonfunctionisamplificationofthesignal,butinlikefashion,thereisoften theneedtoattenuatethesignal;thatis,toreducetheamplitudeinsteadofincreasingtheamplitude.That isthefunctionchosenforFigure2-3.Theoutputsignalisattenuatedtoone-halfthevalueoftheinput.No othercharacteristicsofthesignalarechanged.Theshapeoftheamplitudevariationsofthewaveformwith timearenotchanged,sothesignalappearsthesameexceptitsamplitudevaluesarereduced.
TransducingtheSignal Theoutputoftheanalogsystemsdiscussedisahumanworldparameterexternaltotheelectronicsystem. Asmentionedpreviouslyseveraltimes,itmaybeatemperature,orapressure,orameasureofhumidity,or alinearmotion,orarotation.Thus,theelectronicoutputofthesignalconditioningfunction,inmanycases, mustbechangedinform.Itmaybeavoltageoracurrentoutoftheelectronicsystemandmustbechanged toanotherformofenergy. Adevicetochangeorconvertenergyfromoneformtoanotheriscalledatransducer.InFigure2-4,the transducerisameterthatshowstheamplitudeoftheoutputvoltageonavoltagescale.Thevoltageoutput fromtheelectronicsystemisconvertedtotherotationofaneedleinfrontofascalemarkedonthematerial TEAM LRN
13
ChapterTwo Signal Conditioning Output
1.4 1.2 1.0 0.8 0.6 0.4 0.2
Volts
Volts
Filtered Output of DAC
0
1
2 3 time
4
0.7 0.6 0.5 0.4 0.3 0.2 0.1
0
5
1
2 3 time
Conditioning the Signal Output
Input
4
5
Transducing the Signal to Useful Output
Output
In this case, the signal conditioning function is just a resistor divider that attenuates the signal to one-half its original value.
Output
Input
Figure2-3:Signalconditioningfunction
behindtheneedle.Thescaleiscalibratedsoparticularneedledeflectionsrepresentspecificvoltagevalues. Thus,anydeflectionoftheneedleasaresultoftheelectroniccircuitoutputcanbereadasaparticular voltagevalueatanyinstantoftime.Theelectronicsystemoutputhasbeenconvertedtoameterreading, andthemeterreadingcan becalibratedintothetype Transducing the signal to useful output — ofparameterthesystemis Interfaces to human measuring.Itcouldbea world parameter external to the fluidlevel,arateofflow,a electronic system. pressure,andsoforth. Similarchangesinenergy formoccurinothertypes oftransducers.Thevoltage orcurrentoutputfromthe electronicsystemgetsconvertedtoallformsofhuman worldparametersjustbythe choiceofthetransducer. ExamplesofTransducers
Volts
Conditioning the Signal
Transducer
0
0.5
1.0
The meter reading at any instant in time indicates the amplitude of the analog value.
In this case, the transducer is a meter. Figure 2-4: The Transducer Function. Figure2-4:Thetransducerfunction
Figure2-5showsexamples ofvarioustypesoftransducers.Figure2-5aisapictureofaspeakerenclosure.Insideiswhatiscalleda driver.Itisacommontransducerthattakeselectricalaudiosignalsandconvertsthemintosoundwaves. Thedriverisplacedinsideaboxtomakeitintoaverygoodsoundingspeakerenclosure.Manytimesthe driveronlyhandlesthelowandmid-frequencyaudiosignals,soanotherdriverforthehighfrequencies, calledatweeter,isinsertedintothespeakerenclosuretoallowthespeakertoreproduceabroaderrangeof audiofrequencies. TEAM LRN
14
SignalPathsfromDigitaltoAnalog Wound Coil Tweeter
Soft Core
Midrange Driver Low Freq. Driver Linear Motion
Electrical Signals Speaker (Driver)
ear Sound Output
a.Audiospeaker
Sound Inputs
Electrical Signals
Electrical Power
b.Microphone(sensor)
Rotating shaft that provides torque
c.Motor
Electrical Power
d.Solenoid
Figure2-5:Examplesoftransducers
Thereisacounterparttransducertothespeaker—amicrophone—thatisusedasaninputdeviceforsensing thesignal.ItisshowninFigure2-5b.Themicrophoneconvertssoundsignalsintoelectricalsignalssothey maybeinputtedintoanelectronicsystem. Figure2-5cshowsamotor.Normallyamotorisnotclassifiedasatransducer,butitis.Amotortakeselectricalenergyandconvertsitintorotationaltorque.Motorsareusedeverywhere,fromrunningmachinery,to trimminggrass,toprovidingtransportation. Figure2-5dshowsasolenoid.Asolenoidisatransducerthatconvertselectricalenergyintolinearmotion. Itconsistsofacoilofwirewithasoftironcoreinsideofit.Whencurrentispassedthroughthecoil,a magneticfieldisproducedthatpullsonthesoftironcoreanddrawsitinsidethecore.Themovementofthe corecanbeusedtomovealeverarm,tocloseadoor,tooperateashutter,andsoforth. Therearemanymoreexamplesoftransducersthatconvertelectricalenergyintoapressure,avalveforcontrollingfluidflow,atemperaturegauge,andsoforth.Asvariousapplicationsaredescribedinsubsequent chaptersmanywillusevarioustypesoftransducers.
Summary Thediscussioninthischaptercoveredthefunctionsnecessarytoconvertadigitalsignalintoananalog outputandthenintoahumanworldparameter.Itcompletedthesignalchainfromaninputanalogsignal,to adigitalconversion,tocomputationindigitalform,toaconversionbacktoanoutputanalogsignal,toan outputhumanworldparameter.Thenextchapterwillexaminethesensingfunctionindetail.
TEAM LRN
15
ChapterTwo
Chapter2Quiz 1. 2. 3. 4. 5. 6. 7. 8.
Adigital-to-analogconverter: a. outputsadigitalsignalinserialform. b. outputsananalogsignalinstair-stepform. c. outputsasmoothandcontinuousanalogsignal. d. outputsonedigitalcodeafteranother. Theoutputofthedigital-to-analogchainis: a. aserialdigitalcodestring. b. aparalleldigitalcodestream. c. areal-worldquantity. d. alwaysameterreading. Aninputtoadigital-to-analogconvertermaybe: a. aparalleltransferofdigitalcodes. b. ananalogsignalofsuitableamplitude. c. ananalogsignalofdiscretevalues. d. aserialtransferofdigitalcodes. e. aanddabove. f. bandcabove. Inaparalleltransferofbits: a. allbitsofadigitalcodearetransferredatthesametime. b. allbitsofadigitalcodearetransferredinasequentialstring. c. allbitsarefilteredintoananalogsignal. d. allbitsaresignalconditionedoneatatime. Inaserialtransferofbits: a. allbitsofadigitalcodearetransferredatthesametime. b. allbitsofadigitalcodearetransferredinasequentialstring. c. allbitsarefilteredintoananalogsignal. d. allbitsaresignalconditionedoneatatime. Theoutputofthedigital-to-analogconverteris: a. astair-stepoutputthatvariesuntilthenextinputdigitalcodeisreceived. b. astair-stepoutputthatchangesbetween1and0untilthenextdigitalcodeisreceived. c. astair-stepoutputthatstaysconstantataparticularleveluntilthenextdigitalcodeisreceived. d. astair-stepoutputthatchangesfrommaximumtominimumuntilthenextdigitalcodeis received. Thedigital-to-analogoutputmustbefilteredto: a. clarifythedigitalstepsintheoutput. b. keepthestair-stepdigitaloutput. c. maketheanalogoutputchangesmoothlyandcontinuously. d. maketheanalogoutputmorelikeadigitaloutput. Atransduceris: a. adevicetochangeorconvertenergyfromoneformtoanother. b. adevicethatmaintainstheanalogoutputindigitalsteps. c. adevicethatconvertsanalogsignalstodigitalsignals. d. adevicethatconvertsdigitalsignalstoanalogsignals. TEAM LRN
16
SignalPathsfromDigitaltoAnalog 9. Amotoris: a. atransducerthatchangesdigitalsignalsintoanalogsignals. b. atransducerthatchangesanalogsignalsintodigitalsignals. c. atransducerthatraisestheanalogvoltageoutputtoahighervoltage. d. atransducerthatchangeselectricalenergyintorotationaltorque. 10.Ameteris: a. atransducerthatconvertstheanalogoutputtotherotationofaneedleinfrontofascale. b. atransducerthatchangesanalogsignalsintodigitalsignals. c. atransducerthatraisestheanalogvoltageoutputtoahighervoltage. d. atransducerthatchangesdigitalsignalsintoanalogsignals.
Answers:1.b,2.c,3.e,4.a,5.b,6.c,7.c,8.a,9.d,10.a. TEAM LRN
17
C H APTER 3
Sensors Introduction InChapter1,Figure1-8showsthebasicfunctionsneededwhengoingfromananalogquantitytoadigital output.Thefirstoftheseissensingtheanalogquantity.Thedeviceusedinthefunctiontosensetheinput quantityandconvertittoanelectricalsignaliscalledasensor—themainsubjectofthischapter. Asensorisadevicethatdetectsandconvertsanaturalphysicalquantityintooutputsthathumanscan interpret.Examplesofoutputsaremeterreadings,lightoutputs,linearmotionsandtemperaturevariations. Chapter1indicatedthatamajorityofthesephysicalquantitiesareanalogquantities;i.e.,theyvarysmoothly andcontinuously.Sensors,intheirsimplestform,aredevicesthatcontainonlyasingleelementthatdoesthe necessarytransformation.Althoughtoday,moreandmorecomplicatedsensorsarebeingmanufactured;they covermorethanthebasicfunction,containingsensing,signalconditioningandconvertingallinonepackage. Inthischapter,inordertoclearlycommunicatethesensingfunction,themajorityofsensorswillbesingle elementsensorsthatoutputelectricalsignals—voltage,currentorresistance.Butalso,closelycoupledto sensorswithelectricaloutputs,sensorsareincludedthatusemagneticfieldsfortheiroperation.
TemperatureSensors OralTemperature Everyone,sometimeoranother,hashadtheneedtofindouttheirbodytemperatureorthebodytemperatureofamemberoftheirfamily.Anoralthermometer liketheoneshowninFigure3-1wasprobablyused.Liquidmercuryinsideofa glasstubeexpandsandpushesupthescaleonthetubeastemperatureincreases. Thescaleiscalibratedindegrees(ºF—Fahrenheitinthiscase)ofbodytemperature;therefore,theoralthermometerconvertsthephysicalquantityoftemperature intoascalevaluethathumanscanread.Theoralthermometerisatemperature sensorwithamechanicalscalereadout. 60
Indoor/OutdoorThermometer
40
80
20 Spring Anchor
100
0
-20
120
0
14
Bimetal strip spring expands as temperature increases and rotates pointer to indicate temperature
Figure 3-2: Rear view of Bimetal Strip Thermometer
-4
0
Figure3-2:Rear-viewofbimetalstrip thermometer
103 102 101 100 99 98 97 96
Normal body temperature (°F) 98.6
Figure3-1:Oral thermometer Figure 3-1: Oral Thermometer
AnothertemperaturesensorisshowninFigure3-2.Itisa bimetalstripthermometer.Twodissimilarmetalsarebonded togetherinastripthatisformedintoaspring.Themetalsexpanddifferentlywithtemperature;therefore,aforceisexerted betweenthemthatexpandsthespringandrotatestheneedleas thetemperatureincreases.Thethermometerscaleiscalibrated toknowntemperatures—boilingwaterandfreezingwater.These pointsestablishascaleandthedeviceismadeintoacommercial thermometerwithFahrenheit(ºF)and/orCelsius(Centigrade— ºC)scales.TheoneshowninFigure3-2isforºF.Theoutdoor thermometerisanothertypeoftemperaturesensorthatconverts thephysicalquantityoftemperatureintoameterreadingeasyfor humanstoseeandinterpret. TEAM LRN
18
Sensors
Thermocouples Athermocoupleisanothercommon temperaturesensor.Aplacetofindone isinanaturalgasfurnaceinahome similartothatshowninFigure3-3.It controlsthepilotlightfortheburnersin thefurnace.Thethermocoupleisaclosed tubesystemthatcontainsagas.Thegas expandsasitisheatedandexpandsa diaphragmattheendofthetubethatisin thegascontrolmodule.
Pilot light keeps thermocouple heated. It also lights burner gas when thermostat in house demands heat. Thermocouple gas expands due to pilot light heat.
Burner
Initial button is pressed to open Valve A to the pilot light and heat thermocouple. Gas supply
Valve A
Pilot Light Gas Control Module
Expanded diaphragm from expanded gas keeps Valve A open.
Household Furnace
Figure3-3:Aresidentialfurnacepilotlightcontrol
Thesystemworksasfollows:Abutton onthepilotlightgascontrolmoduleis pressedtoopenvalveAtoinitiallyallowgastoflowtolightthepilotlight.Theexpandeddiaphragmof thethermocouplesystemcontrolsvalveA;therefore,thebuttonforthepilotlightmustbehelduntilthe thermocoupleisheatedbythepilotlightsothatthegasexpandsandexpandsthediaphragm.Theexpanded diaphragmholdsvalveAopen;therefore,thepilotlightbuttoncanbereleasedbecausethepilotlightheatingthethermocouplekeepsthegasexpanded.Sincethepilotlightisburning,anydemandforheatfromthe thermostatwilllighttheburnersandthehouseisheateduntilthedemandbythethermostatismet.
V − Voltage in mV
Athermocouplethatputs Sealed joint outanelectricalsignal Hot Cold junction reference Metal #1 astemperaturevariesis junction showninFigure3-4.It isconstructedbyjoining Metal #2 twodissimilarmetals. V Whenthejunctionofthe twometalsisheated,it Temperature generatesavoltage,and Figure3-4:Abimetalthermocouple theresultisatemperature sensorthatgeneratesmillivoltsofelectricalsignaldirectly.Thetotalcircuitreallyincludesacold-junction reference,buttheapplicationusestheearthconnectionofthepackageasthecoldreferencejunction. Theremaybeaneedtoamplifytheoutputsignal fromthesensor,asshowninFigure3-5,because theoutputvoltageamplitudemustbeincreased toausefullevel.ThisisthesubjectofChapter4, signalconditioning.
Silicon-JunctionDiode
Sensor Physical Quantity
with Voltage Output
Output Voltage
Voltage Amplification
Output Voltage
Signal Conditioning
Figure3-5:Asensoroutputsignalmayhavetobe Figure 3-5: A sensor output signal may have to be increased to a useful level by amplifica
Anothersensorthatproducesavoltagedirectly increasedtoausefullevelbyamplification astemperaturevariesisasilicon-junctiondiode. ThecharacteristiccurvesforitsforwardandreversevoltagewithcurrentareshowninFigure3-6.Theforwardcurrentversusforwardvoltageforpositivevoltagesincreaseslittleuntiltheforwardvoltagereaches +0.7V,thenitincreasesrapidly.Heretheforwardresistanceisverysmall—intheorderof50Ωto80Ω.
Thereversecurrentfornegativereversevoltageis1,000timesandmoresmallerthantheforwardcurrent.It staysrelativelyflatwithreversevoltageuntilthemagnitudereachesthereversebreakdownvoltage.When TEAM LRN
19
10
VR — Reverse Voltage — V 30
25
20
15
10
5
9 8 7
50˚C
6
− ∆ VF Negative temperature ∆ T(ºC) coefficient
4 3 2 1
25˚C
10
50˚C
Reverse voltage breakdown
25˚C
5
0.5 0.7
1.0
1.5
VF — Forward Voltage — V
20
IR — Reverse Current — µA
thejunctionisreversedbiased belowthebreakdownvoltage, thereverseresistanceisvery large—intheorderofmegohms. Theforwardvoltageandreverse breakdownvoltagedecrease astemperatureisincreased; thus,thediodejunctionhasa negativetemperaturecoefficient.Theforwardvoltagehasa muchsmallervoltagevariation withtemperaturethandoesthe reversebreakdownvoltage.The reversecurrentbelowthebreakdownregioncanalsobeused foratemperaturesensor.Arule ofthumbforthereversecurrent isthatitdoublesforevery10ºC riseintemperature.Thereverse conditionsareusedfortemperaturesensors,butthemost commonistousetheforward voltagechange.
IF — Forward Current — mA
ChapterThree
30 40 50 60 70 80 90 100
Figure3-6:SiliconP-Njunctioncharacteristics Figure 3-6: Silicon P-N junction characteristics
Example1.TemperatureCoefficient UsingFigure3-6,calculatethetemperaturecoefficientoftheforwardvoltageofthediodeandshow thatitisnegative.TheforwardcurrentIF=5mA. Solution: TºC VF 25 1.02V 50 0.70V TempCoefficient=∆VF/∆T=−0.32V/25ºC=−0.0128V/ºC ∆=25 −0.32V
Thermistor 300
300Ω @ −50°C
V Resistance — kΩ
Athermistorisaresistorwhose valuevarieswithtemperature. Figure3-7ashowsthecharacteristicsofathermistorreadily availableatRadioShack.Two circuitsfortheuseofthermistorsareshowninFigure3-7. Figure3-7busesthethermistor inavoltagedividertoproduceavaryingvoltageoutput. Figure3-7cusesatransistor toamplifythecurrentchange providedbythethermistoras
40
RS#271-0110
V
Thermistor
30 20
10 kΩ
10
Ω 800 −50 −25
0
Ib
Vout
Vout
+25 +50 +75 +100 +125 Temp ºC
a.Characteristics
b.Voltageouput
c.Currentoutput
Figure3-7:Thermistortemperaturesensor TEAM LRN
20
Sensors temperaturechanges.Insomemicromachinedthermistors,theresistanceat25ºCisoftheorderof10kΩ. Oneofthedisadvantagesofusingathermistoristhatitscharacteristicswithtemperaturearenotlinear.As aresult,inordertoproducelinearoutputs,thenonlinearitymustbecompensatedfor.
AngularandLinearPosition PositionSensor—FuelLevel InChapter1,Figure1-2,anautomobilefuelgaugewasusedtodemonstrateananalogquantity.Thatsame examplewillbeused,asshowninFigure3-8a,todemonstratethesensingfunction.Thecompletesensor consistsofafloatthatridesonthesurfaceoffuelinafueltank,aleverarmconnectedtothefloatatone end,and,attheotherend,connectedtotheshaftofapotentiometer(variableresistor).Asthefuellevel changes,thefloatmovesandrotatesthevariablecontactonthepotentiometer.TheschematicofFigure 3-8bshowsthatthepotentiometerisconnectedacrosstheautomobilebatteryfrom+12Vtoground.The variablecontactonthepotentiometermovesinaproportionalmanner.Whenthecontactisattheendofthe potentiometerthatisconnectedtoground,theoutputvoltagewillbezerovoltsfromthevariablecontact toground.Attheotherend,theoneconnectedto+12V,therewillbe+12Vfromthevariablecontactto ground.Foranypositionofthevariablecontactinbetweentheendpoints,thevoltagefromthevariable contacttogroundwillbeproportionaltotheamountoftheshaftrotation. CalibratingitasshowninFigure3-8ccompletestheliquid-levelsensor.Atafulltank,thefloat,leverarm andpotentiometershaftrotationaredesignedsothatthevariablecontactisatthe+12Vendofthepotentiometer.Whenthetankisempty,thesamecombinationofelementsresultsinthevariablecontactatthe groundlevel(0V).Otherpositionsofthefloatresultinproportionaloutputvoltagesbetweenthevariable contactandground.AsFigure3-8cshows,athree-quarterfulltankgivesanoutputof9V,ahalf-fulltank willgiveanoutputof6V,andaone-quarterfulltankwillgiveanoutputof3V.Thus,addingavoltmeterto measurethevoltagefromthevariablecontacttoground,markedinliquidlevel,completestheautomotive fuelgauge.Sensorsthatconvertaphysicalquantityintoanelectricalvoltageoutputareverycommon.The outputvoltagecanbeanywherefrommicrovoltstotensofvolts.
Full 3/4 Full
Liquid Level 1/2 Full 1/4 Full
+
+ 12V
0V 3V 6V 9V 12V Voltage from variable contact to ground.
−
25% 50% 75% 100% Shaft rotation
a.Physicalcircuit
b.Schematicofcircuit
CourtesyofMasterPublishing,Inc.
Figure3-8:Positionsensor—fuellevelgauge TEAM LRN
21
c.Fuellevelconversionto voltage—calibration
ChapterThree
HallEffect—PositionSensor TheHalleffectisshowninFigure3-9a.E.H.Halldiscoveredit.Ifthereiscurrentinaconductoranda magneticfieldisappliedperpendiculartothedirectionofthecurrent,avoltagewillbegeneratedinthe conductorthathasadirectionperpendiculartoboththedirectionofthecurrentandthedirectionofthe magneticfield.Thispropertyisveryusefulinmakingsensors,especiallywhenasemiconductorchipis usedfortheconductor.NotonlycanthesemiconductorbeusedtogeneratetheHallvoltage,butadditional circuitrycanbebuiltintothesemiconductortoprocesstheHallvoltage.Asaresult,notonlyaretherelinear sensorsthatgenerateanoutputvoltagethatisproportionaltothemagnitudeofthemagneticfluxapplied, but,becausecircuitrycanbeaddedtothechip,therearesensorsthathaveswitchedlogic-leveloutputs,or latchedoutputs,oroutputswhoseleveldependsonthedifferencebetweentwoappliedmagneticfields.
nt
rre
AlinearHall-effectsensoris showninFigure3-9c.Itsoutput voltagevarieslinearlyasthe magneticfieldvaries.When thefieldiszero,thereisa quiescentvoltage=VOQ.Ifthe fieldis+β(northtosouth), thevoltageVOincreasesfrom VOQ;ifthefieldis–β(southto north),thevoltageVOdecreasesfromVOQ.Thesupply voltageistypically3.8Vto 24VforHall-effectdevices.
The Hall Effect: If a conductor has a current in it, and a magnetic field is applied perpendicular to the direction of the current, a voltage (the Hall voltage) is generated in a direction perpendicular to both the current and the magnetic field.
Cu
HallEffect—LinearPosition
Conductor tic ne ag ld M Fie
Figure3-9bshowsaHall-effect switchanditsoutputwhenusedas asensor.Whenthemagneticflux exceedsβONinmaxwells,theoutput transistoroftheswitchisON,and whenthefieldislessthanβOFF,the outputtransistorisOFF.Thereisa hysteresiscurveasshown.Whenthe outputtransistorisOFF,themagneticfieldmustbegreaterthanzeroby βONbeforethetransistorisON,but willstayONuntilthemagnetic fieldislessthanzerobyΒOFF. Thezeromagneticfieldpoint canbe“biased”uptoaparticular valuebyapplyingasteadyfield tomakeβO=ΒSTEADY-STATE.
Vol ta
ge
HallEffect—Switch
a.Halleffect
Output Voltage
VOH
Hall-Effect Sensor (switch)
BHYS
B Magnetic Field
−
+
VO VS
VOL
IS
BOFF
b.Hall-effectsensorswitch
0
BON
Magnetic Field — B maxwells
Output Voltage
Sensitivity: ∆V6
∆V6 ∆B
VOQ ∆B
Quiescent VO when B = 0 −
B Magnetic Field
VO
+ −B
0
c.LinearHall-effectsensor Figure3-9:Hall-effectsensors TEAM LRN
22
+B
Sensors
HallEffect—BrakePedalPosition AbrakepedalpositionsensorisshowninFigure3-10a.AHall-effectswitchingsensorisused.Steppingon thebrakemovesamagnetawayfromtheHall-effectsensoranditsoutputswitchestoalowvoltagelevel turningonthebrakelight.Whenthebrakeisreleased,themagneticfieldisagainstrongenoughtoswitch theoutputVOtoahighlevel,turningoffthebrakelight.
HallEffect—LinearPositionSensor InFigure3-10b,asthemagnetismovedoverthesensorthemagneticfieldproducesanoutputVOthatis proportionaltothestrengthofthefield.Thelinearoutputvoltagecanbeconvertedtoameterreadingthat indicatesthelinearpositionoftheassemblythatmovesthemagnet.AmplifyingVOcanincreasethesensitivityofthemeasurement.
HallEffect—AngularPositionSensor Aroundmagnet,halfNorthpoleandhalfSouthpole,isrotatedinfrontofalinearHall-effectsensoras showninFigure3-10c.AsthemagnetturnsthemagneticfieldvariesandproducesanoutputVOthatisproportionaltotheangularrotation.VOcanbeconvertedtoameterreadingcalibratedindegreesofrotation.
HallEffect—CurrentSensor CurrentinawireproducesamagneticfieldaroundthewireasshowninFigure3-10d.Ifthewireispassed throughasoft-ironyoke,thesoftironcollectsthemagneticfieldanddirectsittoalinearHall-effectsensor. Themagneticfieldvariesastheamplitudeofthecurrentvaries,whichproducesacorrespondingproportionalVOfromthelinearsensor,and,thus,asensorthatdetectstheamplitudeofthecurrent.Analternating currentisshowninFigure3-10d;therefore,thevoltageVOwillbeanalternatingvoltage.VOisdetectedin Figure3-10dusinganoscilloscope. Hall-Effect Sensor
+V
N S
Brake light
Magnet
Pivot
Linear movement
Brake off
N
Pivot Brake on
S
VO
Hall-Effect Linear Sensor
Brake pedal
a.Hall-effectpositionsensor(switch)
Meter reads position
b.Linearpositionsensor nt
rre
Cu
Soft iron yoke
tation ar ro g ul An N
10
0
Oscilloscope
Magnetic field
Linear Hall-Effect Sensor
A
t
0°
90° VCC
A S
1
VO
t
c.Angularpositionsensor
VO
Linear Hall-Effect Sensor
d.Currentsensor
Figure3-10:Hall-effectsensorapplications TEAM LRN
23
ChapterThree
Rotation VariableReluctanceSensor
A
Voltage Amplitude
Figure3-11ashowsthephysicalsetupofanelectromagneticsensorthatproducesacontinuousseriesof voltagepulsesasaresultoftime-varyingchangesofmagneticflux.ThemagneticfluxpathinFigure3-11a, calledthereluctancepath,isthroughtheironcoreofthewoundcoil,throughthecogontherotatingwheel andbacktothecoil.Whenthecogonthewheelisalignedwiththeironcore,theconcentrationoffluxisthe greatest.Asthecogmovestowardorawayfromthecoreofthecoil,theconcentrationoffluxismuchless. Anytimemagneticfluxchangesandcutsacrosswires,itgeneratesavoltageinthewires.Thevoltageproducesacurrentinthecircuitattachedtothewires.Asaresultoftherotationofthewheelandthecogpast thecoil,aseriesofvoltagepulses,asshowninFigure3-11b,isgenerated.Thetime,t,betweenthepulses variesasthespeedofthecoggedwheelvaries.Countingthepulsesoverasetperiodoftime,say,asecond, thespeed(velocity)ofthecoggedwheelcanbecalculated.Thevariationsofthespeedcanbecalculatedfor acceleration,andof Rotating course,thepresence cogged wheel These teeth could be ofpulsesmeansthe on shaft small magnets or have magnetized inserts wheelisinmotion. t Wound coil air gap Thedisadvantageof N turns iron core suchasensoristhat thereisnosignalat V zerospeed,andthe airgapbetweenthe time Magnetic mechanicalmoving flux lines partandthecoilcore a.Physicalsetup b.Voltageoutput mustbesmall,usually Figure3-11:Variablereluctancerotationsensor equaltoorlessthan 2−3centimeters.
Example2.RPM Avariablereluctancesensoroutputs120pulsesinatimeperiodof3seconds.Whatistherpm(revolutionsperminute)? Solution: rps(revolutionspersec)=120/3=40×60sec=2400rpm
MagnetoresistorSensor Amagnetoresistorsensorchangesitsresistanceproportionaltothemagneticfluxdensitytowhichitis exposed.Itismadeofanickel-iron(Permalloy)whichisdepositedasathinfilmontoasemiconductor surface.Itrequiresspecialfabricationofconductingstripsonhigh-carriermobilitysemiconductorssuchas Indium-AntimonideorIndiumArsenide.ThebasicprincipleisshowninFigure3-12a.ThethinfilmisdepositedinastrongmagneticfieldthatorientsthemagnitizationMinadirectionparalleltothelengthofthe resistor.AcurrentisthenmadetopassthroughthethinfilmatanangleθtotheMdirection.Iftheangleis zero,thethinfilmwillhavethehighestresistance.Atanangleθ,itwillhavealowerresistance.Whenan externalmagneticfieldisappliedperpendiculartoM,thenθchangesandtheresistancechanges.Thisisthe basicprinciplethatproducesaresistancechangewhenamagneticfieldisappliedandallowstheuseofthe thinfilmdeviceasasensor. TEAM LRN
24
Sensors Figure3-12bshowsthe changeinresistanceasthe angleθofthecurrentin relationshiptoMvaries. Oneoftheadvantagesof usingmagnetoresistoris thatothersemiconductor circuitscanbefabricated onandinthesamesemiconductorsubstrate.The resistorelementisusually placedinaWheatstone bridgecircuitinorderto makeamoresensitive measurement.
VCC θ
Magnetization M Shorting bars
Applied magnetic field
R2
Applied field
R3 I
a.Basicprinciple Out +
∆R R
Out −
M
Linear range R1
−90°
−45°
0° 45° θ Angle
90°
R4
Gnd
c.Physicalconstruction (Wheatstonebridge)
b.Changeofresistancewithθangle
Suchaphysicallayoutis Figure3-12:Magnetoresistorsensor showninFigure3-12c. Thereareshortingbarsdepositedoverthefilmtodirectthebiascurrentatanangleequalto45º.Thisisto putthequiescentpointinthecenterofthelinearregionofoperationoftheresponsecurveofFigure3-12b. WhenVCC=5V,thebridgesensitivitycanbeasmuchas15mVperOerstedofanappliedfield.
Pressure PiezoresistiveDiaphragm ThephysicalconstructionofapressuresensorisshowninFigure3-13a.Afluidorgasunderpressureis containedwithinatubetheendofwhichiscoveredwithathin,flexiblediaphragm.Asthepressureincreasesthediaphragmdeflects.Thedeflectionofthediaphragmcanbecalibratedtothepressureappliedto completethepressuresensorcharacteristics. Moderndaysemiconductortechnologyhasbeenappliedtothedesignandmanufacturingofpressuresensors.AdescriptivediagramisshowninFigure3-13b.Thethindiaphragmismicromachinedfromasilicon substrateonwhichahigh-resistivityepitaxiallayerhasbeendeposited.Thepositionofthediaphragmand itsthicknessonandinthesubstrateisdefinedusingtypicalsemiconductortechniques—formasilicondioxideonthesurface,coatitwithphotoresist,exposethephotoresistwithultravioletlightthroughamaskto definethediaphragmarea,andetchawaytheoxideandsilicontothecorrectdepthforthethindiaphragm. Theassemblyisthenpackagedtoallowpressuretodeflectthediaphragm. +V Silicon oxide
Thin flexible diaphragm Fluid or gas under pressure
Diaphragm under pressure
a.Sensorprinciple
Silicon etched away in this area Metal contact
RX
R3 VO
A Silicon wafer
Thin diaphragm deflect under pressure and changes resistance
High-resistivity epitaxial layer
b.Micromachinedsiliconresistor Figure3-13:Micromachinedpressuresensor TEAM LRN
25
R2
Rx
B R1
c.Wheatstonebridge
ChapterThree Usingintegratedcircuitmetallizationtechniques,thethindiaphragm,whichchangesresistanceasit deflects,isconnectedintoaWheatstonebridgecircuitasshowninFigure3-13c.Thisprovidesavery sensitive,temperaturecompensated,measuringcircuit.RXinthecircuitisthethindiaphragmresistanceexposedtopressure.R1,R2,andR3aresimilarlymicromachinedresistorsbuttheyarenotexposedtopressure. Astemperaturechangesalltheresistorschangeinlikefashionbecausetheyarelocatedveryclosetogether onthesmallsemiconductorsurfaceandhavethesametemperaturecoefficient.Asaresult,thesensoris temperaturecompensated.Andsincetheresistorsareveryclosetogetheronthesubstrate,andaremachined atthesametime,theyareveryuniforminvalue.
TheWheatstoneBridge HowdoestheWheatstonebridgeofFigure3-13cwork?Thesensingvoltage,VO,ismeasuredacrossthe bridgefrompointAtopointB.VO=0whenthebridgeisbalancedandisatitsmostsensitivemeasuring point.Thecircuitisanalyzedasfollows: ThevoltagefrompointAtogroundis:
VA=RX/(RX+R3)×V
ThevoltagefrompointBtogroundis:
VB=R1/(R1+R2)×V
Whenthebridgeisbalanced,VA=VBand
RX/(RX+R3)×V=R1/(R1+R2)×V
CancellingVonbothsidesoftheequation,
RX/(RX+R3)=R1/(R1+R2)
andtransposing,
RX(R1+R2)=R1(RX+R3)
RXR2=R1R3becauseR1RXcancelsoneachsideoftheequation.
or
Therefore,
RX=R3×R1/R2
Atbalance,theunknownresistanceisequaltoR3timestheratioofR1toR2. AsRXchanges,thebridgewillbecomeunbalancedandavoltage,VO,otherthanzeroresults.Thevoltage, VO,iscalibratedtothepressuretocompletethesensorcharacteristics.Pressuresfrom0–500psi(pounds persquareinch)canbemeasuredwithsuchapressuresensor.IfR1,R2,andR3allequal10kΩ,whenRX variesfrom10kΩto20kΩ,theoutputvoltagewillbeapproximatelyfrom10mVto20mVper1kΩof resistancechange.Oneoftheadvantagesofthesiliconsubstratesensorsisthatotherintegratedcircuitscan beinandonthesilicontoprovidesignalconditioningtothevoltageoutput,VO.
Example3.WheatstoneBridgeCharacteristicCurve IntheWheatstonebridgeofFigure3-13c,R1=R2=R3=10kΩandRXvarieswithpressurefrom 10kΩto15kΩ.Plotthechangeinvoltage,VO,againstthechangeinresistance,RX.MakeV=1V. Solution: VO=VA–VB=V(RX/(RX+R3)–R1/(R1+R2))=V(RX/(RX+10kΩ)–0.5) TEAM LRN
26
Sensors
RX 10k 11k 12k 13k 14k 15k
RX+10kΩ 20k 21k 22k 23k 24k 25k
RX/(RX+10kΩ) 0.5 0.524 0.545 0.5652 0.5833 0.600
VO 0 0.024 0.045 0.065 0.0833 0.100
PlotthesenumbersonanXandYaxiswithX=VandY=Ωandthecharacteristiccurveofoutput voltageagainstresistanceisobtained.Theoutputvoltagecanthenbecalibratedtopressuretogivea characteristiccurveofvoltageagainstpressure.
CapacitiveTouchDiaphragm
C − Capacitance — pf
ThecapacitivetouchdiaphragmsensorhasthesamemicromachinedstructureasthatshowninFigure3-13b. However,itssensorprinciple,showninFigure3-14a,isdifferent.Thethinmicromachineddiaphragm isdeflectedaspreviously,butnowthedeflecteddiaphragmisdesignedtotouchagainstadielectriclayer attachedtoametalelecThin diaphragm trode.Itformsacapacitor Thin diaphragm deflects under pressure no pressure andaspressureincreases, Metal electrode thecapacitancebetween Fluid or As the pressure increases, the gas under thediaphragmandthe deflection of the diaphragm pressure C metalelectrode,separated against the surface of the dielectric increases C bythedielectric,increases in a linear fashion. dielectric pressure — psi linearlywithpressure. Thecharacteristiccurveis a.Sensorprinciple b.Capacitance showninFigure3-14b. vs.pressure
BothofthemicromaFigure3-14:Capacitivetouchpressuresensor chinedsensorsfabricated fromsiliconhave–40º to+135ºoperation.Forveryextremeoperating Photon Of Light conditionsofaircraftandautomotiveapplicaReverse Biased tions,thereisacapacitivesensorwithaceramic diaphragmthatdeflectsintoacavity.Itscapacitanceagainincreaseswithpressure. Cathode
Diode Chip Anode
Hole
LightSensors LightBasics(Review) Abriefreviewispresentedoftheprinciplesof lightanddetectionbyphotodiodesandphototransistors.ForamorethoroughreviewrefertoBasic Electronics1,Chapter11.Figure3-15shows howareverse-biasedphotodiodehasitsreverse leakageincreasedbylightshiningonit.Photons, 1
Free Electron
Ammeter
Figure3-15:Areversed-biasedphotodiodelightsensor CourtesyofMasterPublishing,Inc.
BasicElectronics,G.McWhorter,A.J.Evans,©1994,MasterPublishing,Inc. TEAM LRN
27
ChapterThree whichareparticlesoflightthatarehigh-frequencyelectromagneticwaves,areabsorbedinthereverse-biased diodedepletionlayer.Theyproducefreeelectronsandholesthatincreasethereversecurrent.Themorephotons,thehighertheintensityoflight,themoreenergyisabsorbed,andthelargerthereversecurrent.Thus, thephotodiodeisalightsensorwithavariablecurrentoutput.
TheElectromagneticSpectrum Theelectromagneticspectrumisdividedintoradiowavesandlightwavesbyfrequency.Lightwavesare furtherdividedbyintoinfrared,visible,ultravioletandX-rays.Thespectrumiseitherexpressedinfrequencyorwavelength.Wavelengthisthedistancethatanelectromagneticwavetravelsthroughspacein onecycleofitsfrequency.Sincedistanceisvelocitymultipliedbytime,wavelengthcanbeexpressedasthe velocityofelectromagneticwavesmultipliedbythetimeofonecycleoffrequencyf.Sincetheaccepted speedoflightis186,000milespersecondor300,000,000meterspersecond,thisis:
or,
λ(inmeters)=300,000,000meters/sec×1/f(inseconds) λ(inmeters)=300/f(inMHz)
Ifvisiblelight(whitelight)ispassedthrougha White light is a mixture photons of different prism,asshowninFigure3-16,thevisiblelight of wavelengths. separatesintoitscolorcomponents.ThefrequenGlass Prism cyofvisiblelightisfrom400millionmegahertz Wavelength Of Reddest Light = 70 to750millionmegahertz.Thewavelengthisfrom Shorter wavelengths and Micrometers energy toward violet end 750nanometers(10−9)to400nanometers.Light of spectrum. sensorsextendintotheinfraredfrequencyrange belowvisiblelightandintotheultravioletlight frequencyrangeabovevisiblelight.Cadmium sulfidesensorsaremostsensitiveinthegreen lightregionofvisiblelight,whilesolarcellsand ULTRAVIOLET INFRARED RED YELLOW BLUE phototransistorsensorsaremostsensitiveinthe ORANGE GREEN PURPLE (VIOLET) infraredregion.
PhotoresistorSensor
Frequency (MHZ)400 x 106 λ (meters) 750 x 10−9
750 x 106 400 x 10−9
Asensorthatchangesresistanceaslightisshined Figure3-16:Visiblelight—itsfrequencyandwavelength onitismadefromCadmiumSulfide(CdS),a Figure 3-16: Visible Light—Its Frequency and Wavelength. CourtesyofMasterPublishing,Inc. semiconductorthatislightsensitive.ThecharCourtesy of Master Publishing, Inc. acteristicsofoneavailableatRadioShackare showninFigure3-17a.Inthedarkwithnolightshiningonititsresistanceisgreaterthan0.5MΩ.With onefootcandleoflightshiningonit,itsresistanceis1700Ω,andtheresistanceisreducedto100Ωwhen 100footcandlesoflightshineonit.CircuitapplicationsareshowninFigure3-17b.Itcanbeusedtochange resistancevalues,toprovideasensorwithavoltageoutput,orasasensorsupplyingcurrenttoaload.
Example4.PhotoresistorApplication UsethecircuitofFigure3-17bthatprovidesavoltageoutput.TheresistorR1=200Ω.Whatisthevoltage out,VO,whenthesupplyvoltageis10Vandthelightshiningonthesensoris15Ftcand100Ftc? Solution: Ftc RL R1 R1+RLVO
15 100
800Ω 200Ω 1000Ω 200/1000×10=2V 100Ω 200Ω 300Ω 200/300×10=6.67V TEAM LRN
28
Sensors 700K
V
600K 500K 2000
Dark
1700 Ω @1 FtC
Light
1600
RX
R RL
100 Ω @100 FtC
1200 800
RX =
RRL
RL
R+RL
R1
R Change
400
V
10 20 30 40 50 60 70 80 90 100110120
VO =
R1 R1+RL
V
Voltage output
Light-Footcandles (FtC)
I
a.Characteristics
SolarCell
b.Circuitapplications
Network of narrow metal strips on top forms anode contact.
Doped silicon
ANODE
Light shines between narrow anode contacts.
CATHODE
LIGHT
Magnified Section Of Wafer
Solarcellscanbeappliedincircuits,as showninFigure3-18c,byparallelingthe cellsforincreasedcurrentoutput,orby connectingthecellsinseriesforincreased voltageoutput.Individual2×4cmsolar cellsareavailableatRadioShackthatprovide300mAat0.55V,orthereareenclosed modulesthatprovideupto6Vat50mA.
Very thin p region at top surface is nearly transparent.
a.Physicalstructure
CourtesyofMasterPublishing,Inc.
Solar Cells
+V I
Current − mA
crystal wafer Thesolarcellisagainasemiconducwith cathode torPNjunctionthatislightsensitive. contact on bottom. ItismadeupofanN-typesubstrate,as showninFigure3-18a,withaverythin Pregionoverthetopsurface.Mostof thethinPsurfaceiscoveredwithnarrowstripsofmetalthatformtheanode ofthePNdiode.Awholenetworkof V thenarrowstripsareinterconnected onasiliconwafertoprovideincreased currentoutputatthe PN-junctionvoltage.The Cell backofthesiliconwafer 300 rating 0.5V @ 250 iscoatedwithmetalto 300mA 200 formthecathodeofthe 150 diode.Lightshiningon 100 thesurfaceofthesolar 50 cellgeneratesamaximum 0.1 0.2 0.3 0.4 0.5 0.6 voltageofabout0.55V. Voltage — Volts Underload,theaverage b.V-Icharacteristics voltageoutputisapproximately0.5V.Acommon characteristiccurveofvoltageplotted againstcurrentisshowninFigure3-18b.
A
Current Source
Figure3-17:Photoresistorsensor
Coils in parallel for increased I −V +V
Cells in series for increased V
2V
−V c. Circuit applications c.Circuitapplications Solar Panel on roof
Figure3-18:Solar celllightsensors
−V
−
+
+V
Diode prevents reverse current when battery voltage is higher than solar panel output V
d.TricklechargeforRVcoachbatteries TEAM LRN
29
ChapterThree AverycommonapplicationforRVmotorhomesisshowninFigure3-18d.Asolarpanelismountedonthe roofofamotorhomeandconnectedasshowntotricklechargethecoachbatterieswhentheRVisparked andunderlightload.Sunlightgeneratesthevoltagetosupplythetricklecurrent,whichhelpskeepthebatteriesfromdischarging.Manyunitsareavailablewithpowerratingsfrom2to50watts.
Phototransistors Figure3-19allowsaquickreviewoftheoperationofbipolartransistors,bothNPNandPNP.Recallthatfor anNPNgroundedemitter +5V stageshowninFigure I Collector I PNP 3-19atheemitteristied NPN I −0.7V current, controlled I Forward-biased C by base current, E emitter-base Collector E flows across reversetoground,andforactive junction just biased collector-base N I like diode P Base I B junction P operation,thebasevoltN I B Collector current, N B I P Forward-biased controlled by base ageisat+0.7Vabove base-emitter junction current, flows across C E Emitter I just like diode 0.7V Flipped reverse-biased I C groundandforwardI collector-base I junction C biasesthebase-emitter I =I +I B I = h I −5V I =I +I junction.Thecollector Transistor I =h I I voltageisatapositive { Current h = Normal I h = I Gain E Symbol voltageaboveground I (+5V)sothecollectora.NPNoperation b.PNPoperation basejunctionisreverse Figure3-19:Bipolartransistoroperation biased.Whenthereisa currentintothebase,IB,acrosstheforward-biasedbase-emitterjunction,ahighercollectorcurrent,IC,flows acrossthereverse-biasedcollector-basejunction.Thereisacurrentgainthroughthetransistorequaltothe collectorcurrentdividedbythebasecurrent,IC/IB.AsshowninFigure3-19,thecurrentgainishFE.EverythingisthesamefortheoperationofthePNPtransistorexceptthevoltagesareallnegativewiththeemitter tiedtoground.ThehFEisthesame V Light Intensity parameterasfortheNPN. C
E
C
E
B
B
B
B
E
C
E
C
E
B
C
C
FE B
FE
E
B
C
C B
C
FE B
FE
C B
C
Light intensity supplies base current
I Aphototransistor,atransistordesigned C tobeactivatedbylight,hasthesame basicoperationastheNPNandPNP V transistordescribedexceptithasno baseconnection.Itswidebasejunction E isleftexposedtolight.PhototransisI torsaremostsensitivetoinfraredlight. Thesymbolsandvoltagesareshownin a.Symbolandoperation Figure3-20a.Lightraysthatimpactthe V base-emitterjunctioneffectivelyproduce R basecurrentthatactivatesthephototranR C sistor.Throughtransistoractionalarger Q B collectorcurrentisproduced.Asshown bythecharacteristiccurvesofFigure Q R E 3-20b,morelightintensityproduces R morecollectorcurrent.
100%
C
80%
Resistive Load Line IC — mA
CE
60% 40% 20% 10%
E
VCE — Volts
b.Characteristiccurves
CC
L
bias
1
Q1 VO
2
Adjust
Relay Contacts
C
RAdjust
NO
B E
Q2
Relay Coil
E
Aphototransistorcanbecoupledtothe baseofadrivertransistor,asshownin Figure3-20c,inordertomakealinear
c.Linearorlogicaloutput
d.Relaydriver
Figure3-20:Phototransistorlightsensor TEAM LRN
30
NC C
Sensors driveroralogic-leveldriver.Ifalogic-leveldriverforON-OFFapplicationsisneeded,RBIASandREare eliminatedandtheRADJUSTusedtosetthedesiredsensitivity.RBIASandREsettheoperatingpointforQ2to obtainlinearoperationofthedriver.Figure3-20dshowsaphototransistorsensingthepresenceoflightto makealogic-leveldriverforarelay.Thepresenceoflightclosesthenormally-opencontacttothecenter terminaltoactivateaconnectedcircuit.
LEDLightSource
VariousLEDs,thematerialsusedtomakethem,and thecoloroftheirlightoutputareshowninFigure 3-21b.Thewavelengthinthiscaseisgiven inAngstroms(Å),whereanAngstromis10–10 meters.WhenLEDsareusedforlightsourcesfor phototransistors,theLEDwavelengthshouldbe matchedtothephototransistor.Forexample,Figure 3-22showstherelativeoutputfromaphototransistorusinganLEDasasource.AninfraredLEDwith awavelengthof898nanometers(8980Å)provides almostthreetimesasmuchoutputfromthephototransistorasanLEDwithanorangelightoutputof 650nanometers(6500Å).
Relative Response
+V Eventhoughalight-emittingdiode (LED)isnotasensor,itisavery V − 0.5 Material λ (Å) Color importantlightsourceforlightsenI= R R sors.AnLEDisaforward-biased I Indium Phosphide 9850 Infrared Gallium Arsenide 8980 Infrared LE D semiconductordiodeasshownin Gallium Arsenide Phosphide 6500 Orange Figure3-21a.LEDsaremadefrom 0.5V Gallium Phosphide 5650 Green Gallium Nitride 4000 Purple specialsemiconductormaterials otherthansilicon,butstillhave a.Schematic b.TypicalLEDs thesametypeofjunctioncharacteristics.Whenaratedamount Figure3-21:LEDlightsources ofcurrentispassedthroughthe forward-biaseddiodeitemitslight.Theamountofcurrent,I,throughthediodecanbeadjustedbychoosing thevalueofRwhenagivenvoltage,V,isused.Theforward-biasedvoltageacrossthediodeisapproximately0.5V,positive(+)ontheanodeandminus(−)onthecathode.
Typical Phototransistor
1.2
Infrared Light 8980
1.0
Visible Light
0.8
9850
6500
0.6 0.4
5650
0.2
4000
0
4000
5000
6000
7000
8000
9000
10000
11000
400
500
600
700
800
900
1000
1100
Figure3-22:LEDsaslightsourcesfora Fig. 3-22: LEDs as Light Sources phototransistorsensor for a Phototransistor Sensor.
Example5.WavelengthsofLEDs WhatisthewavelengthinmetersoftheLEDswhosewavelengthisgiveninAngstroms(Å)? Solution:(amillionthofameter(micron)equals10,000Å)
Å 9850 8980 6500 5650 4000
microns(divideby104) 0.9850 0.8980 0.6500 0.5650 0.4000
meters(divideby106) 0.9850×10–6 0.8980×10–6 0.6500×10–6 0.5650×10–6 0.4000×10–6 TEAM LRN
31
−Å − nanometers
nanometers(10–9) 985 898 650 565 400
ChapterThree
OtherSensors Theexpansionofthetypesofsensorsintomoderndayapplicationsisalmostmindboggling.Theadventof micromachiningusingsemiconductorsandsemiconductorfabricationtechniques,andtheabilitytoprovide asensoranditsassociatedcircuitrytosignalconditionthesignalallinonepackagehasexpandedthetypes andvarietyoftypesofsensors.Forexample,inautomotiveandaircraft,therearesensorsformassairflow, exhaustgasanditsproperties,engineknock,linearacceleration,justtonameafew.Infact,inthemodern automobilethereareover100sensorspercar2.Suchapplicationexplosionstestifytotheimportanceofthe sensorinelectroniccircuitry.
Summary Sensorsofalltypeshavebeendescribedinthischapter.Thedevicesthatconvertananalogphysicalquantityintoformsofenergythathumanscanunderstandandinterpret.Thesensorsinthischapterhadoutputs ofelectricalsignals—voltage,current,resistance,capacitance.Becausetheoutputsignalsaregoingtobe usedinotherelectroniccircuitrytoprovidesignalsthatcanbeconvertedtodigitalsignals,changesmustbe madetothesensoroutputsignalstoadaptthemtofurtheruse.Thatisthesubjectofthenextchapter—signalconditioning.
Chapter3Quiz 1. 2. 3. 4. 5.
2
Asensor: a. sensesanoutputquantityandinputsanelectricalsignal. b. sensesanoutputelectricalsignalandinputsaphysicalquantity. c. sensesaninputquantityandoutputsanelectricalsignal. d. sensesanoutputphysicalquantityandoutputsaphysicalquantity. Magneticfields: a. arenotimportanttotheoperationofsensors. b. playanimportantpartintheoperationofmanysensors. c. areharmfultotheoperationofsensors. d. aregeneratedbyallsensors. Athermocouple: a. sensestemperature. b. sensesvoltage. c. sensescurrent. d. sensesimpedance. SiliconP-Njunctions: a. usethereversevoltagevariationstosensecurrent. b. usebothforwardjunctioncurrentvariationsforsensingvoltage. c. don’tusethejunctionvoltagevariationstosensetemperature. d. usetheforwardvoltagevariationstosensetemperature. Athermistor: a. isasensorthatvariestemperatureasvoltageisapplied. b. isasensorwhoseresistancevarieswithtemperature.
SensorsystemefurdasAuto,Klaus-DieterLinsmeier,©1999,verlagemoderneindustrie. TEAM LRN
32
Sensors 6.
c. isasensorthathasalinearvariationwithtemperature. d. isasensorthatvariestemperatureascurrentisapplied. InaHall-effectsensor: a. avoltageisgeneratedthatisinthesamedirectionasacurrentandamagneticfield. b. avoltageisgeneratedthathasnorelationshiptothedirectionofanappliedcurrentor magneticfield. c. avoltageisgeneratedperpendiculartothedirectionofacurrentandperpendiculartothedirectionofamagneticfield. d. needsonlyamagneticfieldforitsoperation. 7. SemiconductorsareparticularlyusefulforHall-effectsensorsbecause: a. othercircuitsusefulforprocessingthesensorsignalcanbebuiltintothesemiconductor. b. theyareisolatedfromthesensor. c. theycanbemanufacturedinonestep. d. thereisnootherwaytomakethesensor. 8. Hall-effectsensorscanbeusedtosense: a. linearposition. b. angularposition. c. current. d. allofabove. 9. Avariablereluctancesensor: a. haszerooutputwhenthemagneticfieldisnotchanging. b. dependsontimevaryingchangesofamagneticfield. c. hashighoutputwhenthemagneticfieldisnotchanging. d. doesn’tneedamagneticfield. e. aandbabove. f. canddabove. 10.Amagnetoresistorsensor: a. changesitsresistanceproportionaltothemagneticfieldfluxdensitytowhichitisexposed. b. changesitsvoltageoutputasaresultofamagneticfield. c. changesitscurrentoutputasaresultofamagneticfield. d. doesn’trequireamagneticfield. 11.Micromachinedsensors: a. areprocessedwithmicromachines. b. aremachinedusingcomputer-controlledmachines. c. areprocessedusingsemiconductormanufacturingtechniques. d. don’tneedaccuratemachiningtechniques. 12.Micromachinedsensors: a. measurepressurebyapplyingamagneticfield. b. measurepressurebychangingresistance. c. measurepressurebyremovingamagneticfield. d. measurepressurebychangingcapacitance. e. aandcabove. f. banddabove. 13.Thephotodiode: a. isnotsensitivetoanylight. TEAM LRN
33
ChapterThree b. isalightsensorwhoseoutputdoesnotvarywithlightintensity. c. isalightsensorwithavariablecurrentoutput. d. isalightsensorwithavariablevoltageoutput. 14.Thelightspectrum: a. isbelow400megahertz. b. extendsfrominfraredonthelowendtoultravioletonthehighend. c. isabove1,000millionmegahertz. d. isvariable,notconstant. 15.Wavelength: a. isthedistancethatanelectromagneticwavetravelsthroughspaceinonecycleofitsfrequency. b. isnotadistancebutaspeed. c. isnotaspeedbutavelocity. d. isameasureoftime. 16.Asensorthatchangesresistancewhenlightisilluminatesitis: a. photocurrentsensor. b. photovoltagesensor. c. photoimpedancesensor. d. photoresistorsensor. 17.Solarcells: a. aresemiconductorPNjunctionsthataresensitivetolight. b. canbeconnectedinparalleltoincreasecurrentoutput. c. canbeconnectedinseriestoincreasevoltageoutput. d. aabove. e. allofabove. 18.Aphototransistor,alightsensitivetransistor: a. hasnormalbase,collector,emitterconnections. b. hasthebaseandcollectorconnectedtogether. c. hasnobaseconnection. d. hasthebaseandemitterconnectedtogether. 19.Phototransistors: a. aremostsensitivetoinfraredlight. b. aremostsensitivetoultravioletlight. c. aremostsensitiveto100MHzlight. d. aremostsensitiveto10MHzlight. 20.LEDs(lightemittingdiodes)whenusedaslightsources: a. maybeusedasrandomlightsourcesforphototransistors. b. shouldbematchedtotheirphototransistorsensor. c. arenotimportanttophototransistorsensorapplications. d. arenotreliablelightsources.
Answers:1.c,2.b,3.a,4.d,5.b,6.c,7.a,8.d,9.e,10.a,11.c,12.f,13.c,14.b,15.a,16.d,17.e,18.c,19.a, 20.b. TEAM LRN
34
C H APTER 4
SignalConditioning Introduction
C
C
T
O O R Signalconditioning,asthe S N N A D S D S E N nameimplies,meansmodifyI I I I D N S A Digital Digital G T G T ingthesignal,changingits D A OUT S IN D Processing N I Processing N I U C I C characteristics,adjustingitto A O A O C N L N L N E theneedsoftheapplication. I I G R N N Thismaymeananincrease S G G ordecreaseinthemagnitude b. Digital to Transducer. ofthevoltagesignal,oran a. Sensor to Digital. a.Sensortodigital b.Digitaltotransducer increase(ordecrease)inthe Figure 4-1: Signal Conditioning Function. Figure4-1:Signalconditioningfunction magnitudeofthecurrent signal,orachangeintheabilityofthesignaltoprovidepower.AsshowninFigure4-1,thesignalconditioningfunctionfitsintwoplacesinthechainfromanaloginputtoanalogoutput.First,itisinthechain fromsensortotheanalog-to-digitalconversion,second,itisinthechainfromthedigital-to-analogconversiontotransducer.Oneofthemostimportantelectroniccircuitstosatisfythesignalconditioningfunction istheamplifier.
Amplification Anelectroniccircuit calledanamplifieris usedwhenavoltage orcurrentsignalneeds tobeincreasedin amplitude.Anamplifier canbeasinglecircuit slope is withasingleactive equal to gm device(transistor),or itcanbeacombinationofcircuitswith manyactivedevices. a.SchematicsymbolsofMOSFETs b.Characteristiccurveoffield-effect RecallthatinChapter transistor 3,Figure3-19a,the Figure4-2:MOS(metal-oxidesemiconductor)field-effecttransistor bipolarNPNtransistor CourtesyofMasterPublishing,Inc. operationwasdiscussed,andinFigure3-19b,theoperationofabipolarPNPtransistorwasdiscussed.Therearealsovarious typesoffield-effecttransistorsasshowninFigure4-2a.ThesearecalledMOSFETs(metal-oxidesemiconductorfield-effecttransistors).ThereareN-channelandP-channeldevicesthatoperateinthedepletion modeortheenhancementmode.Thecharacteristiccurveofafield-effecttransistor(FET)isshownin Figure4-2b.Avoltagefromgatetosourcecontrolscurrentfromsourcetodrain.Recallthatforthebipolar transistorsofFigure3-19,acurrentintothebase-emitterjunctioncontrolsthecollector-to-emittercurrent, TEAM LRN
35
ChapterFour whileforfield-effecttransistors,avoltagefromgatetosourcecontrolsthecurrentfromdraintosource. Tounderstandtheoperationofanamplifierandhowitmightbeused,anamplifierwillbedesigned,and itscharacteristicsexamined,usingasingleNPNbipolartransistorinacommon-emittercircuit.Commonemittermeanstheinputsignalisappliedbetweenbaseandemitter,andtheoutputsignalistakenbetween collectorandemitter.Theemitterisacommonpointbetweenthetwo.
BipolarNPNAmplifier
NPN Common-Emitter
tim
e
Collector Current—IC in mA
Input signal varies base Characteristic Curves Thedesignbeginsbychooscurrent from no-signal of 0.06 D C Load Line ingadeviceandlookingat mA to maximum of 0.08mA 14 and minimum of 0.04mA 12 itscharacteristicsshownin I = 0.1 mA 10 Figure4-3a.Theamplifieris I = 0.08 mA 8 goingtobea“small-signal” I = 0.06 mA 6 I = 0.04 mA linearamplifier.“SmallA 4 h = 6mA = 100 I = 0.02 mA 0.06mA signal”meansthatthe 8mA 2 Biased Operating Point A operatingpointwillbesetso 6mA 2 4 6 8 10 12 14 16 18 20 thatamplifiedoutputsignals B I willbeexactlythesame Collector-to-Emitter Voltage-V in Volts 4mA time astheinput,withminimal Collector current a.Characteristiccurves varies from no-signal distortion,butincreasedin of 6 mA to maximum of 8 mA and minimum V amplitude.“Small-signal” of 4 mA meansthattheinputsignal I R b.Outputsignal amplitudeonlydeviatesthe I V signalasmallportionaway fromthesteady-stateoperatingpoint.Asaresultthe amplificationpropertiesdo c.Measuringcircuit notlosetheirlinearqualities. Figure4-3: Point“A”issteady-stateoperatingpointsetbybias Theoperatingpoint—thenoCourtesyofMasterPublishing,Inc. signalsteady-stateoperating pointaroundwhichthesmall-signalacsignalsvary—ischosenbysomesimpleguidelines1. b b b b
FE
b
C
CE
c
b
CE
1. Theoperatingpointshouldbewithinthelinearportionofthecharacteristiccurves.
2. VCEshouldbeapproximately0.5VCC.
3. Emitter-to-groundvoltageshouldbe10%to15%ofVCC.
4. Base-to-groundvoltagewillbeapproximately0.7Vgreaterthantheemitter-to-groundvoltage.
Theamplifierisgoingtobeusedinautomotiveapplicationssothesupplyvoltage,VCC,willbeequalto +12V.TheoperatingpointisgoingtobesetatpointA,thebiasedoperatingpointshownonthecharacteristiccurvesofFigure4-3a.Whenthereisnosignal,pointAsaysthatthecollectorcurrentwillbe6mAand theVCE(voltagefromcollectortoemitter)willbe6V.
CharacteristicCurves LookatthecharacteristiccurvesofFigure4-3a.Whatdotheymean?Theyweretakenusingthemeasuring circuitofFigure4-3c.Inthiscircuit,thebasecurrent,IB,canbesettodifferentvalues.ThevoltageVCEcan bevaried,andthecollectorcurrent,IC,canbemeasured.IBissetto0.02mA(20microamperes)andVCEis 1
BasicCommunicationsElectronics,J.W.Hudson,G.Luecke,©1999,MasterPublishing,Inc.,Lincolnwood,IL. TEAM LRN
36
SignalConditioning variedfrom0to20V.Theheavy-linecharacteristiccurvemarkedIB=0.02mAistracedasICismeasured duringthevariationofVCE.AsIBisincreasedin0.02mAstepsandVCEisvaried,theothercharacteristic curveswillbeplotted. Thetransistorwilloperateacrossthesecharacteristiccurvesasdrivenbyasignalthatvariesitsbasecurrent andasregulatedbythevalueofVCE.Attheoperatingpointchosen(A),IC=6mAandIB=0.06mA,thus, asshowninFigure4-3b,thesteady-statecommon-emittercurrentgain(hFE)equals100atthispoint.Small IBchangesproduceICchangesthatare100timesgreater.Thecurrentgain,hFE,iscalledalarge-signalor DCcurrentgain.ThereisanACcurrentgain,hfe,thatisusedforsmall-signalACcircuitanalysis.Itmay varyfromthehFEvaluebecausethevariationofIBisinverysmallincrements.
Biasing
VCC = +12V
TheActualDesign
IC
I1
C
B
I2 IB
E
Input
R2
Output
E
IE
RE
VE
Figure 4-4: NPN Common-Emitter Small Figure4-4:NPNcommonSignal Amplifier.
Herearethedesignparametersthathavebeenset:
RL
R1
VB
TheoperatingpointAissetatitsoperatingcharacteristicsbybiasing thecircuit.Thereareanumberofbiasingcircuits:fixed-currentIBbias, voltage-dividerbias,collector-feedbackbias.Thisdesignwillusevoltagedividerbias.ThecircuitlooksliketheoneinFigure4-4.TheresistorRE isplacedinthecircuittoprovidenegativefeedback.Thisfeedbackandits effectoncircuitperformancewillbediscussedwhenopampsandoscillatorsarediscussed.Fornow,thepresenceofREinthecircuitgivesthe circuitmorestabilityagainstchangesintemperatureorparametervalues.
emittersmallsignalamplifier
VCC=12V IC=6mA hFE=TheNPNtransistorchosenhasaspecifiedminimumof50;itsactualhFEis100. VBE=0.7Vforasilicontransistor VE=1.0V(about10%ofVCC) VCE=6V
1. ThefirststepistosolveforRL:
L
SinceVCE=6V, VCC–ICRL=VCE 12–(6mA×RL)=6V therefore, 12–6=6mA×RL and RL=6V/6mA=6V/6×10–3 RL=1×103=1000Ω=1kΩ 2. ThenextstepistosolveforRE: Sinceinanytransistorwithreasonablegain,IBisasmallfractionofIC,andsinceIE=IC+IB,theapproximationthatIEisequaltoICisreasonablyaccurate. Therefore, VE=REIC Therefore, RE=VE/IC or RE=1V/6mA=1V/6×10–3=0.166×103=166Ω TEAM LRN
37
ChapterFour Resistorsaremanufacturedinstandardvaluesof150Ωor180Ω.ForthisdesignRE=150Ω,andthe actualVE=0.9Vthatis:(6×10–3×0.15×10+3=0.9V). 3. ThenextstepistosolveforR2: Oneoftherulesforvoltage-dividerbiasisthatthecurrent,I2,throughthedividershouldbeatleast10 timesthemaximumbasecurrent.Themaximumbasecurrent,IBmaxis:
IBmax=IC/hFE(min)=6mA/50=0.12mA
Thus,I2=1.2mAandthevalueorR2canbecalculatedsince:
VR2=VBE+VE=0.7V+0.9V=1.6V
R2=VR2/I2=1.6V/1.2mA=1.33×103=1330Ω
and
Astandardvalueis1300Ω,soR2=1.3kΩ 4. ThenextstepistosolveforR1: R1inthevoltagedividerbiascircuitwillhavethefollowingcurrent:
I1=I2+IBmax=1.2mA+0.12mA=1.32mA
SinceVR2=1.6V,thevoltageacrossR1is:
VR1=12V–VR2=12–1.6=10.4V
Therefore,
R1=VR1/I1=10.4V/1.32mA=7.88×103=7880Ω
8,200Ωisastandardvalue,soR1=8.2kΩ Thedesignedamplifiercircuitusinga2N2222AtransistorisshowninFigure4-5.Itsoperatingpointsare onthe“loadline”showninFigure4-3a. 5. Thenextstepistocalculatethevoltagegain. Thevoltagegain2ofathecommon-emitteramplifiercircuitshowninFigure4-5is:
AV=(RL×IE)/0.026
where:RL=totalloadresistance(RLinparallelwithanyloadacrossRL)
IE=DCemittercurrentinmA.
IE=IC(approximately)
Substitutingintheequation:
AV=(1×103×6×10–3)/2.6×10–2=(6×102)/2.6=2.3×102=230
ThevoltagegainindBis:
DB=20log10AV=20log10230=20×2.76=47.2dB
Thevoltagegainis230or47.2dB.
2
Ibid. TEAM LRN
38
SignalConditioning
AmplifierFrequencyResponse
VCC = +12V
Notonlymustanamplifieramplifythevoltageorcurrentchanges R 1K R 8.2K ofaninputsignal,butitmustbeabletoaccuratelyreproduce C thesesignalsasthesignalfrequencychanges.Thecapabilityofan C B 2N2222A amplifiertohandlethesignaloverdifferentfrequenciesiscalled Input E itsfrequencyresponse.Anexampleofthefrequencyresponseof R 1.3K acommon-emitteramplifiersimilartotheoneinFigure4-5is R 150Ω C = 200µF showninFigure4-6.Itisagraphofanamplifier’sgain,AV,plotted againstfrequencywiththeinputsignalamplitudeheldconstant 4-5: 2N2222A Common-Emitter Small-Signal asthesignalfrequencyisvaried.Withtheinputsignalamplitude Figure Figure4-5:2N2222Acommon-emitter Amplifier. small-signalamplifier constant,theoutputsignalshouldremainconstantifthegain,AV, remainsconstant.Thegaindoesremainconstantinthemidbandas showninFigure4-6.However,forfrequenciesgreaterthanfH,thesocalledhigh-frequencycornerfrequency,thegainreducesasthesignalfrequencyincreases.Thisisduetocircuitanddevicecapacitancethatisin parallelwithRL.AVisreducedby3dBfromitsmid-bandvalueatfrequencyfH.The3dBpointisalsothe frequencyatwhichAVhasreducedto0.707ofitsmidbandvalue.FortheamplifierinFigure4-6,fHis about5to7MHz. 1
L
IN
2
Gain A extends WhentheamplifierisaDCampli- to mid-band zero for dc amplifier fier,themidbandvalueofAVwill extenddowntozerofrequency; 3 dB however,iftheamplifieronlyamplifiesACsignals,AVwillreduceasthe Fall off A of gain signalfrequencyisloweredbelow due to coupling fL,thelow-frequencycorner.Like capacitor C f f fH,fListhefrequencywhereAVis –3dB(or0.707)ofitsmidband Frequency value.Thisreductioningainisdue V A = 20 log tothecouplingcapacitorsandcaV pacitorsacrosstheemitterresistors usedinACamplifiers.ForFigure Figure4-6:Common-emitteramplifier 4-6,fLisabout30to40Hz. frequencyresponse
E
E
55dB
V
Mid-band gain, AV
AV in db
50dB 45dB 40dB 35dB
V
30dB
0.707 AV Fall off of gain due to parallel capacitance across RL to ground
25dB
IN
20dB 1Hz
L
H
10Hz 100Hz 1.0kHz 10kHz 100kHz 1.0MHz 10MHz 100MHz
V
(db)
10
fL — The low-frequency corner frequency where the gain is 3 dB less than AV at mid-band.
O
IN
fH — The high-frequency corner frequency where the gain is 3 dB less than AV at mid-band.
Example1.CornerFrequencies Showthatthe–3dBpointonafrequencyresponsecurvewithamid-bandgainof40dBisthesame pointwherethegainis0.707ofthemid-bandgain. Solution: Sincethemid-bandgainindBisAV=20log10VO/VIN,then 40 = 20log10VO/VIN 2 = log10VO/VIN 102 = VO/VIN 100= VO/VIN,themid-bandgainequals100 Ifthe–3dBpointis0.707AV,thenthepointisatAV=70.7 Therefore, AV = 20log1070.7 AV = 20×1.85 AV = 37dB 37dBis–3dBdownfromthemid-bandgainof40dB. TEAM LRN
39
ChapterFour Foramplifierapplications,itisveryimportanttoknowthefrequencyrangeoftheinputsignalsthatareto behandledandtoexaminethemid-bandfrequencyrangefromfLtofHsothattheproperamplifiercanbe usedforanapplication.
Coupling DCCoupling Whenonecircuit,suchastheoneinFigure4-5,doesnotprovideenoughgain,circuitscanbecascaded— coupledtogether—toprovidemoregain.ThemeansofcouplingareshowninFigure4-7.Figure4-7a showsaDCamplifierusingtwoamplifierstages.Theoverallgainisequaltothefirststagegaintimesthe secondstagegain.ThatisoneadvantageofexpressingtheamplifiergainindB.ThedBvaluesofgainof eachstagecanbeaddedtogetthetotalgainindB.Theeffectonfrequencyresponseisalsoshown.With DCcouplingtheamplifierhasconstantgaindowntozerofrequency.Specialcaremustbetakeninthe designbecausetheDCvoltagescouplefromstagetostagesotheproperoperatingvoltagesonthebase, collectorandemittermustbeincorporatedinthedesign.
ACCoupling Figure4-7bisACcoupling.Acapacitor,CCisusedtocouplethesignalfromthefirststagetothesecond stage.Therealsoisacapacitor,CE,thatisusedtobypasstheemitterresistorofsecondstage.Thecoupling capacitorpreventstheDC voltagesofstage1tocouple throughtostage2,asthey dointheDCcaseofFigure 4-7a.ACcouplingallows theuseofidenticalstages, makesthedesigneasier,and evenprovideshigherAC gainbecausetheeffectof thenegativefeedbackofRE a.DCcoupling b.ACcouplingwithC iseliminatedatfrequencies abovefL.BelowfL,usingRE andCCcouplingcausesa reductioningain. Figure4-7cshowshow inductancecanbeusedto reducethehigh-frequency responsebecauseofthe increaseininductivereactance,andyetstillmaintain responseatthelowenddown tozerofrequency.Figure 4-7dshowstransformercoupling.Transformercoupling providesDCisolation,but needstheACtimevarying signalforitsoperation.The frequencyresponseislikea capacitor-coupledamplifier.
c.ACcouplingwithL (alsoDCcoupling)
Figure4-7:Typesofcoupling betweenamplifierstages CourtesyofMasterPublishing,Inc. TEAM LRN
40
d.Transformercoupling
e.Opticalcoupling
SignalConditioning
CouplingUsingLight Figure4-7eshowscouplingusinglight.Thereiscompleteisolationbetweenstage1andstage2usinglight coupling.ThecaseshownusesatransistortomodulatethecurrentthroughtheLED,whoselightemission isdetectedbyaphototransistor.Thelightmediacanveryeasilybeafiber-opticcable. Whenchoosinganamplifierforanapplication,examinethetransistorcharacteristiccurves,knowthetype frequencyresponserequiredandwhetheroperationisrequireddowntozerofrequency,anddetermineif morethansmall-signaloperationisneeded.
Example2.CascadedGain Showthananamplifierwiththreestageseachwithagainof20dBperstagehasanoverallgainof1000. Solution: Againof20dBis 20dB=20log10AV 1=log10AV AV=10 Threestageshaveoverallgainof10×10×10=1000.ItisinterestingtonotethatthedBadditionof 20+20+20=60dBfortheoverallgain.Therefore, 60=20log10AV 3=log10AV 103=AV 1000=AV
Small-Signalvs.LargeSignal ReturntoFigure4-3a,thecommon-emittercharacteristiccurvesfortheNPNtransistor.Thestraightlineplottedonthecharacteristiccurvesisa“loadline”forthe1kΩloadresistorusedinthedesignoftheamplifier stageofFigure4-5.Itrepresentsthevariationincollectorvoltagethatoccurswhencollectorcurrentchanges duetovariationsinbasecurrent.TheoperatingpointAisontheloadline.Ifbasecurrentincreases,thevoltagedropacrossthe1kΩloadresistorincreasesandthecollectorvoltageisdecreased.Ifthecollectorvoltage isreducedtozero,thetransistorwouldbeshorted,andtheoperatingpointwouldbeatpointC.Ifthecollector currentiszero,thetransistoriscutoff,andtheoperatingpointisatB.TheoperatingpointAistheno-signal steady-stateoperatingpoint.Whenaninputsignalisappliedthatvariesthebasecurrentasmall-signalincrementof0.010mAeachsideoftheoperatingpointA,thechangesinthecollectorcurrentwillbe100times (minimumof50)greateror1mA.Thecollectorvoltagewillswing1VeachsideoftheoperatingpointA. AsshowninFigure4-3a,aninputsignalisappliedthatvariesIBfrom0.04mAto0.08mA.Thecollector currentvariesfrom4mAto8mAasaresult,and thecollectorvoltagevariesfrom4Vto8V.Thereis Linear operation amuchlargeroutputvoltageswing,butthesignalis Small-Signal stilllinearandnotdistorted.Astheoperationofthe amplifierchangestoa“large-signal”modeandmore Large-Signal Linear operation inputbasecurrentchangeissupplied,theoperating pointontheloadlinerunsintothenonlinearportion ofthecharacteristiccurves,pointD,anddistortionof Distorted output theoutputwaveformoccurs.Thedistortionisshown Large-Signal inFigure4-8.Itisveryimportanttotheapplication, iflinearoperationiswhatisrequired,thattheinput Figure4-8:Linearsmall-signalandlarge-signal,and signaldoesnotdrivetheoutputoftheamplifierinto large-signaldistortedoperation thedistortionregion. TEAM LRN
41
ChapterFour Thesignalrangefromsmall-signaluntildistortionattheoutputoccursiscalledthedynamicrangeofthe amplifier.Unlessthecircuitisdesignedtooperateoutsidethelinearregion,makecertainamplifiershave enoughdynamicrangefortheapplication.
ClassesofAmplifiers Figure4-9isthesamesortofplotofcharacteristic curvesasFigure4-3a,butitdefinestheclasses ofamplifiercircuitsthatcanbedesigned.The operatingpointsontheloadlineandtheoperating waveformsareshown.Thesmall-signalamplifier ofFigure4-5atpointAiscalledaClassAamplifierbecausetheoperationistotallylinear—exact reproductionoftheinputattheoutput. AClassBamplifieroperatesatpointBontheload line.Itislinearwhenitoperates,butitoperates Figure 4-9: Bias points of various classes of transistorized amplifiers. Figure4-9:Biaspointsofvariousclassesof onlyfor180ºoftheinputcycle.Thisisaveryimtransistorizedamplifiers CourtesyofMasterPublishing,Inc. Courtesy of Master Publishing, Inc. portantclassforpoweramplifiers—amplifiersthat mustsupplylargeamountsofcurrentandhave,atthesametime,significantvoltageswings. AClassABamplifier,asshowninFigure4-9,hasanoperatingpointontheloadlinethatisbetweenClass AandClassB.Itisusedtoeliminatecrossoverdistortioninlinearpoweramplifiersandintunedamplifiers forcommunicationscircuits. AClassCamplifieroperatesontheloadlineatapointwherethetransistoriscutoffandmustbedriven intoconductionbytheinputsignal.AsshowninFigure4-9,collectorcurrentflowsforonlyasmallportion ofaninputcycle.ClassCamplifiersareusedextensivelyinresonanttunedcircuitamplifierstoprovide outputsoveranarrowbandoffrequencies,usuallyradiofrequenciesandabove.
Field-EffectTransistorAmplifiers Amplifiersarealsodesignedusingfield-effecttransistors.ThesymbolsforMOStransistorswereshown inFigure4-2.TherearealsoJFETs(junctionfield-effecttransistors)thataremadefromsemiconductor junctionsratherthanalayerofmetaloveroxideoversilicon.TheycomeinP-channelorN-channeldevices operatinginthedepletionorenhancementmode.Depletionmodetransistorshavecurrentfromdrainto sourcewithoutanygate-to-sourcevoltage;whileenhancementmodetransistorsdonothaveanydrain-tosourcecurrentunlessagate-to-sourcevoltageisapplied.DepletionmodeJFETSarethemostcommontype usedforindividualtransistoramplifierstages.MostMOStransistorsareenhancementmodedevices.
JFETCharacteristicCurves Figure4-10showscharacteristiccurvesofadepletionmodeN-channel.Thechangesindrain-to-source current,ID,areplottedagainstdrain-to-sourcevoltage,VDS,asthegate-to-sourcevoltage,VGS,isvaried. ThecurvesaredevelopedthesamewayasthebipolartransistorcurvesofFigure4-3;however,notethatfor thesecurves,thatachangeinvoltagefromgatetosourcecausesthechangeincurrentfromdraintosource. Todesignanamplifier,aloadlineisplottedonthesecharacteristiccurvesjustasforthebipolartransistor. Beforetheamplifierisdesignedseveralimportantpointsarenoted.Thereisagate-to-sourcevoltagethat iscalledthe“pinch-off”voltage.Itisthegate-to-sourcevoltagethatstartsconductionofdrain-to-source currentforenhancementmodetransistors,anditisthegate-to-sourcevoltagethatcauseszerodrain-tosourcecurrentindepletionmodedevices.Anytimethedrain-to-sourcevoltageisabovethegate-to-source voltagebythepinch-offvoltage,thetransistorisoperatinginthepinch-offmode.Thepinch-offmode TEAM LRN
42
SignalConditioning +VDD
12
Triode Region
ID
Pinch-off region
D
ID Drain-Source Current (mA)
IDSS drain current 10
VGS = 0
G
X
IS
VGS
VGS = −0.5V
VDS
S
8
t
VGS = −1.0V
b.Schematicsymbols
6
VGS = −1.5V 4
A
VGS = −2.0V VGS = −2.5V
2
2
4
6
8
10
12
14
16
18
VDS
ID
7.5
3.75mA
−1.25V
5.5
5.5mA
0.5V
2.0
1.75mA
∆
VGS = −3.0V
Pinch off voltage
VGS −1.75V
gm = 1.75mA 3500µmhos 0.5V
c.Gain&gm
20
VDS Drain-to-Source Voltage (V)
a.Characteristiccurves Figure4-10:AnNPNJFETtransistor(depletingmode)
meansthechannelwithinthefieldV effecttransistorispinchedoffandthe drain-to-sourcecurrent,IDS,remains R essentiallyconstantforfurtherlarge variationsofdrain-to-sourcevoltage, I D VDS.FordepletionmodeJFETs,when V VGSequalszero,thedevicewillbe S V operatingatpointX,andthedrain currentwillbeIDSS.Thepinch-offvoltageandIDSSareimportantparameters specifiedbyFETmanufacturers. a.ChoosingRDat D
RD
RD
D
AN-ChannelJFETAmplifier Design
R1
RD
R2
RS
ID
R1
IS
DS
GS
VDD
VDD
VDD
DD
R2
RIN
RS
−V
b.Fixedbias
c.Selfbias
theoperatingpoint
d.Fixedand selfbias
Figure4-11:AnNPNJFETamplifierdesign
TheJFETamplifierdesignisagainfor anautomotivesmall-signalamplifier.ThedeviceisanN-channeltransistoroperatinginthedepletionmode andthesupplyvoltageis+12V.Thedesignbeginsbyplottingaloadlineonthecharacteristiccurvesof Figure4-10.ThepointAischosenastheoperatingpointbecauseitisinanicelinearregion.AtpointA, ID=4.6mA,VGS=–1.5VandVDS=6.5V.Theloadlinefollowstheequation:
ID=VDD/RD–(1/RD)×VDS
derivedfromVDS=VDD–IDRDasfollows:
IDRD=VDD–VDS
ID=VDD/RD–VDS/RD=VDD/RD–(1/RD)×VDS
SubstitutinginthevaluesforIDandVDS,RD=1,196ohms.
TEAM LRN
43
ChapterFour Theslopeoftheloadlineis1/RD,andthecircuitcorrespondstoFigure4-11a.RDischosenas1.2kΩand theloadlineplottedthroughpointA.EasyendpointsfortheloadlinearedeterminedwhenID=0then VDS=VDDor+12V,andwhenVDS=0,ID=VDD/RDor10mA.
BiasingtheCircuit Figure4-11showsvariouswaysofbiasingtheJFETatoperatingpointA.Acombinationoffixedand self-biasshowninFigure4-11dischosenforthedesign.Theself-biasrequiresthatthevalueofRSbe calculated.Itshouldbenotedthatwithself-bias,theVDSwillbereducedbytheamountofthevoltagedevelopedacrossRS.LookingatthecharacteristiccurvesofFigure4-10,IDwillnotvarysignificantlyifVDSis reducedbyseveralvolts.ThevoltageacrossRSischosentobe+2V.WithID=4.6mA,thevalueofRScan becalculatedas:
RS=2V/4.6mA=0.435×103=435Ω
Astandardvalueof430Ωwillbeused. BecausetheVGSvoltagemustbe–1.5VandthesourceisatthevoltageacrossRS,whichis+2V,thegate voltagemustbe+0.5V.ThisvoltageisprovidedbytheresistordividerofR1andR2.Theinputimpedance oftheJFETisveryhighsoitwillnotloadtheresistordivider;therefore,thevaluesofR1andR2canbe quitehightoreducethepowerdissipation.ThevoltageacrossR2=+0.5Vandcanbecalculatedas:
0.5V=R2/(R1+R2)×VDD=R2/(R1+R2)×12V 12R2=0.5R1+0.5R2 11.5R2=0.5R1
Transposing,
R1=11.5R2/0.5 R1=23R2
ThevalueofR1is23timesthevalueofR2.R2ischosenasastandardvalueof47kΩ,andasaresult,R1 equals1.1MΩ.ThecompleteddesignisshowninFigure4-12.AsnotedinFigure4-10c,fora0.5Vchangein VGS,thereisa2.0VchangeinVDSanda1.75mAchangeinIDScurrent.Theamplifierhasavoltagegainof4.
Example3.CalculatingRatioofR2:R1 InFigure4-11b,ifVDD=+10Vand–V=–10V,whatratioofR2:R1shouldbeusedtoobtainaVGS=–1.5V? Solution: SinceVDD=+10Vand–V=–10VandVGS=–1.5V,thenthevoltageacrossR2is: 8.5=R2/(R1+R2)×20V 8.5R1+8.5R2=20R2 8.5R2=11.5R1 R2/R1=8.5/11.5=0.74 +12V
Gm—Transconductance
R 1.2kΩ Thereisaparameter,gm,forfield-effecttransistorscalledtransconduc1.1MΩ R Output tance.Itisdefinedasthechangeindrain-to-sourcecurrentinamperes pervoltofchangeinthegate-to-sourcevoltage.Itisachangeincurrent, Input ∆I,overachangeinvoltage,∆V;ortheinverseofresistance.Thus,transR 430 Ω 47K R conductancehastheunitsofmhos,ratherthanohms.Fortheamplifierof Figure4-12,asshowninFigure4-10c,thereisa1.75mAchangeindrain 4-12: Completed NPN JFET Small-Signal Amplifier. currentfora0.5Vchangeingate-to-sourcevoltage.Thisisa3.5mAperFigure Figure4-12:CompletedNPN JFETsmall-signalamplifier voltchangeor3500micromhosforgm. 1
2
TEAM LRN
44
D
S
SignalConditioning Thevoltagegainofanamplifiercanbeexpressedas:
AV=–gmRL
Accordingly,thegainoftheamplifierofFigure4-12is:
AV=3500×10–6×1.2×103=4200×10–3=4.2
ThismatchesthevaluecomputedfromFigure4-10.ExaminingtheequationAV=–gmRL,onecanseethat thegaincanbeincreasedbyincreasingRL.TodothisonewouldneedtoincreaseVDD.Ofcourse,ifgmis higherthegainishigher.Thus,devicesarejudgedforamplifiersbytheirgm.Figure4-2bshowsaneasy waytoevaluategm,itistheslopeofalinetangenttoIDSvsVGScurve.
AnNPNMOSFETAmplifier ThesamecharacteristiccurvesshowninFigure4-10applytoanenhancementmodeN-channelMOSFET withacoupleofexceptions.Thegate-to-sourcevoltagesarepositiveandequaltoandgreaterthanthethresholdvoltage,Vt.Vtisrequiredtostartthechannelcurrentfromdraintosourceintheenchancementmode. ThecharacteristiccurvethatplotsontheVDSaxishasVGS=VtandanyadditionalcurveshaveVGS=Vt+V. ThecharacteristiccurvesrepresentthefullVGSvoltage,butonlytheVvalueaboveVtiscontributingto enhancingthechannelcurrent.
IDS Drain-to-Source Current (mA)
ThecharacteristiccurvesfortheN-channelMOSFETareshowninFigure4-13.Thetransistorwillbeusedin theenhancementmodetodesignasmall-signalamplifiersimilartotheJFETamplifier.Again,theamplifier willbeusedinanautomotiveapplicationsothepowersupplyvoltageis+12V.Theoperatingpointissetas pointA,againinthelinearregion.AtpointA,VDS=8V,IDS=3.3mA,VGS=6VandVt=2V.ThedottedparaboliccurveisthelocusofpointswhereVDS=V,thecomponentofVGSaboveVt.ThepointsontheVGScurves wheretheVDScurveintersectsarethepointswherethechannelgoesintopinchoff.Operationtotherightof thedotted-linecurveisinpinchoff;operationtotheleftisinthetrioderegion.Small-signallinearamplifiers mustoperateinthepinch-offregion.TheloadlineisplottedforRL=1.2kΩjustliketheJFETdesign. VDS = VGS − Vt VDS = Vt + V − Vt VDS = V
Triode region
20
Slope = gm
18
kΩ 1.2 line d loa
16 14
Pinch off region
VGS = Vt + 8
VDS = VGS
12
VGS = Vt + 5
2 kΩ load line
10 8
C
6
VGS = Vt + 6
VGS = Vt + 4
B
VGS = Vt + 3
A
4
VGS = Vt + 2
2 2
4
Vt
6
8
10
12
14
16
18
20
22
24
VDS Drain-to-Source Voltage (V)
VGS = Vt = 2V
a.Characteristiccurve Point A VGS Vt + 5V = 7V Vt + 4V = 6V Vt + 3V = 5V ∆ = 2V
Vt = 2V IDS 5.5 mA 3.3 mA 2.5 mA 3 mA
RL = 1.2K VDS 3 mA 5.5V gm = 2V 8.0V = 1500 9.0V µmhos 3.5V
Point B VGS Vt + 4 = 6V Vt + 5 = 7V Vt + 6 = 8V ∆ = 2V
Vt = 2V IOS 3.5 mA 5.5 mA 8 mA 4.5 mA
RL = 2K VDS 17.0V 4.5 mA gm = 2V 13V = 2250 8V µmhos 9.5V
b.Gainandgm Figure4-13:AnN-channelenhancement-modeMOSFET TEAM LRN
45
ChapterFour
FixedandSelf-Bias TheMOSFETN-channelcanbebiased,asshowninFigure4-14a,justliketheJFET.TheVDSvoltageis somewhatlargerbecausethesteady-stateVScanbemuchsmallerduetothefactthatallVGSvoltagesare positive.InFigure4-14a,RL=1.2kΩandIDS=3.3mA;therefore,sinceIS=ID,
RS=0.5V/3.3mA=0.152×103=152Ω
Astandardvalueis150ΩsoRS=150Ω. TohaveVGS=6V,thegatemustbeat+6.5Vsincethesourceisat+0.5V;therefore,
R2/(R1+R2)×12V=6.5V 6.5R1 =(12–6.5)/6.5×R2 R1=0.846R2
R2ischosenasastandardvalueof470kΩ,whichresultsinastandardvalueof390kΩforR1.The designedstageisshowninFigure4-14a.
Drain-to-GateBias AnotherbiasingarrangementthatalsoprovidesnegativefeedbackisshowninFigure4-14b.Inthisarrangement,sincegatecurrentiszero,VDS=VGS,andasmallincreaseindraincurrentcausesasmallreduction inVDS.ThesmallreductioninVDSisfedbacktocauseasmallreductioninVGS,whichcompensatesforthe originalincreaseindraincurrent.Now,since
VDS=VGS–Vt
ItfollowsthataddingaVtvoltagetoVDS,
VDS=VGS–Vt+Vt=VGS
Asaresult,anewparaboliclocusofpointsisdrawnonthecharacteristiccurvesthatrepresentsVDS=VGS, asshowninFigure4-13a.Inotherwords,thecurveisdisplacedtotherightbythevalueofVt=2V.Becauseofthis,theoperatingpointshiftstopointContheloadline,andIDS=4.33mAandVGS=VDS=6.8V.
Gainandgm Figure4-13bprovidessomelarge-signalvoltagegainandgmvaluesforthecircuitofFigure4-14a.Thevoltagegainis1.75VperVandgmis1500micromhos.Calculatingthegainbyusing–gmRL,thevoltagegainis
AV=−1500×10–6×1.2×103=−1.8
Theminussign,ofcourse,meaningachangeinphaseofthesignal.Itwaspointedoutfortheamplifier ofFigure4-12thatusingalargerload VDD = +12V VDD resistorwouldincreasethestagevoltagegain.Anewloadlineusinga2kΩ RL 1.2 kΩ resistorisdrawnonthecharacteristic 1.2 kΩ RL ID + 8.0V curvesofFigure4-13.Theoperating 390 R1 RG = 10MΩ Output D +6.8V kΩ pointisnowpointBandAV=4.25V Output G D + 6.5V perV,gm=2250micromhosand S Input VGS + 0.5V –gmRL=2250×10–6×2×103=4.25. G Input RS 150Ω R2 470 S Theconcernwiththisdesignisthe IS kΩ increasedpowersupplyvoltageto+24V andincreasedpowerdissipationwhen a.Selfandfixedbias b.Drain-to-gatebias theoperatingpointispointBwhere IDS=5.5mAandVDS=+13V. Figure4-14:N-channelMOSFETsmall-signalamplifiers TEAM LRN
46
SignalConditioning
OperationalAmplifiers Integratedcircuitmanufacturershaveprovidedanexcellentproduct—theoperationalamplifier(opamp)— todesignersofelectroniccircuitsforsignalconditioningsensorsignals.Manytypesandvarietiesare availableforawidespectrumofapplications.Systemdesignersthatneedamplificationintheirdesignneed notdesignanindividualamplifiercircuitbutcanuseanopampinstead. Theterm“opamp”referstoadirect-coupledamplifierthatwasusedinitiallyinanalogcomputersto performmathematicalcomputations,whilesolvingreal-timecontrolsystemproblems.OpampsareDC amplifiersthathavehighgain,highinputimpedance,lowoutputimpedance,andwidebandwidth.Another significantadvantageisthattheamplifier’scharacteristicscanbevariedusingexternalcomponents. Figure4-15describesa inverting input general-purposeopamp. I1, I2 = Input currents VD = Differential input voltage Theamplifierhastwo − ZIN = Input impedance I1 inputsandoneoutput. AVD x VD ZIN VIO = Input offset voltage V 1 Theamplifieroutputis VD EO AVD = Open-loop differential voltage gain ZO normallyalinearoutput VIO ZO = Output impedance voltage,VO,thatisproVO VO = Output voltage + I2 portionaltothedifference V2 ofthevoltagebetween noninverting input thetwoinputs.Thus,itis classifiedasadifferential Figure4-15:General-purposeoperationalamplifier amplifier.Thetwoinputs areidentifiedwithaminusandaplussign.Theinputwiththeminussigniscalledtheinvertinginput;the inputwiththeplussignisthenoninvertinginput.Ifthenoninvertinginputismorepositivethantheinvertinginput,theoutputvoltage,VO,ispositivewithrespecttoground.Conversely,iftheinvertinginputis morepositivethanthenoninvertinginput,VOwillbenegativewithrespecttoground.Whenbothinputsare referencedtoground,andtheinvertinginputismorepositive,VOswingsnegative;whenthenon-inverting inputismorepositive,VOswingspositive.
Characteristics ReturntoFigure4-15.Theoutput,VO,canberepresentedbyagenerator,EO=AVD×VD,fedtotheoutputthroughtheoutputimpedance,ZO.EOistheinputdifferentialsignal,VD,amplifiedbytheopen-loop differentialgain,AVD.ZINistheinputimpedance,andVIOistheinputoffsetvoltagethatcausestheoutput voltagetobedisplacedfromzerovoltswhenthereisnodifferentialinputsignal.AVDisusuallyaverylarge number(>20,000)inmostmoderndayopamps;therefore,evenaverysmallinputsignaldrivestheoutput intosaturation.ThisisadistortedoutputasshownpreviouslyinFigure4-8.Asaresult,normaloperationis withfeedbackfromoutputtoinputtosetthegainoftheopampataparticularvalue.
SettingGain LookatFigure4-16.A resistor,Rf,isconnected fromtheoutputbacktothe + invertinginputtocontrol VIN − thegainoftheopamp withnegativefeedback.
If
Ideal Characteristics Rf
IIN
I1 R1
ZIN = Infinity AVD = Infinity
− A
ZO = Zero VIO = Zero
VD
VO
+ B
Inverting Input A R VO = AVF = − f VIN R1
(VO = 0 when VIN = 0) Bandwidth = Infinity
Figure4-16:Opampwithnegativefeedbackandsignaltoinvertinginput TEAM LRN
47
ChapterFour Iftheoutputgoespositive,asitwouldforaninputsignalonAgoingnegative,aportionofthepositive outputsignalisfedbacktotheinputtocancelpartoftheinputsignal.InFigure4-16,theidealopamp characteristicsarelisted.OneoftheseisZIN=infinity.Asaresult,IIN=0;therefore,fromFigure4-16, Since
I1+If=0 I1=(VIN–VD)/R1andsinceVD=0becauseIIN=0,then I1=VIN/R1
and and
If=VO/RfbecauseVD=0,then VIN/R1+VO/Rf=0 VO/Rf=–VIN/R1 VO/VIN=–Rf /R1
or
AVf=–Rf /R1
Thegainoftheinvertingoperationalamplifierwithfeedback,AVf,isdeterminedbytheratioRf/R1,both externalcomponentstotheamplifieritself. InFigure4-17,VINisappliedtothenoninvertinginput;therefore, VR1=VIN–VO,butbecauseVO=0sinceIIN=0, VR1=VIN Therefore, I1=VIN/R1 Since,
I1+If=0,If=I1
Now,
VO=VR1+VRf=VR1+IfRf
Now,withsubstitutionforVR1andIf, VO=VIN+I1Rf Therefore,sinceI1=VIN/R1 VO=VIN+(VIN/R1)×Rf VO=VIN(1+Rf /R1) Or
VO/VIN=1+Rf /R1
Andthus,AVf=1+Rf /R1 Thefeedbackgain,AVf,foranopampwiththesignalonthenoninvertinginputisoneplusthefeedback gainofanopampwiththesignalontheinvertinginput.Theoutputisoutofphasefortheinvertinginput andinphaseforthenoninvertinginput. Insummary, Forinvertinginput:
AVf=–Rf /R1
Fornoninvertinginput:
AVf=1+Rf /R1
Eventhoughthemanufacturedopampsarenotideal,theparametersaresuchthatmakingtheidealamplifierassumptionscauseverysmallerrors(V V countingADCshowninFigure5-8. COMPARATOR Itismadeupofabinarycounterthat A 0 when V ≤ V countspulsesfromacentralclock.The DAC When comparator output countersbinaryoutputisfedtotwo goes from 1 to 0 it triggers latch to latch in data and units—aDACandalatch.Eachunit transfer input to output hasthenumberofinputoroutputbit linestocoverthenumberofbitsreBINARY Clock DIGITAL LATCH quiredfromtheADC.NoticetheDAC COUNTER OUTPUT intheloop.Thisisthereasonthatthe Reset Latch triggering discussionoftheDACcamefirst.The resets counter binarycodeinputtotheDACproduces ananalogvoltagethatfeedsoneinput Figure 5-8: An 8-bit Counting ADC Figure5-8:An8-bitcountingADC ofacomparator.Theanaloginputvoltagetobeconvertedtoadigitaloutputistheothercomparatorinput.WhentheinputfromtheDACislower thantheanaloginput,thecomparatorwillbeahighvoltage(adigital1);whentheinputfromtheDAC isequaltoorgreaterthantheanaloginput,thecomparatoroutputisalowvoltage(adigital0).Whenthe comparatoroutputchangesfromahighvoltagetoalowvoltage,ittriggersthelatchtolatchinthebinary valuesfromthebitlinesofthecounter.Thus,theoutputofthelatchisthebinarycodematchingthevalue oftheinputanalogvoltage. in
C
in
in
C
C
TheAtoDprocessworkslikethis.Thecounterisresettoacountofzero.TheDACoutputiszeroasaresult.Iftheanaloginputvoltage,Vin,issomepositivevalue,thecomparatoroutputwillbea1.Astheclock incrementsthecounter,theoutputoftheDACwillincreaseinsteps,eachasmallpositivevoltage.Ifthe DACoutputisalowerpositivevoltagethanVin,thecountercontinuestocountandincreasestheDACoutputvoltageuntilitisgreaterthanVin.Thistriggersthecomparator,itsoutputgoesto0tolatchinthebinary codeattheoutputtotheADCandresetthecounter.Resettingthecountertozerocausesthecomparator outputtogotoa1andtheADCisreadyforanotherconversion.Oneofthedisadvantagesofthecounting ADCisthetimeforconversion.Theconversiontimecanbeasgreatas2n–1clockcycles,wherenisthe numberofbitsofthebinaryoutputoftheADC.
TEAM LRN
73
ChapterFive
Example4.MaximumConversionTimeforCountingADC Whatisthemaximumconversiontimeforan8-bit,12-bitand16-bitcountingADCwhentheclock frequencyis1MHz? Solution: Themaximumconversiontimeis2n–1clockcycles;therefore,sincetheperiodofa1MHzclock is1µS, N 2n–1 Max.Conversiontime 8 255 255µS = 0.255milliseconds 12 4095 4095µS = 4.095milliseconds 16 32767 32767µS =32.767 milliseconds
SuccessiveApproximationRegister(SAR)ADC AnimprovementinconversiontimeresultswhenusingaSuccessiveApproximationRegister(SAR)ADC. AsshowninFigure5-9,thecounterofFigure5-8isreplacedwithlogic,registerandlatchcircuitstomake uptheSAR,oneofthemostpopularADCs.TheSARcanhaveconversiontimesfrom100µSto1µSand upto16bitsinresolution.Semiconductortechnologiesofbipolar,CMOSandcombinationsofbothhave beenusedtodesigntheSAR.TheSARseemstobethedesignofchoicefortheconversiontimerequired becausethedesiredperformancecanbeobtainedatareasonablecost.Inaddition,systemthroughput (speed)canbetradedforaccuracy—increasingspeeddecreasesaccuracy. TheSARgetsitsnamefromsuccessivelycomparingtheinputanalogvoltagetotheoutputofaDACthat hasabinary-weightedcodeatitsinput.TheconversionprocessbeginsbysettingtheMSBoftheinputto theDACfromtheSARtoa1.Alltheotherbitsaresetto0.ThisproducesananalogvoltageattheDAC outputequaltoone-halfthefull-scalerangeoftheDAC.Atthecomparator,aswiththecountingADC,the DACoutputiscomparedtotheinputanalogvoltage.IftheinputvoltageisgreaterthantheDACvoltage, Vin
A 1 when Vin >VC
Input Voltage Vin
A 0 when Vin ≤ VC
7 FS 8 3 FS 4
COMPARATOR DAC Output
VC Comparator output going from 1 → 0 tells logic to reset SAR bit to 0 and set next bit to 1.
DAC
FS
FS 2
1
1
1
0
1
0
Clock
L A T C H
DIGITAL OUTPUT
Digital Code Input
b.SARprocess
Control Logic
a.Blockdiagram Figure5-9:SuccessiveapproximationADC TEAM LRN
74
0 LSB
MSB Successive Approximation Register
1
Analog-to-DigitalandDigital-to-AnalogConversions thecomparatoroutputisa1andtheSARMSBisleftata1,andthenextmostsignificantbitinputtothe DACissettoa1.WiththeMSBandnextsignificantbitsettoa1,theoutputfromtheDACwillnowbe one-halfplusanotherone-quartertoequalthree-quartersofthefull-scalerangeoftheDAC.Thesequence isshowninFigure5-9b. Thesequencecontinuestosetthenextmostsignificantbittoa1(allotherbitsarezero)aslongasthe comparatoroutputisa1.Eachtimeabinary-weightedvoltageisaddedbytheDACtoitsoutput—one eighth,onesixteenth,onethirty-secondth,andsoon—thecomparatoroutputwillbea1aslongasthe inputvoltageisgreaterthantheoutputoftheDAC.Whensettingthenextsignificantbittoa1causesthe inputvoltagetobelessthantheDACoutput,thecomparatoroutputgoesto0.Thisresultsinsettingthe lastsignificantbitbacktoa0froma1,reducingtheDACoutputbelowtheinputvoltage.Butatthesame timethenextmostsignificantbitissettoa1andtheDACoutputincreasedagain;however,thistimeonly sayonethirty-secondthofanincrementofvoltageisaddedinsteadoftheone-sixteenththatwasaddedat thebitbefore.ThisisshowninFigure5-9b.Thesuccessiveapproximationcontinuesuntilallbitsaretested andtheclosestapproximationisobtained.TheresultisthattheSARoutputbiteitherissettoa1ora0 dependingontheresultofthecomparisonoftheoutputoftheDACandtheinputvoltage.Thefinaldigital codeforFigure5-9bis11101010. Thetimetoconverttheinputanalogvoltagetoadigitaloutputisnclockcycles,muchlessthanthecountingADC.Figure5-9bshowsthatafternclockcyclesallthebitshavebeentestedandsetandtheSAR outputwillbethedigitaloutputcode.Theoutputcanbetakeninparallelorshiftedoutaseachcomparison ismade.ThisisanadditionaladvantageoftheSARADC.
Example5.MaximumConversionTimeforSARDAC Repeatthecalculationofthemaximumconversiontimeofan8-bit,12-bitand16-bitSARADC.The clockfrequencyis1MHzwhoseperiodis1µS. Solution: n Max.ConversionTime(nclockcycles) 8 8µS 12 12µS 16 16µS
CapacitorCharge-RedistributionADC Ablockdiagramofahybridresistor-tree,capacitorchargeredistributionADCisshowninFigure5-10.Itconsistsof aresistor-treeconversioncircuitthathandlesMbitsofthe ADCoutputandacharge-redistributioncapacitorbank conversioncircuitthathandlesKbitsoftheADCoutput. Thecontrollogic,undersynchronizationbytheclock,providestheswitchinglogicforsettingthebitsintheSAR,the switchsettingsfortheresistortreeandtheswitchsettings forthecapacitorbank.Aftercomparisonofabitbythe comparator,similartotheprocesspreviouslydescribedfor theSARADC,thebitevaluationbythecomparatorisfedto theSARtosetthebitfortheADCoutput.ThehybridDAC isacompromisebetweenusinganallcapacitorchargeredistributioncircuitandanallresistor-treecircuit.The capacitor-chargeredistributionhasslowconversiontimes; TEAM LRN
75
Vin M bits of R String Eval.
K bits of C Charge Redistribution
Compare
Vdd 2
SAR
Switch Control Logic
Start Clock
ADC Output (M+K) Bits Figure 5-10: Hybrid R-Tree Capacitor Charge-Redistribution ADC Figure5-10:HybridR-treecapacitorchargeredistributionADC
ChapterFive theresistor-treecircuithasfasterconversiontimesbutuseslargeICrealestate,especiallyasthebitsinthe ADCoutputincrease.Inintegratedcircuits,resistorsusemoreareathancapacitors.
TheADCOperation InthehybridADC,theinputanalogvoltageiscapturedasanamountofchargeonabankofcapacitors.The capacitorsarebinary-weightedandhandleacertainnumberofbits(equaltoK)ofthedigitalcodetobeconverted.Theremainingbits(equaltoM)areconvertedthrougharesistortreeconversion.Thechargeonthe capacitors,whichremainsconstantduringtheconversion,playsanimportantpart,notonlyintheKbitconversions,butalsointheconversionoftheMbitsusingtheresistortree.Forexample,inFigure5-11,M=5 andK=3sothatfivebitsareconvertedusingtheresistortreeandthreebitsareconvertedusingthebinaryweightedcapacitors.TheMbitsarethefivemostsignificantandtheKbitsarethethreeleastsignificant. Vdd
VREF
Additional Sx bits
Resistor Tree − M bits
SC Switches Vm + ∆V Vm
2M resistors of equal value
(K-1) 2 C
(K-2) 2 C
Visb
COS 2
Coffset =
Node X
Sa
C 2 Vdd
4C
2C
C
C
− +
Sd Switches Y
Vdd
COMPARATOR
Bit Evaluation
2
Z
Capacitor charge − redistribution bank − K bits
Sb
Vin
Figure5-11:Detailsofresistortreeandcapacitorbank(dataacquisitionperiod)
ConvertingtheMBits TheconversionprocessstartswiththedataacquisitionperiodshowninFigure5-11.SwitchSbisconnected totheinputanalogvoltage,Vin,switchSxisconnectedtoVDD/2andSaisconnectedtoVlsb.ThebinaryweightedcapacitorbankchargestoVDD/2–Vinbecausethelowerendofthecapacitorsareconnectedto NodeZ.Thetotalcapacitanceinthebankis2KC.TheoffsetcapacitorCOS,equaltoC/2,ischargedto VDD/2–Vlsb.BothinputstothecomparatorareconnectedtoVDD/2atthistime,thus,nocomparison. AtthecompletionofthedataacquisitionperiodSxopens,SbswitchesfromVinandisconnectedtotheVm lineoftheresistortree,asshowninFigure5-12,andSaisconnectedtoground.ThevoltageatNodeXis theimportantvoltageinalloftheconversionsforitfeedstheminusinputtothecomparator.Theplusinput ofthecomparatorisconnectedtoVDD/2.IfthevalueofNodeXislessthanVDD/2,thecomparatoroutput willbea1;ifitisgreaterthanVDD/2,theoutputwillbea0. WithSbconnectedtotheresistortree,thecontrollogicsetstheMSBoftheoutputdigitalcodetoa1andselectsthetapfromtheresistortreethatrepresentsone-halfoffull-scalerangeforVmjustasintheSARADC. Asaresult,thevoltageatNodeXisevaluatedagainstVDD/2.IfthevoltageofNodeXislessthanVDD/2,the MSBoftheoutputdigitalcodefromtheSARissetto1.IfthevoltageatNodeXisgreaterthanVDD/2the outputbitoftheSARissetto0.ThiscompletestheevaluationoftheMSB;itiseithersettoa1ora0. TEAM LRN
76
Analog-to-DigitalandDigital-to-AnalogConversions V Thecontrollogic S C S 2 Capacitor 2 X stepstoevaluate bank − Bit thenextsignificant V + ∆V Evaluation + Q C bit.Itsetsthenext MSB = 1 V Z S ∆V = one lsb significantbittoa V = V 2 S V Node X 2 1.Thisalongwith Q theMSBvalueof a1or0willcause theSARtoselect Figure5-12:EvaluatingR-treebits thecorresponding valueofVmfromtheresistortreetofeedtheNodeZlineconnectedtothecapacitorbank.Thenewvoltage valueontheZlinecausestheconstantchargesonthecapacitorbanktoredistributeandchangethevoltage atNodeX.ThenewNodeXvoltageiscomparedtoVDD/2,andthebitevaluationiscompletedbysetting thesecondmostsignificantbittoa1or0dependingontheresultofthecomparison.Thebitevaluation processcontinuesuntilallMbitsareevaluated.ThisresultsinasetSARcodeoutputfortheMbits.At theendoftheMbitevaluations,thevoltageofNodeXwillberepresentativeofthevalueofthefivemost significantbitsintheSARoutputdigitalcode. dd
a
X
m
m
C
b
ref
dd
b
c
m
C
ConvertingtheKBits
Vdd
Node X 2
C TheNodeXvoltagevalueis 2 Capacitor bank maintainedastheevaluation S Resistor tree voltage X nowchangestothecapaciafter all M bits have torbankcircuittoevaluate been evaluated 2C 2 C 4C theKbits,thelastthree significantbitsofthedigital C C outputcode.TheKbit S V + ∆V V Y evaluationisaccomplished 2 byswitchingtheendsofthe Z S V capacitorsintherespective bitposition,onebitposition atatime,totheYline.The Figure5-13:Evaluatingcapacitorbits Ylineconnectstoaresistortreeconnectionthatisone significantbithigherinvoltage(Vm+∆v)thantheZlinevoltage.
Sa
x
(K−1)
d
m
m
− +
COMPARE Bit Evaluation
dd
b
ThemostsignificantbitofthethreeKleastsignificantbitsisevaluatedfirstasshowninFigure5-13.The endofitscapacitor,inthiscaseofvalueC,isconnectedtotheYline.ThechargeonthecapacitorsredistributesandchangesthevoltageatNodeX.IfNodeXisgreaterthanVDD/2,thebitissettoa1andtheend ofthecapacitorisleftconnectedtotheYline;ifitislessthanVDD/2,thebitissettoa0andtheendofthe capacitorisswitchedbacktotheZline.Withthebitsettoa1,thevoltageoncapacitorCisaddedtothe resistortreevaluetosettheNodeXvoltagevalue. Thecontrollogicswitchestheendofthenextbinary-weightedcapacitanceofthenextleastsignificantbit bychangingitsSdswitchandconnectingittotheYline.Thechargeredistributeswiththenewcapacitor, nowwithavalueof2C,andthevoltageatNodeXchangescorrespondingly.TheNodeXvoltageiscomparedtoVDD/2andthebitevaluatedasaboveandtheoutputsettoa1ora0.Asbefore,ifthebitissettoa 0,theendofthecapacitorisreturnedtotheZlinewithswitchSd.TheprocesscontinuesuntilallKbitsare evaluatedandthefinalSARdigitalcodeissentoutfromtheSAR. TEAM LRN
77
ChapterFive
HighestSpeedConversions Analog Input Voltage VIN VREF
+
R
− R
+ −
R
+ −
DECODER
Thehighestspeedconversionsaremadewithflash ADCs.Thehighspeedismadepossiblebytheuseof simultaneouscomparisonsoftheanaloginputvoltagetoreferencesgeneratedfromaresistorstring.A blockdiagramofaflashADCisshowninFigure5-14. Forann-bitflashconverter,thereare2n–1reference voltagesand2n–1comparatorsrequired.Thus,for an8-bitflashconverter,255comparatorsarerequired, andfora10-bitflashconverter,1023comparatorsare required.Ahighpriceispaidforthespeedadvantage—highpower,largesiliconareafortheICs,and highcostcontributetothepricethatmustbepaid.
LATCH
Theconversionprocessisrathersimple.ThereferR + encevoltagesareconnectedtotheminusinputofeach − comparatorandareseparatedinvaluebyoneLSB. Theanaloginputvoltageisconnectedtotheplusinput ofeachcomparator.Asimultaneouscomparisonis madeateachcomparator.Iftheinputanalogvoltage + ontheplusinputislessthanthereferencevoltageon − theminusinput,theoutputofthecomparatorisa0. R + Thecomparatoroutputwillbea1iftheinputanalog − voltageisgreaterthanthereferencevoltage.Each R comparatoroutputispresentedtothedecoderatthe 2 Comparators sametimeandthedecoder’soutputisstoredasan n-bitwidecodeinalatch.Alltheinputsoftheinput Clock analogvoltagethataregreaterthantheirrespective Figure5-14:Flashconverter resistor-stringreferencevoltageswillhavecomparaFigure 5-14: Flash Converter toroutputsofa1;alltheinputsthatarelessthantheir respectiveresistor-stringreferencevoltagewillhavecomparatoroutputsthatare0.Theresultantdigital codeintothedecoderresultsintheequivalentbinaryoutputcode,foragivenn-bitcode,thatrepresentsthe valueoftheinputanalogvoltage. n−1
SampleandHoldandFilters SampleandHold TherearetwootherfunctionsthatareassociatedwithAtoDconversions.Oneissampleandhold;theotherisfiltering.Sampleand hold,asshowninFigure5-15,isjustwhatitsays.Theinputanalog signalissampledbyswitchS1closingmomentarilyandcharging C1.C1thenholdsthevalueoftheinputvoltageuntiltheADCcan processthedata.Itprobablyisobviousthatacapacitorthatleaks itschargebetweensampleswouldcontributeerrorstothesampling process.Likewise,switchesthathavevariablecontactresistance varythetimestochargethecapacitorsandcontributeerrors.Thus, highqualitycapacitorsandfastswitchesarekeytosampleandhold TEAM LRN
78
S1 Input Analog Signal
ADC
C1
FigureFigure5-15:Asimplesample 5-15: A simple Sample and Hold Circuit
andholdcircuit
Analog-to-DigitalandDigital-to-AnalogConversions circuits.Atonetime,sampleandholdcircuitswereavailableindependently;however,mostsampleand holdcircuitsareincorporatedrightintheADC.Infact,inthehybridresistor-treecapacitorcharge-distributionADCthereisnoneedforasampleandhold.Itisbuiltinaspartofthecircuitdesign,savingcoston providingsuchacircuit.
Filtering
C
Ampl.
Ampl.
Rel. Amp
Filtering,asshowninFigFilter Output Initial Output ure5-16a,isusedtolimit thebandwidthofsignals. DAC Filter Assuch,itcansmoothout theinputsignal,eliminate f freq. t t t t t t t t t t t t t t t t noisespikes,limitthehigh time → time → frequencyresponse,select a. Bandwidth Limiting b. Filtering DAC output a.Bandwidthlimiting b.FilteringDACoutput particularsignalfrequenFigure 5-16: Filtering cies,andthelike.Figure Figure5-16.Filtering 5-16bshowstheirspecific useinDACsystems.TheDACoutputcanbeastep-likesignal.Filteringisusedtosmoothoutthestep natureofthesignalandoutputasmoothanalogsignal.Mostfiltersaretailoredtotheparticularapplication. Theyareselectedtocontrolaspecificneedofthesystem;therefore,generalfiltersareusuallynotthesolution.Thefiltersmustbechosenspecificallyfortheapplication.TheexamplefortheDACsysteminFigure 5-16brequiresthatthefilterbechosenforthespecificsystem.Theoutputsignalthatemergesmustbea smoothcontinuoussignalwithtimeratherthanajaggedjerkyout.Theresultisthattheinputsignalshown inFigure5-2isreproducedveryaccuratelyaftertheADCconversionandtheDACconversion. 1 2 3
4
5 6
1 2 3
7 8
4
5 6
7 8
Summary Inthischapter,DACsandADCshavebeendiscussedshowingtechniquesusedforeachandcircuitsthat implementthefunctions.Inthenextchapter,digitalprocessorswillbediscussed.Theyreceivethedigital signalsfromtheADCs,modifyandmanipulatethedigitalsignals,andthendeliverthedigitalsignalstothe DACs.
TEAM LRN
79
ChapterFive
Chapter5Quiz 1. 2. 3. 4. 5. 6. 7. 8. 9.
Inabinarynumber: a. thedigitpositionvalueincreasesby1timesoverthedigitvaluetotheright. b. thedigitpositionvalueincreasesby2timesoverthedigitvaluetotheright. c. thedigitpositionvalueincreasesby4timesoverthedigitvaluetotheright. d. thedigitpositionvalueincreasesby8timesoverthedigitvaluetotheright. Adecimalequivalentofabinarynumber: a. istheadditionofallthebitpositionvaluesforallthebitsequalto1. b. isthemultiplicationofallthebitpositionvaluesforallthebitsequalto1. c. isthesubtractionofallthebitpositionvaluesforallthebitsequalto1. d. isthedivisionby2ofthebitpositionvalueoftheLSB. Theprincipleusedtodesignaresistor-stringDACis: a. theMSBisone-eighththefullvalueandthenextbitpositionisonehalfoftheMSBvalue. b. theMSBisone-fourththefullvalueandthenextbitpositionisonehalfoftheMSBvalue. c. theMSBisone-thirdthefullvalueandthenextbitpositionisonehalfoftheMSBvalue. d. theMSBisone-halfthefullvalueandthenextbitpositionisonehalfoftheMSBvalue. TheequivalentresistancebetweenVREFandgroundoftheR/2RladderDACis: a. 4R. b. 2R. c. R. d. R/2 ThedigitpositioncurrentintheR/2RladderDACis: a. onehalfthecurrentinthebitpositiontotheleft. b. oneeighththecurrentinthebitpositiontotheleft. c. onefourththecurrentinthebitpositiontotheleft. d. equaltothecurrentinthebitpositiontotheleft. Thevoltageincrementfroma10-bitresistor-stringDACwith10Vappliedis: a. about10volts. b. aboutonevolt. c. about10millivolts. d. about100millivolts. Asimplecurrent-steeringDAC: a. combinesbothvoltageandcurrenttoproducetheanalogoutput. b. addsbinary-weightedvoltagestoproducetheanalogoutput. c. producestheanalogvoltagebysensingaresistorstring. d. addsbinary-weightedconstantcurrentstoproducetheanalogoutput. ThecountingADC: a. containsaDACwhoseinputistheoutputofacounter. b. containsacomparatortocomparetheanaloginputtotheoutputofaDAC. c. latchesthecounteroutputcodewhenthecomparatorinputsareequal. d. alloftheabove. e. aandbonlyabove. TheSARgetsitsnamefromaprocessthat: a. successivelycomparestheinputanalogvoltagetotheoutputofaDACthathasabinaryweightedinputcode. TEAM LRN
80
Analog-to-DigitalandDigital-to-AnalogConversions b. sumsaseriesofbinary-weightedcurrents. c. sumscurrentfromaladderresistornetwork. d. sumsvoltagesfromaresistorstring. 10.ThemaximumconversiontimeforaSARDACis: a. 4nclockcycles. b. nclockcycles. c. 8nclockcycles. d. n/2clockcycles. 11.Inthehybridresistor-treecapacitorcharge-redistributionADC: a. (M–K)bitsareconvertedusinganRtreeand(M+K)bitsusingaCnetwork. b. KbitsareconvertedusinganRtreeandMbitsusingaCnetwork. c. MbitsareconvertedusinganRtreeandKbitsusingaCnetwork. d. (M+K)bitsareconvertedusinganRtreeand(M–K)usingaCnetwork. 12.Inthehybridresistor-treecapacitorcharge-distributionADC: a. theKbitsareevaluatedfirstandthentheMbits. b. theMbitsareevaluatedfirstandthentheKbits. c. theKandMbitsareevaluatedatthesametime. d. onlytheKbitsareevaluated. 13.InFlashADCs: a. thehighspeedismadepossiblebysimultaneouscomparisons. b. thereareasmanycomparatorsastherearebits. c. thereareasmanyreferencevoltagesastherearebits. d. thebasicstringforcomparisonsisacapacitorcharge-redistributionnetwork. 14.Asample-and-holdcircuit: a. hasamomentaryswitchthatconnectstheinputvoltagetoacapacitorlongenoughforthe capacitortocharge. b. hasaresistorinserieswithacapacitorinserieswithaswitch. c. hasacapacitorthatischargedtoholdthevalueoftheinputvoltage. d. aonlyabove. e. aandcabove. f. noneoftheabove. 15.FilteringisimportanttoDACoperation: a. becauseitaddsnoisetotheoutputsignal. b. becauseitreturnstheDACoutputtoasmoothcontinuoussignal. c. becauseitselectsonefrequencytopassonfromtheoutput. d. becauseitactsasaveryhigh-frequencyhigh-passfilter.
Answers:1.b,2.a,3.d,4.c,5.a,6.c,7.d,8.d,9.a,10.b,11.c,12.b,13.a,14.e,15.b. TEAM LRN
81
C H APTER 6
DigitalSystemProcessing Introduction Previouschaptershavesensedtheanalogsignal,conditionedthesignalandconverteditfromanalogto digital.Inthischapter,theprocessingofthedigitalsignaltomodify,calculate,manipulate,changetheform ofthesignalortoroutethesignaltoparticularchannelsisdiscussed.Alloranyoftheseprocessingoperationsmaybeneededtoaccomplishataskpredeterminedbytheapplicationthatisbeingfulfilled.Thetotal systemisdesignedtoperformatask,andthedigitalprocessorisaveryimportantpartofthesystem.
DigitalProcessororDigitalComputer Asthenameimplies,thedigitalprocessorinputs,stores,performsoperations andoutputsdigitalsignals.Performinglogicorarithmeticcomputations, modifyingtheformatofthesignal, storingdatatemporarilyormorepermanently,decodingsignalsfordisplay andoutputtingsignalsaresomeofthe operationsdictatedbytheinstructions intheapplicationprogram.
CPU
Central Processing Unit
INPUTS
OUTPUTS
Clock
Timing and Control Signals Address Codes on Address Bus
Instruction and Data Codes on Data Bus
Power Programs Figure6-1showsthebasicstructure System are stored ofadigitalprocessor,moregenerMEMORY in memory as well as data allycalledadigitalcomputer.The for the programs mainbrainofthestructureistheCPU (centralprocessingunit)wheretheopFigure6-1:Adigitalprocessor Figure 6-1: A Digital Processor erationsthatareperformedaredecided uponandcontrolled.Thedigitalsignals intheformofbinarycodesthattellthedigitalprocessorwhichoperationtoperformarecalledinstructions. Eachdigitalprocessorismanufacturedtorespondtoaparticularsetofinstructions.Eachinstructioninthe setwillcausethedigitalprocessortodoauniqueoperation.Forexample,aninstructionmightcausethe digitalprocessortoinputadigitalsignalfromaparticularinput.Oraninstructionmighttelltheprocessor totaketheinputsignalandstoreittemporarily,ortostoreitinmemorymorepermanently.Anotherinstructionmighttakeadigitalsignalthathasbeenoperatedonbytheprocessorandoutputittoaparticular output.Oraninstructionmighttelltheprocessortodoalogicaloperation(forexample,ANDtwobinary numberstogether),ortodoanarithmeticoperationlikeADDtwobinarynumbers,ormaybesubtractthem. Theinstructions,presentedinsequencetotheprocessor,arecalledaprogram.
DigitalComputerProgram Thearrangementoftheinstructions,oneafteranother,forthedigitalprocessortoperformsetoperationsin aparticularsequencetoaccomplishataskiscalledaprogram.Thesetofinstructionsinaprogramisstored inmemorytoberecalledeachtimethatthedesiredtaskisrequired.Ifadifferenttaskisrequired,thena differentprogramisneeded. TEAM LRN
82
DigitalSystemProcessing AsshowninFigure6-1.Theinstructionsofaprogramarestoredinmemoryatspecificaddresses,usuallyinsequence,andaremovedfrommemorytotheCPUoverthedatabus.Itisjustlikeahomewitha particularaddress.Thepostofficeusestheaddresstodeliverthemail.Inlikefashion,theinstructionsin memoryareatuniqueaddresses.Whenaparticulartaskisneeded,theaddressofthefirstinstructioninthe programissentbytheCPUtomemoryovertheaddressbus.Theaddresslocatestheinstructioninmemory, theCPUinstructsthememorytoreadtheinstructionanditissentoverthedatabustotheCPU.TheCPU decodestheinstructionandperformsthedirectedoperation.Eachsubsequentinstructionintheprogramis addressed,recoveredfrommemory,senttotheCPUandexecuted.
AddressandInstruction/DataBus Addresses,overtheaddressbus,arenotonlyusedtolocateinstructionsinmemorybutareusedtoidentify particularinputsorparticularoutputs.Byaddressingaparticularinput,theCPUhasselectedthatinputto supplyinputdata;oraddressingaparticularoutput,theCPUwillsenddatatothatoutputtobetransmittedtothenextfunction.Andthereisanotheruseofaddresses.Whenaninstructioncallsforanarithmetic operation,(orotheroperationsthatrequireuniqueinformation),suchas,ADDAandB,thedataAandthe dataBmustbesuppliedtotheCPUbeforetheoperationscanbeperformed.DataAandBandotherdata usedfortheprogrambeingexecutedarestoredinanotherportionofmemory,separatefromtheprogram. DataAandDataBareaddressedovertheaddressbusjustlikeinstructionsandrecoveredandsenttothe CPU.TheinstructionsandthedataaretransmittedfrommemorytotheCPUoverthedatabus;thus,this busisusuallycalledtheinstruction/databus.
TimingandControl AlltheCPUoperations,alladdress,instruction,anddatatransfers,asshowninFigure6-1,occurinatimed sequencedeterminedbythetimingandcontrolsignalsderivedfromtheCPU’sclock.Theclockisacircuit thatoutputsaseriesofrepetitivepulsesoccurringatasetfrequencyorsetfrequencies.Theclockpulses havefastriseandfalltimessothatcircuitscanbetriggeredoneitheredgetoaccuratelytimetheoperation ofthecircuits.Therisetimeiscalledtheleadingedgeandthefalltimethetrailingedgeofthepulses. Clocksignalsmustbeveryaccurate.Asaresult,theyaregeneratedbyphase-lockedloops(PLLs),orfor thegreatestaccuracy,byquartzcrystaloscillators.Quartzcrystals,ofaparticularcutandsize,whenexcited withelectricity,willoscillateataveryprecisefrequency.Theclocksignalspreciselycontrolthetransfers, manipulations,andstorageofinformationthroughouttheCPUandtheaccompanyingtotalsystem.
PowerSystems Eachdigitalprocessorhasacompleteuniquepowersystem.Sophisticatedsystemsarerequiredforthe distributionofthesupplyvoltagesandtherequiredcurrents,regulatedtokeepthevariationofvoltagesto withintightlimits,asthecircuitsswitchrapidlyfromonestatetoanother.Extensiveuseofbypasscapacitorsatcriticaljunctionshelptomaintainvoltageswithinlimitsassignificantvaluesofcurrentareswitched alongthesupplylines. Asthedensityofintegratedcircuitshasincreased,thereismoreneedforheatsinksandcoolingairdistributionasthewatts/in2dissipationincreases.ICtechnologyhasledthewayascircuitdensityincreasedwithin anICtochangethecircuittypefrombipolartoMOS(metal-oxide-semiconductor)toCMOS(complementaryMOS)sothatthepowerdissipationpercircuitfunctionhasbeenreduced.Asdensityfurtherincreased, thesupplyvoltagesforcircuitoperationhavebeenreducedfrom5Vto3V,andnow1.8Vtoagainreduce thepowerdissipationperfunction.Thetightregulationspecificationsstillremainevenwiththereductionin thevoltagevalues. TEAM LRN
83
ChapterSix
TheCPU— ProgramCounter
Instruction/Data Bus
Address Bus
Figure6-2isadiagramofageneralized Instruction/Data Data-Address Instruction Instruction/Data Address Register centralprocessing Register Register Address/Switch (Program Counter) unit(CPU).Themain componentsarethe ALU Instruction Logic Arithmetic programcounter,the Decoder Circuits Circuits INTERNAL instructionregister, MEMORY I/O A B B A theinstructiondecodALU Switching Input/Output Registers Circuits Circuits er,thedataaddress Read-only Memory (ROM) Input Address register,thearithInput Circuits Random-Access meticandlogicunit Memory (RAM) Output ALU (ALU),thetiming Address Registers Register andcontrolcircuits, Output andthepermanent andtemporarystorTiming and Control Circuits Clock age.Asdiscussed previously,adigital code,calledan Timing Control instruction,organizedinsequence Figure6-2:AgeneralizedCPU intoaprogram,is senttotheCPUto instructittoexecuteaparticularoperation.Theinstructioncamefromamemoryaddresscontainedinan instructionaddressregistercalledtheprogramcounter.Theprogramisstoredinmemoryoneaddressafter anotherinsequencesotheprogramcounterholdingtheaddresscanbeincrementedbyonetostepthrough theprograminstructionsonestepaftertheother.Thus,thenamefortheaddressregisteristheprogram counter.Eachinstructionaddressfromtheprogramcounteraddressesthenextstepintheprogramasthe taskproceeds.
Example1.ProgramCounter Using4-bitaddresses,showinasimpleexamplehowtheprogramcounterisincrementedtosequence throughaprogramtoadd16to8. Solution: Program Counter (increment by 1)
Memory
Address
0001
0001
MOV 16 to Register A
0010
0010
MOV 8 to Register B
0011
0011
Add Register A to Register B
0100
0100
Place sum in Register A
Instruction Address Chapter 4 Example 1 Illustration
TEAM LRN
84
Instructions in memory sent to instruction register in CPU in sequence
DigitalSystemProcessing
CPU—InstructionRegisterandInstructionDecoder AsthedigitalcoderepresentingtheCPUinstructionisretrievedfromitsmemorylocationitisstoredina temporarystorageregistercalledtheinstructionregister.Hereitisrecognizedanddecodedbytheinstructiondecoderanddirectedtotheappropriatecircuitstoexecutetheoperationdictatedbytheinstruction.
CPU—TheDataAddressRegister Iftheinstructionrequiresthatadditionaldatabefetchedfrommemory,thenthenextinstructionswilldirect theCPUtoplacetheaddressforthedatainthedataaddressregister,sendtheaddresstomemorytoretrieve thedataandstoreitinatemporarystoragelocationintheCPU,eitheraregister,oraRAMlocation.Through amultiplexingswitch,theinstructionanddataaddressaresenttomemoryoverthesamebus,thedatabus.
CPU—TheArithmeticLogicUnit(ALU) TheALUprovidesthelogical,computational,anddecision-makingcapabilitiesoftheCPU.Basicarithmeticoperations,suchas,addition,subtraction,multiplication,anddivision;basiclogicaldecisions,aswell as,greaterthan,lessthan,equalto,positiveornegativeareallperformedbytheALU. RegistersfortemporarystorageofdatabroughtfrominputsorfrommemoryareavailableintheALU.The informationintheseregistersisusedbytheCPUforcompletingtheoperationdirectedbytheinstruction addressedbytheprogramcounter.Whentheoperationiscompletedtheinformationiserasedorreplaced withnewinformationtobeusedforexecutingthenextinstruction.
CPU—InternalMemory ThereareinternalmemoriescontainedwithintheCPU.Theymaybeadditionalregisters,read-onlymemory(ROM)orrandom-accessmemory(RAM).Theystoreparticularsetsofinstructionscalledsubroutines, temporarydata,anddataroutinginformation.TheRAMisofthetypethatneedstoberefreshedperiodically.SomeCPUsdonothaveanyROMorRAM,butusuallyhavetheadditionalregisters.FortheseCPUs, theROMorRAMisintheexternalmemoryshowninFigure6-1.
TimingandControl EachoftheoperationsoftheCPUistimedandcontrolledbycircuitsthatoperateatspecifictimes.Many operationsoccuratthesametime;othersaresequencedsotheyoperateafterdataisentered,ortransmitted, orbeforeanotheroperation.Thetimingandcontrolsignals,generatedfromthemasterclocksignals,not onlytimetheCPU,butalsoaredistributedthroughouttotimeandcontrolthecompletesystem.
CPU—InputandOutput(I/O) NotallCPUshavetheinputandoutputselectioncircuitsintheCPU;forsome,thesecircuitsareexternalas showninFigure6-1.Figure6-2showstheI/OcontainedintheCPU.Theinputaddressregistersdetermine theparticularinputthatwillreceivedata,andtheoutputaddressregistersdeterminetheparticularoutput usedtocoupleoutdatatoexternaldestinations.IftheCPUneedsdata,theCPUsendstheaddressofthe inputtoreceivethedatatotheinputaddressregisterandinputsthedatafromthatinput.TheCPUinputs thedataataselecttimesothatitissynchronizedtotheoperationthatisbeingexecuted.Likewise,after theCPUhasexecutedanoperation,theresultantdataneedstobeoutputtedtocompletethetask.TheCPU sendstheaddressoftheoutputthatistocoupleouttheresultantdatatotheoutputaddressregister,and, synchronizedbytheclock,outputsthedata.
TEAM LRN
85
ChapterSix
Example2.I/OSelection Showwithasimpleexample,usinga4-bitcode,howaparticularinputisselectedbytheCPU. Solution: Load Input 4 bits Address Register INPUT ADDRESS with address of input desired. REGISTER Address from register is sent to decoder that selects the proper input.
INPUT 0
D E C O D E R
Address
0000
INPUT 1
0001
INPUT 2
0010
INPUT 3
0011
INPUT 15
1111
INPUT
0011
WhatisaMicroprocessor? WhenallthecircuitryforthefunctionsshowninFigure6-2foraCPUarecontainedinanIC,theICis knownasamicroprocessor.AttachtoittheI/Ofunctions,memory,andpowersupply,andonehasadigital processorshowninFigure6-1,ormorecommonly,adigitalcomputer.
WhatisaMicrocomputer? Whenallthecircuitryforadigitalcomputeriscontainedononeintegratedcircuit,theunitiscalleda microcomputer.Eventhoughthereareself-containedmemoryandI/Ocircuitscontainedinamicrocomputer,externalcircuitsofthesametypemaybeadded,especiallymemory.Asaresult,therearemany variationsbetweenmicroprocessorsandmicrocomputers.Memory,I/O,signalconditioning,timingand controlmanytimesareaddedtoadapttheparticularICtoanapplication,ortoamarketrequirement. Aparticulartypeofmicrocomputer,nowcalledamicrocontrollerunit(MCU),hasbeenadaptedto theindustrialcontrolmarket.AmicrocontrollerunitfromtheMSP430familymanufacturedbyTexas InstumentswillbeusedinChapter7toexplainassembly-languageprogrammingandinChapter10to demonstratetheapplicationofMCUsbyprovidingthereaderanopportunityforahands-onprojectthat canbebuiltfromcontainedinstructions.
SystemClarifications SystemBuses InFigure6-1andFigure6-2therearewidesignalpathsconnectingthefunctionalunitsinthediagrams. Eachofthesecontainsmultiplewiresconnectingbetweenunits.Eachiscalleda“bus”becauseitrepresents morethanonewiremakingtheinterconnectionsbetweenunits.Forexample,ifthememoryinFigure6-1 has65,536differentmemorystoragelocations,thenabinaryaddressof16bitsmustbeusedtoaddress eachlocation.Theaddressbus,asaresult,isreally16wiresbundledtogether,eachwirecarryingabinary signalof1or0tomakeupthe16-bitwordfortheaddress. TheexpansionofmemorylocationsasbitsareaddedtotheaddressisshowninFigure6-3.Iftheaddressis expandedto24bits,16,777,216memorylocationscanbeaddressed;iftheaddressisexpandedto32bits, 4,294,967,296locationscanbeaddressed.Ifeachmemorylocationhasan8-bitpieceofbinaryinformation (calledabyte),then24bitswilllocate16millionbytesofinformation;moreprecisely,16,777,216bytesof memory,butshortenedbyindustryusetoa16-Megabytememory(16MB).Inlikefashion,a32-bitaddress willlocate4.2billionbytesorisa4.2-Gigabytememory(4.2GB). TEAM LRN
86
DigitalSystemProcessing Memoryanddatabus- Address Address Address Address Bits Locations Bits Locations Bits Locations Bits Locations esarethebusesthat 1 2 9 512 17 131,072 25 33, 554, 432 mustbethewidest 2 4 10 1024 18 262,144 26 67, 108, 864 3 8 11 2048 19 524,288 27 134, 217, 728 (tobeabletohandle 4 16 12 4096 20 1,048,576 28 268, 435, 456 thelargestnumberof 5 32 13 8192 21 2,097,152 29 536, 870, 912 6 64 14 16,384 22 4,194,304 30 1, 073, 741, 824 bitsatatime)inorder 7 128 15 32,768 23 8,388,608 31 2, 147, 483, 684 tocarrythememory 8 256 16 65,536 24 16,777,216 32 4, 294, 967, 296 addressesandthe Figure6-3:Memorylocationsvs.addressbits instructionsrequired Figure 6-3: Memory Locations vs. Address Bits bythesystem.Control busesandtimingsignallinesmayhaveonlyasingleline,butinmostcaseshavemultiplelines,buttheir buseshardlyneedtobeaswideastheaddressanddatabuses.
DigitalInformationNomenclatureandTransfer Binarystringsofbitsareidentifiedinanumberofways.Longstringsofbitsarecalledwords.Modern daydigitalcomputersuse16-,32-,and64-bitwords.InFigure6-4aa16-bitwordisshown.Inanybinary representations,themostsignificantbit(MSB)isontheleftofthestring,andtheleastsignificantbit(LSB) isontheright. Agroupof8bits,asshowninFigure6-4a,iscalleda“byte,”andisaverycommongroupingusedto identifymemorycapacity.A1MB(1megabyte)memoryhasastoragecapacityofonemillionlocations withabyte(8bits)ateachlocation.Eventhoughamemorymaybeorganizeddifferently,saytwomillion locationswith4bitsperlocation,thecapacityisstillreferredtoas1MB.Yearsagothis4-bitgroupwas usedextensivelyandcalleda“nibble.” Abyte,oranumberofbytes,isacommonwayofidentifyingotherbinarysignals.Acontrolsignalmay containacertainnumberofbytes.Acodemaybemadeupofwordsthatareeachabyte,oracodemay containanynumberofbits.ThiswillbefurtherclarifiedinthesectiononDigitalSignalRepresentations. MSB
LSB 16-bit word
Byte 2
Byte 1
Two 8-bit bytes
Nibble #4
Nibble #3
Nibble #2
Nibble #1
Four 4-bit nibbles
a.Words,bytes,nibbles MSB
LSB
b.Paralleltransfer MSB X
1
LSB 1
0
0
1
1
0
1
0
1
0
1
0
1
0
1
MSB Y
0
LSB 0
0
0
0
0
0
0
0
0
0
1
After 11 logical shifts to right
X − Right Shift Information Flow Left Shift Information Flow − Y
c.Serialtransfer Figure6-4:Digitalinformationnomenclatureandtransfer TEAM LRN
87
1
0
0
1
ChapterSix
DataTransfers Withinadigitalcomputer,digitalprocessor,digitalsystem,ordigitalcircuit,thebinarybitsthatcarry theinformationmustbetransferredfromplacetoplacetoallowthesystemorcircuittoperformitstask. Figures6-4bandcshowthemethodoftransfer.Figure6-4bisaparalleltransferandFigure6-4cisaserial transfer.Thisdiscussioncentersonthesignalswithinadigitalprocessor,orwithinaself-containeddigital system.FurtherdiscussionofthetransferofdatabetweendigitalsystemsiscontainedinChapter8. InFigure6-4b,allthebitsofbinaryinformationaretransferredatthesametime.Ifitisa16-bitwordas shown,all16bitsaresentfromonelocationtotheotheratthesametime,inparallel.Thehighestspeed digitalprocessorsusetheparalleltransfersonotimeislostinprocessingthebinaryinformationtoactonit. Theserialtransfer,showninFigure6-4c,takeslongerintimetoprocesstheinformation.Asshown,each bitofinformationisshiftedinsequencetoidentifyallthebitsinthe16-bitword.Usingthe16-bitwordas anexample,16clock-shiftingpulsesarerequiredtoidentifyall16bits.Theshiftingofthebitscaneitherbe inarightorleftdirection,asshown,andthereareanumberofdifferenttypesofshifts—alogical,circulate, orarithmetic.
LogicalShifts Aright11-stepshiftisshowninFigure6-4c.AsthebitsareshiftedrighttowardtheLSBposition,adetectioncircuitreceivestheLSBoutputandidentifiesthebitvalueas1or0.Thebitsarriveserially,onebit afteranother,untilall16bitsofthewordareidentified.Inalogicalshift,bitsof0valuesareinsertedatthe MSBpositionastheshiftingoccurs.Foraleftshift,theidentifyingcircuitisattheMSBpositionrather thantheLSBposition,andthebitsareinsertedattheLSBposition.
ArithmeticShifts Manytimestheinstructiontotheprocessormayonlybeforoneshiftbecauseshiftingabinarywordtothe rightdividesthebinaryvalueby2.Likewise,shiftingabinarywordonebitpositiontotheleft,multiplies thebinaryvalueby2.Thesetypesofshiftsareparticularlysignificantinarithmeticoperations.
Example3.ArithmeticShiftLeftforMultiplication Showanexample,usingan8-bitword,todemonstratehowshiftingabinarynumberonebitpositionto theleftmultipliesthebinaryvalueinthenumberby2. Solution: Bit Position Value
128
64
32
16
8
4
2
1
Original No. Value
0
0
0
16
0
4
0
1
Original No.
0
0
0
1
0
1
0
1
32
0
8
0
2
0
0
0
1
0
1
0
1
0
New Value Original number shifted left one bit
=
21
=
42 Insert 0
Chapter 4, Example 3 Illustration
Inarightcirculateshift,thebitvalueintheLSBpositioniscirculatedbackandinsertedattheMSBposition.After16clockshifts,thebitsofthe16-bitwordareshiftedoutandidentified,and,aftertheshifting iscomplete,thesamedataisinthe16-bitwordasbeforetheshiftingprocessbegan.Suchshiftsarevery usefulinarithmeticandlogicalshiftswithoutdestroyingtheoriginaldatapresentbeforetheshifts. Binaryinformationcanidentifybothpositiveandnegativenumbers.Todothis,theMSBofthebinaryword isreservedtobeasignbit.Ifthebitisa0,thebinarynumberispositive;ifthebitisa1,thebinarynumber TEAM LRN
88
DigitalSystemProcessing isnegative.Duringanarithmeticshift,thesignbitintheMSBpositionismaintained.Thus,whenashift occurs,thevalueintheMSBpositionisreinsertedintotheMSBposition,sothatitremainsthesameand thearithmeticvalueofthebinarynumberisnotlost.Examplesfora4-bitcodeareshowninFigure6-5.
When MSB = 1 represents 8 negative numbers
When MSB = 0 represents 8 positive numbers
Binary Signals MSB LSB 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1
Decimal Numbers or or 0 0 0 1 +1 1 2 +2 2 3 +3 3 4 +4 4 5 +5 5 6 +6 6 7 +7 7 8 0 8 9 -1 9 10 -2 : 11 -3 ; 12 -4 < 13 -5 = 14 -6 > 15 -7 ?
Column ASCII bits
1
5, 6, 7
Commands
\ a b c d e f g h i j k l m n o
P Q R S T U V W X Y Z [ \ ] ^ −
p q r s t u v w x y z { | } ~ DEL
Power OFF STOP GO A ON A OFF B ON B OFF RIGHT LEFT FORWARD BACK IDLE SPEED 1 SPEED 2 BRAKE POWER ON
3
4
5
6
7
8
110
001
011
2
4321
Characters @ A B C D E F G H I J K L M N O
101 111
Figure6-5:Digitalsignalscanrepresentnumbers,letters, Figure 6-5: Digital Signals can represent numbers, specialcharacters,commands,andsoforth. letters, special characters, commands, and so forth.
Example4.ArithmeticShiftforRecirculation Showanexample,usingan8-bitword,ofhowarightrecirculateshiftofthesamenumberasthebits inthewordreinsertsthesamewordinaregisterafteruseoftheword. Solution: Working Register
Original 0
0
1
1
1
0
0
1
0
0
0
0
0
0
0
0
0
1
1
1
0
0
1
0
0
0
0
0
0
1
0
0
1
1
1
0
0
1
Recirculate After 4 shifts to right 1
0
0
1
0
Recirculate
After 8 shifts to right 0
0
1
1
1
Recirculate
Parallelvs.Serial
Chapter 4 Example 4 Illustration
Onecanseetheparalleltransferofinformationisfastestbecauseittakessignificanttimetoshiftoutthe bitsforidentificationinaserialtransfer.However,thereisasignificanttradeoffinhardwareofincreased circuitry,increasedinterconnections,increasedpowerdissipation,andsoforth.Serialoperationcallsfor onlyonedetectioncircuitattheLSBorMSBpositiontoidentifythebits.Paralleloperationrequiresa circuitforeachbitsothebitscanbeidentifiedallatthesametime.Thismultiplicationofcircuits,interconnections,morepoweroccursthroughoutthesystem. TEAM LRN
89
ChapterSix Thetradeoffthenisonebetweenspeedofoperationversusamountofhardware.ButICprocessing,device andcircuittechnologyishavingatremendousimpactonthistradeoff,asdiscussedinmoredetailinChapter8.TheadvancesbyICsindensityperchip,fasteroperatingspeedsandlowerpoweroperationandnew circuitprotocolsarereducingtheseparationinthistradeoffandserialoperationisgaininginuse.
DigitalSignalRepresentations Figure6-5detailsthatbinarybitsindigitalinformationcancommonlyrepresentnumbers,letters,charactersandcommands.A4-bitbinarycodeisshownthatcanrepresent16differententities.The16different entitiescanbethenumbersfrom0to15(1stcolumn);ortheycanbeeightpositivenumbersfrom+0to+7, andeightnegativenumbersfrom–0to–7(2ndcolumn).Asexplained,theMSBofthecodeisusedtotell whetherthenumberispositiveornegative.Orthe16differentcodescanbeusedtoidentifythenumbers from0to9andsixspecialpunctuationcharacters(3rdcolumn).Orthe16differentcodescouldbeusedto identify16differentcommands(8thcolumn). Inordertoidentifymorecharactersandsymbols,morebitsmustbeaddedtothecode.Asanexample,The AmericanStandardCodeforInformationInterchange(ASCII),mentionedbrieflyinChapter1andcontainedinitscompleteforminChapter8,usesa7-bitcode.Itidentifies52upperandlowercasealphabetic characters,10numbersfrom0to9,34specialdatatransferandTeletypecommands,and32otherspecial charactersforatotalof128. Columns4,5,6and7ofFigure6-5arethe52upperandlowercasealphabeticcharactersandotherspecial symbolsthatareidentifiedintheASCIIcode.Column3,mentionedpreviously,isalsousedintheASCII code.Tofilloutthe7-bitcode,column3hasbits5,6and7at110,andcolumns4,5,6,and7havethemat 001,011,101,and111,respectively.Asthecombinationofthe5,6,and7bitschange,theidentitiesofthe 16codeschangetonewcharacters,numbersorsymbols.
Example5.ASCIICode Identifywhatthegiven7-bitcodesrepresentusingFigure6-5. Solution: Code
Bit
7
6
5
4
3
2
1
Data Represented
1.
0
1
1
0
1
0
1
5
2.
1
0
0
1
0
1
0
J
3.
1
1
0
0
1
1
1
g
4.
0
1
1
1
1
1
1
?
Whathasbeendemonstratedisthatwithindifferentdigitalsystems,thebinaryinformationcanrepresent Chapter 4 Example 5 Illustration manydifferentthings—numbers,characters,symbols,commands,instructions,andsoon.Systemdesigners willdefinehowthecodesareusedinparticularsystems.
Clock,TimingandControlSignals Asstatedpreviously,acomputerprogramisaseriesofstepsthatadigitalprocessormustexecuteinsequenceinordertoaccomplishataskdictatedbytheprogram.Thesestepsinsequenceoccuratparticular settimesdictatedbythetimingandcontrolsignals.Withineachstep,instructionsaredictatinghowelectroniccircuitsareoperatingtoperformthefunctionscalledforbytheprogram.Theinstructionsoccurat specifictimesandthecircuitoperationoccursatspecifictimescontrolledbythetimingandcontrolsignals. TEAM LRN
90
DigitalSystemProcessing
Clock Theheartofthetimingcircuitsistheclock.Itssourceisusuallyacrystal-controlledoscillatorthatgeneratessignalsataveryprecisefrequency.Itssignaloutputisformedintorectangularpulsesthathavevery fastrisingandfallingedges.TypicalpulsesareshowninFigure6-6a.Therisingandfallingedgesofthe clockpulseprovideprecisetimesforcontrollingelectroniccircuitaction.Theclockmayhavejustone seriesofpulseslikephase1(Φ1),oritmayhaveadditionalphasesasshowninFigure6-6a.Theadditional phasesprovideadditionaltimingsignalsforthecontrolofcircuits.AsshowninFigure6-6a,someofthe circuitscontrolledbytheclocktriggerontherisingedgeoftheclockpulse,whileothercircuitstriggeron thefallingedgeofthepulse.Suchalternativesinthetriggeringofcircuitsprovideawideselectionandflexiblemeansfortimingtheoperationofelectroniccircuits.
GatedLatch Aspecificexampleof howelectroniccircuits aretimedisshowninFigure6-6b.Theelectronic circuitshowniscalled agatedlatch.Itisused fortemporarystorageof digitaldata.Theinputs tothegatedlatcharethe binarysignalD(either1 or0),andtheclock.The outputsareQandQ', whicharecomplementary toeachother—ifQ=1, Q'=0orviceversa.A signalthatappearsonD isonlystoredinthelatch andappearsonQafterit is“clockedin,”i.e.,the clockhasappearedand hastimedintheDsignal. AsshowninFigure6-6b, QonlychangesafterD changesandaclocksignaltimesthechangeinto thelatch. Thelatchreceivesits namefromthefactthat itisatemporarystorage electroniccircuitthat latchesontodataand holdsit.Thegatedlatch meansthatdataisgated inataparticulartime.
rising edge
Phase 1 (Φ1) falling edge
Phase 2 (Φ2)
Some circuits are triggered (timed) on this edge
Phase 3 (Φ3)
Some circuits are triggered (timed) on this edge
Phase 4 (Φ4)
a.Clocksignals
Clear
D
Q
Clock Q' Before clock
nD ation o ut inform pear on Q b s e g D chan does not ap clocked is g until it e trailin in by th f clock o e g d e
After clock
Gated Latch (clocked D Flip-Flop) D Q Q' Q Q' 0 0 1 0 1 1 0 1 1 0 Truth Table
1 0 1 Q 0 1 Latch triggers Q' 0 here Clock 1 0 1 2 3 4 5 6 7 8 9 10 t=0 time D
b.Timingofsignalsatgatedlatch A 1 on line for Read Memory Clock
C=AB A B AND Gate A 0 0 1 1
A
C
B 0 1 0 1
Output Control Line
C 0 0 0 1
B C
1 Read Memory Signal
0 1 0
Clock
1
Timed Control Signal for Read Memory
0
Truth Table
t=0
1 2 3 4 5 6 7 8 9 10
time
c.TimedcontrolsignalusingANDgate Figure6-6:Clocksignalsfortimingandcontrol TEAM LRN
91
ChapterSix Atruthtable,showninFigure6-6b,identifiestheoutputQandQ’valuesforeachDinputvalue.Itidentifiesthestateofthesignalsbeforeandaftertheclock.
ANDGateControl AnotherexampleofsignaltimingisshowninFigure6-6c.Herea2-inputANDgateisusedtotimea controlsignal.Thecontrolsignalrequiredtellsamemorytoreadinformationfrommemory.Theaddress oftheinformationhasbeenreceivedbythememoryanddecodedpriortothereceiptofthecontrolsignal. AnANDgateisusedtoprovidethememoryreadsignalataprecisetime.Asthetruthtableshows,both inputstotheANDgatemustbea1fortheoutputtobea1.Ifbothoroneinputisa0,theoutputisa0.By placingthememoryreadsignalontheAinputtotheANDgate,whenitisa1,thememoryistoberead. However,thecontrolsignaltoactuallytellthememorytoreadwillnotoccurontheoutputoftheANDgate untiltheclocksignalisa1.Asaresult,thememoryisreadataprecisetimedeterminedbytheclock.The readsignalontheinputtotheANDgateoverlapstheclocksignalintime,andcanvarysignificantlyintime positioninrelationshiptotheclockandstillbetimedcorrectly.TheANDgateoutput,thememoryread pulseinthiscase,turnsouttobethesamewidthastheclockpulse. Thefactthataclockmayhavedifferentphasesaddstotheflexibilityofthetimingandcontrolsignals.For example,theclockusedinFigure6-6bmightusePhase2,whiletheclockusedinFigure6-6cmightbe Phase4.Thisdemonstratestheflexibility,mentionedpreviously,thatadesignerhastotimethesystemcircuits.
Interrupts Asignalthatcontrolsadigitalprocessoratunexpectedorrandomtimesiscalledaninterrupt.Itinterrupts thedigitalprocessorfromwhatitisdoinganddirectsittodosomethingdifferent,asindicatedbytheinterruptsignal.ASTOPsignalterminateswhatevertheprocessorisdoing.Itusuallyoccursatrandomtimes dependingontheneedtoshutdowntheprocessor.Ormaybetheprocessorisfollowingaprogramand inputsignalsarerequired.Whentheinputsareavailable,theinputcircuitsnotifythedigitalprocessorthat theinputsarepresent.Thisinitiatesaninterrupttotheprocessor,whichhaltswhatitisdoingandinputsthe data.Afterthedataisinputted,theprocessorcontinuesfromtheplaceitwasinterrupted.TheCPUkeeps trackofwheretheprocessoriswhentheinterruptoccurred. Similaractionoccursattheoutputs.Theprocessorisrequiredbytheprogramtooutputdatatoanexternal unit.TheprocessoraddressestheI/Oandselectsanoutput.TheoutputcircuitssendaninterrupttotheCPU tosignifythattheoutputisready.Theinterruptedprocessorswitchestoaroutinetooutputthedata.When thetransfertotheoutputiscomplete,theprocessorreturnstotheprogramlocationdirectlyafterthelocationatwhichitwasinterrupted. Theapplicationofadigitalprocessormaybedictatedbyitsresponsetoaninterrupt.Someprocessorsrespondveryquicklytointerruptssothattheoverallperformancetoexecuteitsprogramandcompleteatask isnotaffected.Whileotherprocessorsmaybeslowtorespondtointerrupts,and,therefore,ifanapplicationdependsonmanyinterrupts,theoverallperformanceoftheprocessorwillbeslowedagreatdeal.The ultimatespeedatwhichtheprocessorcanaccomplishthetaskisseverelylimited.Somedigitalprocessors onlyrespondtoaninterruptwhentheywantto,notrandomlyorunexpectedly.Mostmoderndigitalprocessorsrespondquicklytointerruptsthatoccuratrandomandunexpectedtimes.
StatusBits Digitalprocessorsoperateusingcontrolsignalsderivedfromtheconditionofcheckbitscalledstatusbits. Statusbitsarestoredinaregister.Aregisterisachainoflatchesstrungtogethertotemporarilystoreaset numberofbits;asanexample,a16-bitregisterstores16bits.Mostregistersstorethenumberofbitsinthe wordbeingusedthroughoutthedigitalsystem.Thestatusregisterissomewhatdifferent.Itholdsavariety TEAM LRN
92
DigitalSystemProcessing ofdifferentbitswherethestateofeachbitissomewhatindependentoftheotherbitsintheregister.Many ofthebitsaresetindependentlyandtheirvaluedependsontheresultofaparticularprocessoroperation. Forexample,whatwasthesignofanumberasaresultofanarithmeticoperation—positiveornegative?A statusbitissetaftertheoperationisexecutedtoindicatetheresult.Wastheresultofanarithmeticoperationgreaterorlessthanzero?Astatusbitissettoindicatetheresult.Wasthereacarryoraborrowwhenan arithmeticoperationwasperformed?Isthenumbertoolargeforthedigitalsystemtohandle?Thesettingof statusorconditionbitsaftersuchoperations,andthecheckingofthebitsbytheprocessor,contributetothe controloftheoperationofthedigitalprocessorasitexecutesitsprogram.
Example6.StatusRegister TheNbitofastatusregisterissetwhentheresultofanarithmeticoperationisnegative.Showan exampleofhowthisoccurs. Solution: Result of an arithmetic operation
Working Register 1
0
1
1
Status Register
0
1
1
1
The MSB being a 1 indicates the value in register is negative. If it is a 1, logic circuits test it
MoreAboutSoftware
N
Z
C
And sets the N bit in status register to a 1
Chapter 4 Example 6 Illustration
ReferagaintoFigure6-4forashortreview.Thedigitalinformationflowingthroughadigitalprocessor flowsasagivencombinationofbits—a32-bitaddresscode,a16-bitinstructioncode,oran8-bitcharacter code.Circuitsthatidentifyanddecodethedigitalinformationmustidentifythevalueofeachbit(eithera1 ora0)andactasaresultofthevaluetodecodetheinformation.Asstatedpreviously,theprogramthatthe processorfollowsisaseriesofinstructionsinsequence.Eachinstructionhasagivennumberofbitsand auniquecodeforaparticularinstruction.Theinstructionscomefrommemorytotheprocessoroverthe databus.Insidetheprocessortheinstructionsarestoredtemporarilyintheinstructionregistersothatthe instructiondecodercircuitscandecodethem.Thedecoderevaluatesthebitsandidentifiestheactionthe processormusttaketoexecutetheinstruction. Humanswritethecomputerprograms.Theinstructionstothecomputermustbewritteninalanguagethat humansunderstand;yettheinstructionsthatthecomputerfollowsmustbeindigitalcodesthatthecomputerunderstands.Aconversionisrequiredfromthehumanlanguagetothedigitalcodesthatthemachine (processor)understands.Thedigitalcodethatthemachineunderstandsiscalledmachinecode.Acomputer programwritteninmachinecodeiscalledamachine-languageprogram.
Machine-LanguagePrograms Humanscanwriteprogramsinmachinelanguage.Todoso,theprogrammerwritestheprogramdirectly inthedigitalcodesthatthemachineunderstands.Noconversionisnecessary.Themachinecandecode theinstructionsdirectlyandexecutethemtoaccomplishthetaskrequired.However,thetaskisextremely difficult,tediousandtimeconsuming,andiferrorsaremade,andtheywillberegularly,itbecomesaneven moredifficultandtedioustasktofindtheerrorsandcorrectthem.
Assembly-LanguagePrograms Inordertomakeiteasiertowritetheprograms,themanufacturersofdigitalprocessorshavedesigned theirprocessortorespondtoinstructionsthatareclosertohumanlanguage.Theseinstructionsare calledassembly-languageinstructions.Theyareeasiertounderstandthanmachinecodebutrequirethe TEAM LRN
93
ChapterSix manufacturertoprovideaprogramtoconverttheassembly-languageinstructionsintomachinecode.Such aprogramiscalledanassembler.Acomputerismuchmoreaccurateindoingtheconversion,andbyprocessinganassemblylanguageprogramforaparticularprocessorusingitsassembler,alltheinstructionsare convertedveryaccuratelyintomachinecodeforthatprocessor.
Mnemonics Theoperationoractionthattheassembly-languageinstructioncausestheprocessortoperformisidentified byanabbreviationcalledamnemonic.Theabbreviationusedforthemnemonicgivesastrongsuggestion totheprogrammerwhattheinstructiondoes.Figure6-7ashowsanexampleofarithmeticinstructionsand theirdirectedactions,andgivesthemnemonicthatrepresentseachoftheinstructions.Themnemonicisa shorttwoorthreelettersymbolthatidentifiestotheprogrammertheprocessoractioncausedbytheinstruction.Figure6-7bgivesanideaofwhatothertypesofinstructionsmaybeavailableindigitalprocessors. Arithmetic
Mnemonic
Add Subtract Multiply Divide Absolute Value Negation Shift Increment Decrement
Action
A or AD or ADD S or SU or SB MPY DIV ABS NEG ROL or ROR INC or INR DEC or DCR
Addition of two binary codes Subtraction of two binary codes Multiply two binary codes Divide two binary codes Take absolute value of a binary number Change sign of a binary number Shift left or shift right Add 1 to binary code Subtract 1 from binary code
a.Exampleofmnemonicsforarithmeticinstructions Logical
Data Movement
Branch
Comparison
AND OR NOT XOR
Move Load Store
Unconditional Conditional Subroutine
Less than Greater than Equal
b.Examplesofotherprocessorinstructions Figure6-7:Examplesofdigitalprocessorinstructionset
Operands Inanassembly-languageinstruction,theinstructionitselfdescribestheoperationtobeperformed,butdoes notsaywhatistobeoperatedon;therefore,operands(whatistobeoperatedon)mustbeaddedtothe instructions.Forexample,theinstruction: MovA,B ThemnemonicMOVmeansthatamoveoperationistobeperformedandtheoperandsareregisterA andregisterB.ThecontentsofregisterAaretobemovedtoregisterB.SupposethatregisterBistheprogram counter;therefore,itcontainsthememoryaddressofthenextinstructionofaprogramorsubroutine.ByloadingregisterAwiththeaddressofthefirstinstructionofaprogram,movingthecontentsofregisterAtoregister Banewprogramisstarted.IncrementingregisterB(subtractingonefromitscontents)withtheinstruction: IncB, causestheprocessortosteptothenextinstruction.Aftertheinstructionisexecuted,theprogramloopsback totheIncBinstructionandtheprocessorstepstothenextinstruction.Theprocessorstepsthroughaddressesoftheinstructionsinsequencetoexecutetheprogram. TEAM LRN
94
DigitalSystemProcessing
SophisticatedProgrammingLanguages Thewritingofacomputerprogramtoperformataskconsistsoforganizingthedigitalprocessorinstructionsintothecorrectsequence.Itisapaperprocessthatdoesn’trequirethebuildingofanyhardware,but justunderstandingtheprocessor’sinstructionsandusingthemtomanipulateexistinghardwaretoperform thetaskrequired.Thus,programsarecalledsoftware,andpeoplethatwriteprogramsarecalledsoftware engineersorjustprogrammers.Itistheobjectiveofprogrammerstowritetheirprogramsinalanguage asclosetohumanlanguageaspossible.Theywouldalsoliketolearnaparticularprogramminglanguage andnotberestrictedtousingitonlyforoneprocessor.Theywouldliketoapplytheirknowledgeofthe languagetootherprocessorssolvingotherapplicationproblems.Tosatisfythisneed,sophisticatedprogramminglanguageshavebeendeveloped. Sophisticatedprogramminglanguagesareastepupandbeyondassembly-languageprogramming.They are,oncelearned,usedforwritingmanydifferentprograms,usingdifferentprocessors.Suchlanguagesare referredtoashigh-levellanguagesbecausetheyaresomewhatgeneralpurposebecausetheyareusedto programdifferentprocessors. Whateverhigh-levellanguageisusedonethingiscertain,theprogrammustbeconvertedtomachine-languagecode.Inearliertimesthiswasatwo-stepprocess.Firstaprogramcalledacompilerconvertedthe high-levellanguagetoassemblylanguage.Then,anassemblerwasusedtoconverttheprogramtomachine code.Todaymostcompilersconvertthehigh-levellanguagedirectlytomachinecode.Inaddition,many digitalprocessorsaremembersofafamilyofprocessors;thecompilerforaparticularprocessorusually handlesthewholefamilyofprocessors.
SoftwareSummary Figure6-8providesasummaryofprogramming.Adigitalprocessorcanbeprogrammeddirectlyin machinelanguage,butitisverytediousanddifficulttofinderrors.Oritcanbeprogrammedinassembly language,putthroughaspeciallydesignedprogram(anassembler)thatconvertstheprogramtomachine code.Oritcanbeprogrammed Directly in Assembly Language Sophisticated Language usingasophisticatedhigh-level Machine Language Programming Programming general-purposelanguage.The programmustbeputthrougha speciallydesignedprogram(a Compiler Assembler compiler)thatconvertsthehighlevellanguageinstructionsinto machinecodefortheparticular Machine Code Machine Code Machine Code processorused.Fortranwasan earlyhigh-levellanguage.Today, Figure 6-8: Programming Computers Figure6-8:Programmingcomputers “C”,“C+”,UNIX,JAVAarenames ofsophisticatedlanguagesfor writingprograms.
HowPartsofaProcessorPerformTheirFunctions ALU—ArithmeticLogicUnit Thediscussionnowswitchestohowvariouspartsofaprocessorperformtheirfunctions.Thefirstofthese isthearithmeticlogicunit(ALU).AnarithmeticfunctionperformedbytheALUisaddition,shownin Figure6-9.Thecentralelectroniccircuitusedforadditionisanadder,showninFigure6-9a.Thefull-adder hasthreeinputs—thetwobinarynumberstobeaddedandacarryinput.Figure6-9ashowsnotonlythe TEAM LRN
95
ChapterSix MSB
A B Ci carry in
A7 B7
LSB C6
A6 B6
C5
A5 B5
C4
A4 B4
C3
A3 B3
A2 B2
C2
C1
A1 B1
A0 B0
C0
Ci
Full Adder Co carry out A 0 0 0 0 1 1 1 1
INPUTS B 0 0 1 1 0 0 1 1
Co
SUM S
Ci 0 1 0 1 0 1 0 1
OUTPUTS S Co 0 0 1 0 1 0 0 1 1 0 0 1 0 1 1 1
a.Fulladderandtruth table
S7
S6
S5
S4
Carry
C6 1
1
A
0
1 1 0
1
1
0
1 1 0
1
1
B
0
1
1
0
0
1
1
0
S
1
1
1 0
1
1
1
1 0
1
C5
S3
S2
C2 1
C1
S1
S0
1
0
Carry
b.8-bitadderAandB Figure6-9:Theadditionfunction
full-adderblockdiagram,butalsoitstruthtable.Atruthtable,remember,catalogsthestateoftheoutputsfor allthestatesoftheinputs.IfAorBorCiisa1,thesumbitwillbea1.WhenAandCiorBandCiorAandB area1,thesumbitisa0andCowillbea1.WhenAandBandCiareall1s,thesumbitisa1andCoisa1. Figure6-9bshowsan8-bitadderandtheadditionoftwo8-bitbinarynumbersAandB.NotehowtheCo outputofonestageoftheadderbecomestheCiinputtothenextstagetotheleft.Theexampleshowshow thecarrybitisgeneratedandpropagatestodeterminethesumbitatthenextstage.Thespeedofoperation oftheadderisdeterminedbyhowlongittakesthecarriestopropagatethroughtheadder.Usingtheadder multipletimes,plusshifting,providesthemultiplicationfunction.Subtractingisperformedbyaddingthe one’s(1’s)complementofoneofthebinarynumbersinsteadofthenumberitself,andmultiplesubtractions,plusshifting,resultsinadivisionfunction.
ALU—LogicFunctions
A
A
A
C C C Figure6-10showsthreelogic B B functionsthatarenormallyavailAND OR NOT b b b b b b b b ableinanALU.UsingAandB A 0 1 1 1 0 1 1 0 A 0110 0110 0110 4-bitbinarynumbersasexamples, B B 0 0 0 0 1 0 0 1 1100 1100 C 0 1 1 1 1 1 1 1 thelogicoperationsareperformed C 0100 1110 1001 bitbybitgivingtheresultCfrom a.AND,OR,NOTlogic b.ORfunctiontochange LSBtoMSB.A1appearsas bitvalue theresultfortheANDfunction Figure6-10:Logicfunctions onlywhenAandBarea1.A1 appearsastheresultCwhenAorBorbotharea1intheORfunction.Thecomplementoftheinput—a1 ifinputisa0,ora0ifinputisa1—willappearastheresultCfortheNOTfunction.Theelectroniccircuit thatperformstheNOTfunctioniscalledaninverter. 7
6
5
4
3
2
1
0
AnexampleofusingtheORfunctiontosetparticularbitsinabinarynumbertoaparticularvalueisshown inFigure6-10b.Inthe8-bitbinarynumberforA,01110110,bitsb0andb3andb7are0.Theprogram TEAM LRN
96
DigitalSystemProcessing requiresthatbitsb0andb3besettoa1.ByperforminganORfunctionbetweenAandB,whereBisthe binarynumber00001001,theresultCwillhavebitsb0andb3settoa1.Thebitsthatwere1sinBwillbe settoa1intheresultC.
MemoryandInput/Output Input Data or Output Data Figure6-11ashowsthe Read/Write typicalinterfacebetweena Memory Input/Output microprocessorandmemory. Thiscorrespondstowhat Address Data Data wasshowninFigure6-1,but Address (selects I/O) detailsitjustformemory. Memory I/O Enable Microprocessor Enable Microprocessor Theaddressbuscarries thebinarycodeputoutby themicroprocessorforthe Figure6-11:Datatoandfrommemoryandinput/output addressofinformationin memory.Thememorysizedeterminesthenumberofbitsinthecode.Thedatabuswilleitherhavedata onitthatisputtherebythemicroprocessortostoreinmemory(writetomemory),oritwillhavedataor instructionsthatcomefromtheaddresslocation(readingfrommemory)tothemicroprocessor.Whether thememoryisbeingwrittentoorreadfromiscontrolledbytheread/writesignal.Inaddition,whenever memoryistobeused,whetherwritingorreading,anenablesignalissenttomemorytoactivateit.The read/writeandenablesignalsaretimedcontrolsignalsoperatingatpreciselydesignedtimes.
Input/outputorI/OcircuitsoperateverysimilartomemoryasshowninFigure6-11b.Themicroprocessor sendsoutanI/OaddressontheaddressbustospecifywhichI/Oistobeused.Atthesametime,acontrol signaltellstheI/Othatitwantstoinputdatatothemicroprocessoroverthedatabus;orthatitwantstooutputdatathatthemicroprocessorisplacingonthedatabus.Aswithmemory,timedcontrolsignalenables theI/Ocircuits.Theyarenotactiveuntiltheenablesignalarrives.
AddressingModes Programinstructionstelladigitalprocessorwhattodo,wheretofindtheinformationitistousewiththe instruction,andwheretoputtheresultaftertheinstructionisexecuted.Addressesoraddressingisneeded todirecttheprocessortothecorrectlocation.Addressingmodesarethemeansbywhichtheinstruction indicatestheaddress.Theyarethedesignedwaysthattheinstructiontellstheprocessorhowtolocatethe informationitneedstousewiththeinstruction.Thereareseveralcommonaddressingmodesfordigital processors.FivedifferentonesareshowninFigures6-12,13,14,15and16.
ImmediateAddressing ImmediateaddressingisdiagrammedinFigure6-12.Theprogramcountercontainsamemoryaddressthat pointstotheoperationcode(opcode)oftheinstruction—theoperationtheinstructionwantstheprocessortoperform.Followingimmediatelyaftertheopcode,inthenextmemorylocation,isthedataonwhich theinstructionwilloperate.Soiftheinstructionisaddressedwithimmediateaddressing,thecodethat describestheoperationtobeperformedis Memory inthememorylocationaddressedbythe Prog. Counter (instruction) The op code is contained in the memory location pointed to by contentsoftheprogramcounter,andthe OP Code Memory Loc. the PC followed, in the next dataisinthenextmemorylocation.There memory location, by the data + that is to be used. isrelativelylittledecoding.Theinstruction Data knowsimmediatelywherethedata(operFigure 6-12: Immediate Addressing Figure6-12:Immediateaddressing and)islocated. TEAM LRN
97
ChapterSix
RegisterAddressing Figure6-13diagramsregister addressing.Herethe dataisnotconProg. Counter tainedinmemory Memory Loc. locationsbutin registers.Theinstructioncontains theopcodeand specifiesinwhich registerthesource dataislocated and,ifneedbe, theregisterforthe destinationdata.
RegisterIndirect Addressing Figure6-14diagramsregisterindirectaddressing.In registerindirectaddressing, insteadofspecificregisters containingthedatatobe operatedonasinFigure 6-13,nowthespecificregisterscontainthememory addressofthedata.Thus, loadingdifferentmemorylocationsinregisterscausesthe processortooperateondifferentdatastoredinmemory.
Memory (instruction)
Source
OP Code S, D
Decode
Register #
Data (operand)
Destination Register #
Data (operand)
The source and destination data are contained in registers. The instruction contains the op code and specifies a register as a data location. In the case shown, data is contained in a register for both the source and destination.
Figure6-13:Registeraddressing Figure 6-13: Register Addressing
Prog. Counter
Memory (instruction)
Memory Loc.
OP Code S, D
Source Decode
Register # Destination Register #
(operand) Data
Data − D
(operand) Data
Data − S
Instead of the register containing the data as in register addressing, the register contains the memory address of the data. Thus, by loading the register with different memory locations, different data is operated on by the instruction.
Figure6-14:Registerindirectaddressing Figure 6-14: Register Indirect Addressing
IndexedAddressing Figure6-15diagramsindexed addressing.Thenextmemorylocationaftertheopcodecontainsan index.Theaddressofthedatato beusedisthesumofavalueina registerandthevalueoftheindex. Theinstructionisusedseparately forthesourceandforthedestination.Indexedaddressingisused extensivelyfordatathatisgrouped togetherinmemory.Theprogram canbemodifiedquicklytoselecta differentsetofdatabychangingthe indexintheinstruction.
Prog. Counter
Memory (instruction)
Memory Loc.
OP Code
Decode
Index
+
+
(operand) Data
Register #
S/D
For index addressing, the address of the data is the sum of a value contained in a register and the value of the index. The selection of data addresses that appear in groups can be modified quickly by changing the index.
Figure6-15:Indexedaddressing Figure 6-15: Indexed Addressing TEAM LRN
98
DigitalSystemProcessing
Example7.RegisterIndirectAddressing Showanexampleofregisterindirectaddressing. Solution: Program Counter 0
0
0
0 0
0
1
0
Address 00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111
D E C
Mov @ R1, @ R2
O D
Source
Destination
REGISTER R1 1 0 0 0 0 0 0 1
REGISTER R2 1 0 0 0 1 0 1 0
E
10000001 0 1 1 1 0 1 1 1
The contents of memory location 10000001 are moved to memory location 10001010
10001000 10001001 10001010 0 1 1 1 0 1 1 1
TheprogramcounterpointstothememoryaddresswheretheinstructionMOV@R1,@R2islocated. R1andR2areregisternumbersandthe@signindicatesthatthecontentsoftheregisteristheaddress inmemorywheretheinformationonwhichtheinstructionistooperateislocated.Theinstruction, withMOVastheopcode,saysmovethecontentsofthememorylocationwhoseaddressisthecontentsofR1(thesource)tothememorylocationwhoseaddressisthecontentsofR2(thedestination).
DirectorSymbolicAddressing Figure6-16diagramsdirector symbolicaddressing.Inimmediate addressingofFigure6-12,thememorylocationfollowingtheopcode containedthedatatobeoperated on.Indirectorsymbolicaddressing, thenextlocationinmemoryafter theopcodeisanaddressinmemory thatcontainsthedata.
Prog. Counter OP Code
Memory Loc.
+ Memory Loc.
(operand) Data
S/D
As with immediate addressing, the instruction op code is contained in the Instructionsetsfordifferentpromemory location, but now the next word does not contain the data for the cessorsusespecificsymbolsand instruction, but contains a memory address for the data. notationsfortheirinstructionsand Figure6-16:Directorsymbolicaddressing Figure 6-16: Direct or Symbolic Addressing fortheiraddressingmodes.They usuallyarespecifictotheparticularprocessor.InChapter7,therewillbefurtherdiscussionoftheaddressingmodesusedfortheMSP430 familyofmicrocontrollers.
Summary Thiscompletesthediscussionaboutthebasicoperationofadigitalprocessor,someofitsspecificfunctions,andhowtheprocessorismadetodowhatisinstructedbyaprogramtoperformadesiredtask.Inthe nextchapter,thediscussioncentersonthedetailsofprogrammingtheprocessor. TEAM LRN
99
ChapterSix
Chapter6Quiz 1. Adigitalprocessor,morecommonlycalledadigitalcomputer,hasaunitthatisthebrainofthe systemcalledthe: a. I/O—input/output. b. permanentmemory. c. temporarymemory. d. CPU(centralprocessingunit). 2. Eachdigitalprocessorismanufacturedtorespondto: a. awidevarietyofdifferentsetsofinstructions. b. aparticularsetofinstructions. c. onlyoneortwoinstructions. d. onlyinput/outputinstructions. 3. Adigitalprocessorrespondstoaprogramthatis: a. designedtorandomlyoperatetheprocessorinmanydifferentsequences. b. alwayschangeseverytimeitrunstheprocessor. c. asetofoperationsinaparticularsequencetoaccomplishatask. d. notneededbytheprocessorformosttasks. 4. Theinstruction/databusisused: a. tosendaddressestolocateinstructionsanddatatobedeliveredtotheCPU. b. toidentifyinputsandoutputstoreceiveoroutputdatafortheCPU. c. tosendtiminginformationthroughoutthesystem. d. aandbonlyabove. e. conlyabove. 5. Clocksignalsinthedigitalprocessor: a. preciselycontrolthetransfer,manipulationandstorageofinformationthroughouttheprocessor. b. mustbeveryaccurateintime. c. areaseriesofrepetitivepulsesthathavefastriseandfalltimes. d. allofabove. e. aandconlyabove. 6. Powersystemsindigitalprocessors: a. musthaveveryaccuratevoltageregulatorsandgoodpowerdissipationcontrol. b. requirenoprecisevoltageorcurrentcontrol. c. requirelittleconcernforpowerdissipation. d. operatewithhighvoltageandhighcurrent. 7. Thedevicesthathavecontributedmosttolowpowerdissipationindigitalprocessorsare: a. powertransistors. b. bipolarlogictransistors. c. CMOS—complementary-metal-oxide-semiconductor—integratedcircuits. d. amixofbipolarandMOSdevices. 8. Thedatabuscarriestomemoryadigitalcoderepresenting: a. theinstructionaddressandthedataaddress. b. onlytheinstructionaddress. c. onlythedataaddress. d. noneoftheabove. TEAM LRN
100
DigitalSystemProcessing 9. Thearithmeticlogicunit(ALU)intheCPU: a. providestheI/Ocapabilities. b. providestheclockcapabilities. c. providesthestoragecapabilities. d. providesthelogical,computational,anddecisionmakingcapabilities. 10.Read-onlymemory(ROM),random-accessmemory(RAM)andregistersare: a. logicalcircuitscontainedintheCPU. b. typesofmemorythatareormaybecontainedinaCPU. c. datatransmissioncircuitscontainedinaCPU. d. I/OcircuitscontainedinaCPU. 11.Amicrocontrollerunit(MCU): a. isanindustrialcontrolcomputermadeupfromindividualICs. b. isthesmallestpossiblemicrocomputer. c. isamicrocomputerICthatisadaptedtotheindustrialcontrolmarket. d. isacomputermadeupofindividualICs,butdesignedforlow-poweruse. 12.TheMSB(mostsignificantbit)ofawordis: a. isthesecondbitinthecoderepresentingtheword. b. istheleft-mostbitinthecoderepresentingtheword. c. istheright-mostbitinthecoderepresentingtheword. d. isthemiddlebitinthecoderepresentingtheword. 13.Inaparalleldatatransfer: a. allbitsarriveatapointatthesametime. b. allbitsdonotarriveatapointatthesametime. c. allbitsaredelayedonebitatatime. d. allbitsarriveatapointoneafteranother. 14.Inaserialdatatransfer: a. allbitsarriveatapointatthesametime. b. allbitsarecollected,delayed,andthenarriveatthesametime. c. allbitsaredelayed,thenarriveatapointatthesametime. d. allbitsarriveatapointoneafteranotherinsequence. 15.TheASCIIcodecanidentify: a. numbersonly. b. lettersonly,notspecialcharacters. c. numbers,letters,specialcharacters,commands. d. commandsonly. 16.Clocksignalsinsideadigitalprocessor: a. maytriggerelectroniccircuitsonlyonthefallingedge. b. maytriggerelectroniccircuitsintoactiononeithertherisingorfallingedgeoftheclockpulse. c. maytriggerelectroniccircuitsonlyontherisingedge. d. don’ttriggerelectroniccircuitsontherisingorfallingedges. 17.Aninterruptsignaltoadigitalprocessor: a. speedsuptheoperationofadigitalprocessor. b. controlsadigitalprocessoratunexpectedorrandomtimes. c. actsjustlikeanyotherdigitalprocessorcontrolsignal. d. noneoftheabove. TEAM LRN
101
ChapterSix 18.Amnemonicisa: a. shorttwoorthreelettersymbolthatrepresentsaprograminstruction. b. randomsetoflettersymbolsthatvariescontinuously. c. longsetoflettersymbolsthatisaninstructioninitself. d. symbolthathasnorelationshiptoassembly-languageprogramming. 19.Programswritteninhigh-levellanguages: a. canbewrittenfordifferentprocessorsusingthesamelanguage. b. mustbeconvertedtomachinecodetoruntheprocessor. c. useacompilertoconvertthehigh-levellanguagetomachinecode. d. allofabove. e. conlyabove. 20.Addressingmodesforadigitalprocessor: a. arealwaysimmediateaddressing. b. arethedesignedwaystheinstructiontellstheprocessorwhattodo. c. arethemeansbywhichtheinstructionindicatestheactiontobetakenbytheprocessor. d. conlyabove. e. bandconlyabove.
Answers:1.d,2.b,3.c,4.d,5.d,6.a,7.c,8.a,9.d,10.b,11.c,12.b,13.a,14.d,15.c,16.b,17.b,18.a,19.d, 20.e. TEAM LRN
102
C H APTER 7
ExamplesofAssembly- LanguageProgramming Introduction Manytimestheeasiestwaytounderstandhowtodosomethingistoworkwithexamples.Thatisthesubjectofthischapter.Bylookingatsmallsubprogramsthathavebeenwrittentoaccomplishspecifictasks, thereaderwillbeintroducedtoassembly-languageprogramming.Theobjectiveistoprovideabaseof understandingofhowanassembly-languageprogramisformulatedsothatprogramscanbedeciphered,at leasttoobtaina“feel”forwhattheprogramistryingtoaccomplish.Innowaywillthischapterbeathoroughcoverageofassemblylanguage,itsformat,itsdetail,itsuniqueness,but,hopefully,bytakingsmall segmentsofprogramsanddiscussingthem,linebyline,enoughinformationwillbetransmittedtoaccomplishthebasicunderstandingdesired.
AProcessorfortheExamples Inordertobespecificabouttheprogramsdiscussedandthetasks,aTexasInstrumentsMSP430Familymicrocontrollerhasbeenchosentousefortheprogrammingexamplesbecauseitisreadilyavailable, well-supportedwithdocumentationandapplicationsinformation,andhasrelativelyinexpensiveevaluation tools.Thefamilyofmicrocontrollersisdesignedspecificallyforindustrialcontrol,instrumentation,and measurementtaskswithlow-power,extendedbattery-lifeapplicationsasprimedesignobjectives.These specificationsarenotnecessarilyimportanttoitschoiceforthischapter.Rather,theeasy-to-understand architecture,instructionset,andfamilystructurecontributedsignificantlytotheselection.
AbouttheMSP430Family
JTAG/Debug
InTexasInstruments’words,“TheMSP430devicesconstituteafamilyofultralow-power,16-bitRISC microcontrollerswithanadvancedarchitectureandrichperipheralset.Thearchitectureusesadvancedtiming anddesignfeatures,aswellasahighlyorthogonalstructuretodeliveraprocessorthatisbothpowerfuland flexible.”Thearchitectureiscalled“vonNeumann”sinceallprogram,datamemoryandperipheralssharea commonbusstructure.RISCmeansreducedinstructionsetcomputer,anddefinesaspecificdesignapproach forthemicrocontroller.Thereareonly27 coreinstructions,which,throughthetechFlash/ Oscillator RAM Peripheral Peripheral Peripheral ACLK ROM System (Data) (I/O Port) (I/O Port) (I/O Port) niqueofcombiningcoreinstructions—called Clock SMCLK (Program) MCLK emulation—isexpandedintoasetof51 instructions.Thecoreinstructionsarebuilt MAB 4-Bit MAB 16-Bit CPU intohardware,whiletheemulatedinstructions Incl. R/W 16 Reg. areformedbytheassembler(theprogramthat MDB 16-Bit Bus MDB 8-Bit interpretstheassembly-languagemnemonics Conv. JTAG andproducesmachinecode). ACLK SMCLK
FamilyBlockDiagram AMSP430Familysystemblockdiagramis showninFigure7-1.Notethe16-bitmemory addressbus(MAB),the16-bitmemorydata
Watchdog Timer
Peripheral (Timer_B)
Peripheral (Comparator)
Peripheral (USART)
Peripheral (USART)
Figure 7-1: MSP430 Family Block Diagram Figure7-1:MSP430familyblockdiagram Courtesy of Texas Instruments Incorporated
CourtesyofTexasInstrumentsIncorporated. TEAM LRN
103
ChapterSeven bus(MDB),andthebusconversionfortheI/O,USARTandcomparator.InChapter10,theMSP430F1232, partofafamilyofMSP430F12XXdevices,willbeusedinanapplication.HowtheMSP430F12XXdevicesvaryinthefamilyisshowninTable7-1.
MSP430F12XXDevicesoftheFamily
Memory
430Device F122
Main
Flash
RAM
I/O(8)
BOR
WDT
TA
C
USART
ADC
4kB
256B
256B
3
X
X
X
1
slope
F123
8kB
256B
256B
3
X
X
X
1
slope
F1222
4kB
256B
256B
3
X
X
X
1
SAR10
F1232
8kB
256B
256B
3
X
X
X
1
SAR10
Table7-1:DevicesoftheMSP430F12XXfamily
TheMSP430F12XXdeviceshaveprogrammemorythatisFlashmemory.Thedevicesareidentifiedwith aFinthedevicenumberasshowninTable7-1.TheFlashmemory,whichismadeupofalargemain memoryandasmallerinformationmemory,providesin-systemprogrammabilitythatpermitsflexiblecode changes,and,forremotesystemsthatarebatteryoperated,fieldupgrades.Flashmemoryiselectronically erasableprogrammableROM(EEPROM),andisprogrammableanderasedbyapplyingavoltage.The MSP430F12XXdevicesvaryinprogrammemorysizefrom4kBto8kB,andallhavethesamesizeRAM. Theyhavethree8-bitI/Os,awatchdogtimer(WDT),and16-bitPWMtimer(TA),aUSARTcommunicationinterface,andADCs.Somehavenocomparators(C),somehavebrownoutreset(BOR),andtheADC variesfromslopetoSARs.Theyarepackagedin28-pinpackages.Thebrownoutresetisafunctionthat resetsthemicrocontrollerwhenthepowersupplyvoltagereachesacriticallowvalue.Whenthepowersupplyvoltageisre-established,themicrocontrollerstartsagainfromtheRESETcondition.
MSP430FamilyCharacteristics TheMSP430F1XXXfamily,whichextendsthroughtheF13x,F14x,F15x,andF16xdevices,includesdeviceswithmoreUSARTsandtimers,hardwaremultipliers,12-bitADCs,anI2Ccommunicationsbus,and SVSs—supplyvoltagesupervisors.Thesedevicesarein64-pinpackages. Anotherfamilygroup,theMSP430F4XXdevices,extendsthefamilyinto64-pinand80-pinpackages.The deviceshaveupto60kBofprogrammemoryand2kBofRAM,andmosthave12-bitADCs.Allhave LCDdrivers—from96to160segments. AsegmentofthefamilyisbasedonROMprogramming,theMSP430CorP3XXdevices.Theyhave similarLCDdriverstotheF4XXdevices,butdonothaveFlashmemory.Therearedeviceswith32kB ofprogrammemoryand1kBofRAM,butthemostexotichave6-channel,14-bitADCsthatarepackagedin64-pinpackages.Otherdevicesarein100-pinpackagesandhave32kBofprogrammemory,1kB ofRAM,an8-bitintervaltimer,a16-bittimerA,aUSART,andahardwaremultiply.Suchavarietyof devicesallowthedesignerofcontrolsystemsawidechoiceofdesignoptions.
TheCPU TheCPUforthefamilyisthesame.Asmentionedpreviously,itisa16-bitRISCCPU.Itconsistsofa 16-bitALU,16registersandinstructioncontrollogic.TheregisterarrangementisshowninFigure7-2a. Notethecommonmemoryaddressbus(MAB)andmemorydatabus(MDB).Fouroftheregistersare forspecialpurposes:programcounter,stackpointer,statusregisterandconstantgenerator.Therestare TEAM LRN
104
ExamplesofAssembly-LanguageProgramming general-purposeregisters.The constantgeneratorsupplies instructionconstants,andisnot usedforstorage.Thesixteen fully-addressable,single-cycle 16-bitregistersandorthogonal architectureprovidesversatilityandsimplicityinsystem applications.
ProgramMemoryand DataMemory Amapofmemoryavailablefor theMSP430familyisshownin b.Overallmemory Figure7-2b.Thereare64KB (65,536)ofaddressablememory spacesdividedovertheaddress xxxAh ••• spacesfrom0tohexadecimal xxx9h 14 . . Bits . . 9 8 15 Word A 0FFFFh(1111111111111111 xxx8h 7 6 . . Bits . . 1 0 xxx7h Byte instraightbinary).Thespecialxxx6h Byte functionregistersandperipheral xxx5h Word (High Byte) Word B moduleaddressesarefrom0 xxx4h Word (Low Byte) to01FFh.Recallthatanhafter xxx3h ••• theaddressnotationmeansitis inhexadecimalformatandthat c. Bits, Bytes and Words in a Byte-Organized Memory 01FFhisreallya16-bitword Courtesy of Texas Instruments Incorporated c.Bits,bytesandwordsina a.TheRISCCPUanditsregisters withbitsof0000000111111111. byte-organizedmemory Figure 7-2: CPU, Registers and Memory Map Inhexadecimalnotation,when Figure7-2:CPU,registersandmemorymap thehexadecimaladdressstarts CourtesyofTexasInstrumentsIncorporated withtheMSBofA,B,C,D,Eor F,azeroisplacedinfrontofthe hexadecimalvaluetomakesuretheaddressisidentifiedcorrectly,forexample,0BE14h. Thememoryaddresses(memoryspace)from0200hto0FFFFharesharedbydataandprogramcodememory.Thespacefrom0FFE0hto0FFFFhisreservedforatableofinterruptvectorsinFlash/ROM(Flash forFdevices)andmoreFlash/ROMisdevotedtoprogram,branchcontroltablesanddatatablesbelowthe address0FFDFh.TheremainingaddressesareusedforFlash/ROMandRAM(randomaccessmemory) andareusedforprogramanddatastorage. Wordsofdata,whichoccupy16bitsor2bytes,areonlylocatedatevenaddresses,whilebytescanbe locatedatoddorevenaddresses.Ifadatawordislocatedatanevenaddress,thelowbyteisattheevenaddressandthehighbyteisatthenextoddaddress.ThetypicalarrangementisshowninFigure7-2c.WordA showstheactualbitsofthehighandlowbytes,whilewordBisjustidentifiedbythepositionofthe“high byte”andthe“lowbyte.” Notealsothatifaperipheralmoduleisa16-bitmodule,itsaddresswillbebetween0100hand01FFh.If itisan8-bitmodule,itsaddresswillbebetween010hand0FFh.Theaddressesfrom0to0Fharereserved forspecial-functionregisters,SFRs.Thefunctionsservedbythevariousportionsofmemoryareshown TEAM LRN
105
ChapterSeven inFigure7-2b,andshowsthatsomeofthefunctionsareonlyaccessiblewith8-bit(byte)or16-bit(word) instructions,whileothersareaccessiblewitheither8-bitor16-bitinstructions. Instructionsarefetchedfromprogrammemorywith16-bitaddresses,whiledatamemorycanbeaddressed eitherusing16-bitor8-bitinstructions.ProgramcodecaneitherbeinFlash/ROMorRAMbecausethe Flash/ROMandRAMareconnectedviathesametwobuses:thememoryaddressbus(MAB)andthe memorydatabus(MDB).Inadditiontoprogramcode,datacanbeplacedintheFlash/ROMsectionofthe memorymap,asignificantadvantagefordatatables.
Peripherals ThevariationofperipheralsisoneofthemajoradvantagesoftheMSP430family.Ageneraloverviewof theperipheralvariationswerepointedoutinthefamilydiscussion,butmorespecificvariationsareshown inFigure7-1.ShownarevariationsoftheavailableI/Oports,aswellasacomparatorandaUSART (UniversalSynchronous/AsynchronousReceiver/Transmitter).Withinthefamily,alsoavailablearedifferentADCs,differenttimers,andevenahardwaremultiplier.Mostoftheperipheralsoperateinbyteformat, andmoduleswith8-bitdatabusesareconnectedbybus-conversioncircuitrytothe16-bitCPU.Mostofthe peripheralsusea5-bitmemoryaddressbus.
OperationControlandOperatingModes Thecontentsofthespecial-functionregisters,mentionedpreviously, controltheoperationofthedifferent MSP430functions.Thebitscontainedintheregister(s)selectsystem operation,enableinterrupts,provide informationaboutthestatusofinterruptflags(cautionsignalsthattella programwhetheritcancontinueor not)anddefinetheoperatingmodes oftheperipherals.
Mode
Status Register Bits
CPU
SCG0 SCG1 OSCOFF CPUOFF
Clock Functions MCLK SMCLK ACLK DCO
AM
0
0
0
0
ON
ON1
ON1
ON1
ON1
LPM0
0
0
0
1
OFF
OFF
ON
ON
ON2
LPM1
1
0
0
1
OFF
OFF
ON
ON
OFF
LPM2
0
1
0
1
OFF
OFF
OFF
ON
OFF
LPM3
1
1
0
1
OFF
OFF
OFF
ON
OFF
LPM4
1
1
1
1
OFF
OFF
OFF
OFF
OFF
Notes: 1. Various modules are active as required. 2. If DCO is used as clock source.
Becausethemicrocontrollerthatis Figure7-3:OperatingmodesofMSP430family usedfortheexampledigitalprocessor hasbeendesignedtooperateatlow power,andmanyofitsapplicationsarebatterypowered,thereareanumberofoperatingmodesspecially directedtosavingpowerconsumption.Sixoperatingmodes,AMthroughLPM4,areshowninFigure7-3. AMistheactivemodewheretheCPUispoweredaswellasallothermodulesthataredesignatedtobe activebytheprogram.ModesLPM0toLPM4areso-calledlow-powermodeswithsuccessivelylesspower dissipated.IftheoperatingmodeisoneoftheLPMmodes,anytimetheCPUisrequiredbytheprogram, itmustbecalledintotheactivemodebytheprogram.Tosimplifytheoperationfortheexamplesinthis chapter,theonlymodesusedwillbetheactivemodeandtheLPM3mode.
WatchdogTimer ThereisanothercomponentwithintheMSP430microcontroller,thewatchdogtimerthatisparticularlyassociatedwithremotelow-poweroperation.ItisshowninFigure7-1.Itiscalledawatchdogtimerbecauseits primaryfunctionistoperformacontrolledsystemrestartafterasoftwareproblemoccurs.Thisisforsystem protectionincaseanapplicationisinaremotebattery-operatedlocationandsomeglitchcausesasoftware failure.Afterasettimeinterval,asystemresetisgeneratedandtheprogramisrestarted.Whatisimportantis TEAM LRN
106
ExamplesofAssembly-LanguageProgramming thatifthesystemisoperatingproperlyandthewatchdogtimerisactive,theprogrammustresetthewatchdogtimerbeforeitstimeintervalexpires,otherwisethesystemwillbereset.Ifthewatchdogtimerfunction isnotnecessary,thetimercanbeusedasanintervaltimer.Suchuseisinoneoftheprogramexamples.
SystemReset Tomakesureasystemapplicationalwaysstartsthesameway,aresetofthesystemisinitiatedbytheturnonofpower,calledapower-onreset(POR).Thereisalsoanotherreset,calledpower-upclear(PUC),that isforresettingifthewatchdogtimerhasexpired,orthereissomesystemviolation.Resetisconsidereda systeminterrupt.
Interrupts InChapter6,aninterruptwas describedasasignalthatinterrupts thedigitalsignalprocessorfrom whatitisdoinganddirectsittodo somethingdifferentasindicatedby theinterruptsignal.Itmaycontrol thedigitalprocessoratunexpected orrandomtimes. Oneofthemostcommontypesof interruptsisfromoneoftheperipheralmodules,suchasanI/Ounit. Theprocessorhashadtowaiton aninputuntilitisavailable.Nowit isavailableandsignalstheprocesFigure7-4:MSP430interruptpriorityscheme sorwithaninterruptsignal,andthe CourtesyofTexasInstrumentsIncorporated processoracceptstheinput.Ifanotherinterruptweretooccursimultaneously,theMSP430,asshowninFigure7-4,hasaninterruptpriority scheme.TheperipheralmodulesthatarenearertheCPUintheconnectionchainhavethehigherpriorityin casetwosignalsweretoappearattheprocessoratthesametime.Whiletheinterruptoccurs,allotherinterruptsareblockedbydefault.Forspecificdevicesthemodulesincludedhavespecifichardwarepositionsin thechain.Eachdevice’sinterruptsaredescribedinaninterruptvectortableinthedatasheetforthedevice.
OscillatorsandClockGenerators Includedinthemicrocontrollerisabuilt-inoscillatorthatusesonlyanexternalcrystal.Thecommonoscillatorusesawatchcrystalandoscillatesat32,768Hz,butusingahigher-frequencycrystal,itcanoscillate atfrequenciesfrom1MHzto8MHz.Inaddition,thereisadigitally-controlledoscillatorthatisdigitally tuned.Suchflexibilitymakesiteasytoselectaparticularclockoperatingfrequency. TheMSP430basicclocksystemisshowninFigure7-5.FortheMSP430F12XXmicrocontrollerusedfor thischapter,theLFXT1oscillatoristhelow/highfrequencycrystaloscillatormentionedabove.TheDCO oscillatorisaRC-typeoscillatorandisdigitallycontrolledtoadjustthefrequency.Otherfamilydevices haveasecondcrystaloscillator,XT2,thatcanoscillateatfrequenciesfrom450kHzto8MHz. Themainsystemclock,MCLK,canuseeitherLFXT1orDCOasitssourcecontrolledbythestateofthe selectionbitsSELM.BysoftwarecommandssettingthestateoftheDIVMbits,thesourceforMCLK canbedividedby1,2,4,and8.ThestateoftheDCORbit,whichchooseseitheraninternalorexternal resistor,definesthefundamentalfrequencyoftheDCO.ThenthestateoftheRSELbitsselectsoneof TEAM LRN
107
ChapterSeven eightnominalfrequencyrangesdefined inthespecificdevicedatasheet.The threeDCObitsdividetheDCOrange selectedbytheRSELbitsintoeight frequencystepsapproximately10% apart.BecausetheDCOisaRC-type oscillator,itsfrequencyvarieswith temperature,voltageandfromdevice todevice.ThefiveMODbitssetthe conditionstoadjustandstabilizethe DCOfrequency. TheactionofthethreeRSELbitsand thethreeDCObitstosettheDCO frequencyafterthefundamentalfrequencyissetisshowninFigure7-5b. ThethreeRSELbits,basedontheir binaryvalue,selectoneofeightmoninalfrequencyrangesfortheDCO.The rangesaredefinedforaspecificdevice inthedevice’sdatasheet.Thethree DCObits,basedontheirbinaryvalue, dividetheDCOrangeselectedbythe RSELbitsintoeightfrequencysteps, approximately10%apart.Thus,setting thebinaryvalueoftheRSELandDCO bitswillresultinaDCOCLKfrequencyforthesystem.Thetypicalranges andstepsareshowninFigure7-5b.
a.Clocksystemblockdiagram
Theauxiliaryclock,ACLK,usesLFXT1asits source,anddividesLFXT1downby1,2,4, and8basedonthestateoftheDIVAbits. Thesubsystemclock,SMCLK,useseither XT2CLKorDCOasitssource,againdivided by1,2,4,or8basedonthestateoftheDIVS bits.However,whenXT2CLKisnotpresent, asisthecasefortheMSP430x11xxandx12xx devices,aninternalconnectionismadeinthe MSP430thatconnectsLFXT1CLKinitsplace. Thechoiceofwhichclocksystemtouseis basedupontheapplication.Systemsrequiring veryprecisetimingwithlittlevariationallowed willusethehigh-frequencycrystaloscillators assources.Systemswithverynominalspeed andaccuracyforthetimingandrequirevery lowpowerwillusetheDCO.
b.TypicalDCOxrangeandRSELxsteps Figure7-5:MSP430basicclocksystem CourtesyofTexasInstrumentsIncorporated TEAM LRN
108
ExamplesofAssembly-LanguageProgramming
Timers Timersaredigitalcountersthatuseaclockatasetfrequencyasthesourcetoestablishtimeintervalsby countingacertainnumberofinputpulses.Thus,specifictimeperiodscanbeestablishedeitherbythenumberofpulsescounted,orbychangingthefrequencyofthepulses. ThetimersintheMSP430familyare16-bitcountersthatareextremelyversatile.Theirsourcescanbe programmedtobeanyoneofthoseshowninFigure7-5.Someofthecounterscanbeprogrammedtobe 8-,10-,or12-bitcounters.Eachtimerhascapture/compareregisterblocksthatsensewhenthecounterhas reachedaparticularcount(capture)andcomparethecounttoasettarget.Anoutputsignalfromthecapture/compareblockcanbeusedasaninterruptorasanexternalsignal.Thesetimersareparticularlyuseful tokeeptrackofelapsedtime,tosettimeintervalswithinwhichspecificactionoccursoristooccur,andto produceresets,alertsorwarnings.
AddressingModes Addressingmodeswerediscussedin generalinChapter6.Nowthespecific modesusedintheMSP430familywill bediscussed—theformat,thesymbols used,andadescriptionofthemodes. Thesevenaddressingmodesareshown inFigure7-6;notethecolumnAs/Ad. Asarebitsinaninstructionthatdefine theaddressingmodeusedforthesource, andAdarebitsinaninstructionthat definetheaddressingmodeusedforthe destination.InFigure7-6,addressing modes1,2,3and4havebitsintheAs andAdcolumn;therefore,theycanbe usedtoaddressboththesourceandthe destination.Modes5,6and7canbe usedforthesourceonly.Hereisashort discussionofeachaddressingmode:
As/Ad
Addressing Mode
Syntax
Description
1. 00/0
Register mode
Rn
Register contents are operand
2. 01/1
Indexed mode
X(Rn)
(Rn + X) points to the operand
3. 01/1
Symbolic mode
ADDR
X is stored in the next word (PC + X) points to the operand X is stored in the next word. Indexed mode X(PC) is used. 4. 01/1
Absolute mode
&ADDR
The word following the instruction contains the absolute address. X is stored in the next word. Indexed mode X(SR) is used.
5. 10/−
Indirect register mode
@Rn
Rn is used as a pointer to the operand.
6. 11/−
Indirect autoincrement
@Rn+
Rn is used as a pointer to the operand. Rn is incremented afterwards by 1 for .B instructions and by 2 for .W instructions.
7. 11/−
Immediate mode
#N
The word following the instruction contains the immediate constant N. Indirect autoincrement mode @PC+ is used.
Figure 7-6: Addressing Modes Figure7-6:Addressingmodes
1. RegisterMode—ThesymbolisRn Ifregistermodeaddressingisused,thecontentoftheregisteristheoperand.Forexample,theinstruction MovR1,R2meansthatregisteraddressingisusedforboththesource,registerR1,andthedestination,registerR2.ThecontentsofR1aremovedtoR2.R2ischangedbutR1remainsthesame.Registermodecan beusedeitherforthesourceorthedestinationorboth.
2. IndexedMode—ThesymbolisX(Rn) TheXisanindexthatisaddedtothecontentsofRntoformanaddressthatiseitherthesourceoforthe destinationfortheoperand.Forexample,fortheinstructionMov2(R1),4(R2).Theoperandatthesource address(R1+2)ismovedtothedestinationaddress(R2+4).TheXindexisstoredinthenextwordafter theinstruction;thesourceinthefirstwordandthedestinationinthesecondword.ThecontentsofR1and R2arenotaffected.
TEAM LRN
109
ChapterSeven
3. SymbolicMode—AsymbolnamesuchasADDR Asymbolicnameisgiventotheaddressoftheoperand,eitherthesourceorthedestinationorboth.For example,theinstructionMovADDR,ENDsaystomovethecontentsatthesourceaddressADDRtothe destinationaddressEND.ThesymbolADDRandENDareassigneddigitalwordsthataresubstitutedby theassemblertomakeuptheproperaddress.
4. AbsoluteMode(&ADDR) The&symbolisaddedinfrontoftheoperand,&ADDR.The&symbolindicatesthattheabsoluteoperandaddressiscontainedinthewordfollowingtheinstruction.Absolutemodecanbeusedforboththe sourceandthedestination.Forexample,theinstructionMov&ADDR,&ENDsaysmovethecontentsof thesourceaddressADDRtothedestinationaddressEND.However,nocalculationsareinvolvedasfor symbolicmode.Theabsoluteaddressforboththesourceanddestinationareinthewordsfollowingthe instruction,thesourceinthefirstword,thedestinationinthesecondword.
5. IndirectRegisterMode(@Rn) The@symbolisaddedinfrontofaregisternumber,@Rn.Thisisanaddressingmodethatisvalidonly forthesource.Itindicatesthatthecontentsofthesourcearetobeusedastheaddressoftheoperand.For example,theinstructionMov@R1,0(R2)saystomovethecontentsatthesourceaddress,thecontentsof R1,tothedestinationaddress.Sinceindirectregistermodecannotbeusedforthedestination,thesubstitute forthedestinationoperandis0(R2),whichmeansthedestinationaddressisthecontentsofR2.R1andR2 arenotmodified.
6. IndirectAutoincrement(@Rn+) Besidesthe@symboladdedinfrontofaregisternumberaplussign(+)isaddedaftertheregister,@Rn+. Thisisthesameaddressingmodeasfortheindirectregistermodeexceptthesourceregistercontentis incrementedbyoneforabyteoperationandbytwoforawordoperationaftertheinstructioniscompleted.
7. ImmediateMode(#N) The#symbolisaddedinfrontoftheoperand,usuallyaconstantnumber,#N.The#symbol,statesthat thenumberindicated,whichiscontainedinthewordfollowingtheinstruction,isthesourceoperand.The immediatemodecanonlybeusedforsourceaddressing.Forexample,theinstructionMov#9,ADDRsays thattheconstant9istobemovedtothedestinationADDR(symbolicaddressing).Whenexecuted,the programcounterpointstothewordfollowingtheinstructionandmovesitscontents(thenumber9)tothe destinationADDR.
MoreonMSP430Control Itwillbeimportanttotheunderstandingofassembly-languageprogrammingtolookfurtherhowthe MSP430microcontrolleriscontrolled.Oneoftheprincipalfeaturesofitsdesignistheuseofregistersto implementthecontrol.Thestateofaparticularbitorparticularbitsinaregisterdeterminestheoperating conditionoractionofaparticularfunctioninsidetheMSP430.
TheStatusRegister Thestatusregister,SR,showninFigure7-7,isaprimeexample.ItisregisterR2ofthesixteen16-bitregistersintheCPUshowninFigure7-2a.Thestatusregister,R2,hasnineactivebits;theremainingsevenare availableforfutureexpansion.TheLSBisthezerobit;theeightbitistheMSB.Eachoftheninebitshas aspecificcontrolovertheCPU,oritsstatedictatesthataparticularactionhasoccurred.Forexample,the fourbitislabeled“CPUOFF.”Ifthefourbitisset(toa1),theCPUwillbeoff.Programexecutionstops, TEAM LRN
110
ExamplesofAssembly-LanguageProgramming Reserved for further expansion 15
14
13
12
11
10
Status Register SR
9
8 V
V SCG1 SCG0 OscOff CPUOff GIE N Z C
Overflow bit System clock generator control System clock generator control Crystal oscillator off bit CPU off bit General interrupt enable bit Negative bit Zero bit Carry bit
7
6
SCG1 SCG0
If = 1 turns off Overflow SMCLK. Set = 1 when the result of an arithmetic operation overflows the signedvariable range. If = 1 turns off DCO dc bit 1 generator bit 0 if DCOCLK is not used for MCLK or SMCLK.
5
4
3
2
1
0
OSC OFF
CPU OFF
GIE
N
Z
C
If = 1 XTAL OSC is off wake up is possible only through enabled external interrupts when GIE bit is set and from NMI. If = 1 CPUOFF and program execution stops. Wake up is possible through all enabled interrupts.
Set = 1 if the result of a byte or word operation is negative and cleared when result is not negative. If = 1 all enabled interrupts are handled. If = 0 all maskable interrupts are disabled.
Set = 1 if result of byte or word operation produces a carry; cleared to 0 if no carry occurs.
Set = 1 if the result of a byte or word operation is 0; cleared if result is not 0.
Figure7-7:StatusregisterR2
buttheRAM,theportregistersandanyenabledperipheralsstayactive.TheCPUisawakenedwhenany enabledinterruptoccurs. Thefivebit,labeled“OSCOFF,”ifset(toa1),thecrystaloscillatorenterstheoffmode.TheDCOremains ONsotheCPUcanberunning.TheRAMcontents,theports,andtheregistersaremaintained.Wakeupis possibleonlythroughenabledexternalinterrupts. Thethreebitisthegeneral-interrupt-enablebit,GIE.Ifset,allenabledmaskableinterruptsarehandled; ifreset(toa0),allmaskableinterruptsaredisabled,GIEisclearedbyinterruptsandsetbyareturnfrom interrupt,RETIinstruction,aswellasotherappropriateinstructions.Thesixandsevenbit,labeledSCG0 andSCG1,respectively,determine,throughtheirbitcombination,whichclockisactive.IfSCG0isset(toa 1),theDCOdcgeneratoristurnedoff;however,thisonlyhappensiftheDCOisnotbeingusedasasource forMCLKorSMCLK.IfSCG1isset,SMCLKisturnedoff.Itmustbenoted,asdiscussedinFigure7-3, thatthebitsOSCOFF,CPUOFF,SCG0andSCG1worktogethertodefineanoperatingmode,notindependentlytoprovidevariouscontrol.Theeightbit,labeledV,isanoverflowbit.Itissetwhentheresultofan arithmeticoperationoverflowsthesigned-variablerange. Thezero,oneandtwobitsarelabeledC,Z,andN,respectively.TheCorcarrybitissetwhenabyteor wordoperationcalledforinaninstructionproducesacarry.Itisclearedifnocarryoccurs.TheZorzero bitissetiftheresultofabyteorwordoperationiszero;iftheresultisnotzero,itiscleared(settoa0). Thenegativebit,N,issetiftheresultofabyteorwordoperationisnegative,andisclearedwhentheresult isnotnegative.InstructionsintheprogramwilltesttheC,Z,orNbitsandtheCPUwillrespondasdirected bytheprograminstructions.Operationsasaresultofaninstruction,ortheinstructionitself,cansetthebits sothattheCPUiscontrolledaccordingly.
BasicClockSystemControlRegisters Thebasicclocksystemissetup(configured)byusingthreecontrolregisters,theDCOCTL(thedigitallycontrolledoscillatorcontrolregister),andthetwobasicclocksystemcontrolregisters,BCSCTL1and BCSCTL2.Inaddition,SCG1,SCG0,OSC0FFandCPUOFFbitsinthestatusregistercontroltheoperatingmodeasdescribed.TheDCOCTLregisterandabriefdescriptionofitsbitsandwhattheycontrolis showninFigure7-8.ThecoderepresentedbythestateoftheDCObitsdefinesoneofeightfrequencysteps TEAM LRN
111
ChapterSeven withintheDCOfrequencyrangesetbythe RSELbitsintheBCSCTL1controlregister.Thiswasexplainedpreviously(Figure 7-5).ThestateofthefiveMODbitsseta modulationconstantusedtoadjusttheDCO frequency.Atpowerup,thepower-upcontrol signal(PUC)loadstheDCOCTLregister with060htosettheinitialDCOfrequency.
7 4 DCOCTL
6 2
5 1
4 16
3 8
2 4
1 2
0 1
Bit Bit Value
DCOx MODx DCO2 DCO1 DCO0 MOD4 MOD3 MOD2 MOD1 MOD0 The 3-bit code sets a binary value that defines one of eight frequency steps in the frequency range selected by the binary value of the three RSEL bits in the BCSCTLI register (see Figure 7-5b)
The 5-bit code whose binary value defines how often the fDCO+1 frequency is used within a period of 32 DCOCLK cycles to modulate and adjust the DCO frequency. During the remaining clock cycles (32-MODx) the fDCO frequency is used. When DCOx = 7, the highest frequency has been selected and modulation is not possible.
Thetwobasicclocksystemcontrolregisters, BCSCTL1andBCSCTL2,areshowninFigure7-9,alongwithabriefdescriptionofthe controlaffectedbythebitsofeachregister. BCSCTL1controlsbasicclocksystem1and Figure7-8:Thedigitally-controlledoscillator Figure 7-8: The Digitally-Controlled Oscillator (DCO) Control Register BCSCTL2basicclocksystem2.Referring (DCO)controlregister toFigure7-5andBCSCTL1inFigure7-9, theXTSbitdeterminesiftheLFXT1oscillatorwilloperatewithalow-frequencyorhigh-frequencycrystal toproducetheLFXT1clocksource.ThestatesoftheDIVAbitsdetermineifclocksourceLFXT1isgoing tobedividedby1,2,4or8toproducetheclockACLK.TheRSELbits0,1,and2determinethenominal frequencyrangeoftheDCOaspreviouslydiscussedforFigure7-5b. ReferringtoFigure7-5andBCSCTL2in Figure7-9,theSELMbitstatesdetermine ifDCO,XT2orLFXT1aregoingtobethe sourcefortheMCLKclock.TheDIVMbit statesdetermineiftheclocksourceisgoingtobedividedby1,2,4or8toproduce MCLK.Likewise,the3bit,theSELSbit, statedeterminesifDCOCLK,XT2CLK orLFXT1CLKwillbethesourceforthe SMCLKclock.TheDIVSbitstatesdetermineifthesourcetoSMCLKwillbedivided by1,2,4or8.TheDCORbitcontrols whethercurrentisgoingtobesuppliedto theDCOfromaninternalorexternalresistor tocontroloscillations.Thecompleteclock systemfortheMSP430canbesetupinitially usinginstructionstotheCPUtosetthebits oftheDCOCTL,BCSCTL1andBCSCTL2 registers.
7
BCSCTL 1 057h
6
XT2OFF If it is not used for MLCK or SMCLK, controls XT2 OSC. If = 0 OSC ON If = 1 OSC OFF
XTS If = 0 LFXT1 OSC uses Low f xtal If = 1 LFXT1 OSC uses hi f xtal
5
4
DIVAx DIVA1 0 0 1 1
DIVA0 0 1 0 1
Div 1 2 4 8
3 XT5V Should always be reset to 0
Code determines division factor DIV for ACLK
2
1
0
Bit
RSELx RSEL2
RSEL1
RSEL0
The 3-bit code sets a binary value that selects one of eight nominal frequency ranges for the DCO. The lowest frequency range occurs when the code is 000. (see Figure 7-5b)
a.BCSCTL1 7 BCSCTL 2 058h
6
SELM1
SELM0
Source for MLCK 0 0 = DCOCLK 0 1 = DCOCLK 1 0 = * 1 1 = LFXT1CLK
* This is XT2CLK if XT2 is present. Otherwise, it is LFXT1CLK.
WatchdogTimer
5
4 DIVMx
SELMx
DIVM1
DIVM0
0 0 1 1
Div 1 2 4 8
0 1 0 1
Code determines division factor DIV for MLCK
3 SELS SMCLK source If = 0 source is DCOCLK If = 1 source is XT2CLK or LFXT1CLK
2
1 DIVSx
DIVS1 0 0 1 1
DIVS0 0 1 0 1
Div 1 2 4 8
Code determines division factor DIV for SMCLK
0
Bit
DCOR DCO operation If = 0 DCO operates from internal resistor If = 1 Internal R off. DCO can’t operate unless driven by external resistor.
TheWDTCTLregistercontrolsthewatchb.BCSCTL2 dogtimer.ItisshowninFigure7-10,and adescriptionofthecontrolthateachbit Figure7-9:Basicclocksystemcontrolregisters appliesinaparticularstateisincluded.When thewatchdogtimerfunctionisactive,theWDTTMSELbitmustbe0tobeinthewatchdogmodeandthe WDTHOLDbitmustbe0;ifWDTHOLDisset,thecountingstops. TEAM LRN
112
ExamplesofAssembly-LanguageProgramming 15 14 13 12 11 10 9 8 6 5 4 3 2 1 0 Bit Ifthewatchdogtimeris active,softwareshould WDTISx WDTPW WDTCTL WDTHOLD WDTNMIES WDTNMI WDTTMSEL WDTCNTCL WDTSSEL 1120h WDTIS1 WDTIS0 periodicallyresetthe watchdogtimerbywriting When 8-bit code is a Password. WDTNMI = 1 If register is to be written, a1totheWDTCNTCL Edge Select WDT Mode WDTCNT WDT Timer password 05Ah must be in If = 0 Select Source Interval Select WDTPW. When register is clearbittopreventthe NMI triggers If = 0 0 − SMCLK The 2-bit code to be read, 069h is loaded on rising edge WDT Active 1 − ACLK determines the into WDTPW. timerintervalfromexpiring If = 1 If = 1 division of the NMI triggers Interval clock source andrestartingthesystem. on falling edge timer to provide a time interval SettingWDTCNTCL(to as follows: WDTNMI Clears WDT Status of WDT 0 0 WDTCLK Source / 32768 a1)restartsthecounter, Select Counter If = 0 0 1 WDTCLK Source / 8192 Selects If = 0 WDT is active 1 0 WDTCLK Source / 512 WDTCNT,at0000h.The function of No Action If = 1 1 1 WDTClock Source / 64 RST/NMI pin Writing 1 WDT is off WDTSSELbitselectsthe If = 0 to this bit Watchdog timer Reset function restarts HOLD. clocksourceforWDTCNT, If = 1 WDTCNT NMI function at 0000h when=0thesourceis SMCLK;when=1the Figure7-10:Watchdogtimercontrolregister sourceisACLK.Thestate Figure 7-10: Watch Dog Timer Control Register oftheWDTISbitsdeterminesthetimeintervaloftheclock,eitherwithSMCLKorACLKasthesource. ThecodeforthetimeintervalisshowninFigure7-10.
Thefivebit,WDTNMI,controlswhetherapin,RST/NMI,isaresetinputoranonmaskableinterruptinput (NMI).WhenthestateofWDTNMIisa0,theRST/NMIinputisalevel-sensitiveresetinput,andwhenthe stateisa1,itisanedge-sensitivenonmaskableinput.WhenWDTNMIissetto1,thesixbit,WDTNMIES, controlswhethertheinputtriggersontherising(WDTNMIES=0)orfallingedge(WDTNMIES=1)of theinputsignal.
Timer_AControlRegister Thereisa16-bit,general-purposetimerintheMSP430F1232deviceusedforthischapter,calledTimer_A. Itscontrolregister,TACTL,isshowninFigure7-11,withadescriptionofthecontroleachbitappliesina particularstate. Unused bits
15 TACTL 160h
14
13
12
11
10
9
8
7
TASSELx TASSEL1 TASSEL0
ID1
0 0 1 1
Clock Source 0 0 * TACLK 0 1 ACLK 1 0 SMCLK 1 1 * INCLK
6 ID0
0 1 0 1
MC1
113
MC0
3
2
X
1
0
TACLR TAIE
Bit
TAIFG
Unused
Div 1 2 4 8
Mode control of timer
0 0
0 1
1
0
1
1
Figure7-11:Timer_Acontrolregister TEAM LRN
4 MCx
Code determines division factor DIV for the input clock source
*see data sheet for particular device
5
IDx
Timer Clear If CLR bit is set, timer is reset
STOP Counts up to value in TACCRO, then restarts at 0 Counts continuously to OFFFFh and restarts at 0 up/down continuously counts up to TACCRO value and back down to 0
Timer_A Interrupt Flag 0 − No interrupt pending 1 − Interrupt pending
Timer_A Interrupt Enable If TAIE = 1, interrupt request from timer overflow bit is enabled. If = 0, disabled.
ChapterSeven TheTASSELbitstatesdeterminestheclocksourcetobeusedforTimer_A,eitherinternalclocksACLK orSMCLKoranexternalsourceTACLK.Afterclockselection,thestateoftheIDbitscontrolwhetherthe clocksourceispasseddirectlytoTimer_A,orwhetheritisdividedby2,4or8.ThestateoftheMCbitsset themodeofthetimerasshown.ThemodesofthetimerarefurtherclarifiedinTable7-2.
MC1
MC0
Mode
0
0
Stop
0
1
Up(from0tovalueTACCRO)
1
0
Continuous(from0to0FFFFh,thenrestartat0)
1
1
Up/Down(countsuptoTACCROvalue,thenbackto0)
Table7-2:ModeofTimer_A
Toclearthecounter,thetwobit,TACLR,issettoa1.TheremainingonebitandzerobitcontroltheresponsetoaninterruptgeneratedwhenTimer_Areachesaspecificvalue.Theinterruptsetsaflag,TAIFG, andtheTAIEbitenablestheinterruptifitissettoa1ordisablestheinterruptifitisresettoa0.
Input/OutputControl PreviousdiscussionstatedthattheI/OportsintheMSP430couldbeprogrammedtobeinputsoroutputs.For thefamilydeviceusedforthischaptertherearethreeI/Oports,1,2and3.Figure7-12showstheregisters thatcanbeprogrammedtoconfiguretheexternalpinsoftheMSP430.TherearePxINinputregisters;there arePxOUToutputregisters;therearePxDIRdirectionregistersandtherearePxSELfunction-selectregisters. AllI/Oportsareinitiallyinputswhenthemachinepowersup.IfthezerobitofP1DIRissettoa1,then theexternalPin1.0willbeanoutput;ifitsstateisa0,theexternalPin1.0willbeaninput.Anyinputsignal frompinP1.0,whenprogrammedasaninput,willbestoredinthezerobitoftheP1INregister.Whenpin P1.0isprogrammedasanoutputbyP1DIR,theP1OUTregisterzerobitisoutputtoP1.0.Correspondingly,theotherbitsofP1INandP1OUTwilleitherreceivedataintotheirregisteroroutputdatafromtheir registerbasedontheprogrammingintheP1DIRregister. ExternalpinscanbeusedbyothermodulesratherthanI/Oports1,2and3.ThePxSELbitsofthefunction-selectregistercontrolstheselection.WhenthePxSELbitforaparticularpinissettoa1,thatpinwill beusedbyamoduleotherthanport1or2or3.Thedatasheetfortheparticulardevice,withitspackage pinlayout,willindicateifpinshavemultiplefunctioncapability.Whenthemultiplecapabilityisavailable, thePxSELmustbeconfiguredtoselecttheproperpinfunction. Tosummarize,thePxDIRregisterbitsareset(=1)todictateiftheexternalpinsoftheI/Oportsaretobe outputs.TheinitialconditionisthatallI/Oportsareinputs.AnyinputsignalwillbeplacedinthePxIN register(s).AnyoutputpinswillreceivesignalsfromthePxOUTregister(s).Ifaparticularexternalpinis nottobeanI/OoutputorinputfromPort1,2or3,thenthebitsofthePxSELregister(s)aresettoselect thefunctionthatistobeonthepin.Thefunctionsavailableforthepinarecalledoutonthedatasheetfora particulardevice.
FurtherThoughts Somefurtherthoughtsandconceptsneedtobeexaminedbeforeanactualassembly-languageprogramis explained.Thefirstoftheseissymbolicnotation. TEAM LRN
114
ExamplesofAssembly-LanguageProgramming
SymbolicNotation
Port 1
Another
Module Buffers Recallthattheactual External P1SEL P1DIR 1sand0s(machine 1 Pins P1OUT Output bit 0 bit 0 OUT0 OUT bit 0 buffer language)thatdirect 0 1 thecircuitsinsideof PIN 1.0 IN adigitalprocessorfor P1IN IN0 bit 0 aparticularprogram mustbeformulatedor Another codedforeachinstrucModule Buffers tion.Thishasbeen P1DIR P1SEL 1 P1OUT Output mentionedpreviously bit 1 bit 1 OUT1 OUT buffer bit 1 0 butitbearsrepeating. 1 IN PIN 1.1 Thelanguageusedfor P1IN ourprogrammingis IN1 bit 1 assemblylanguage.To convertassembly-lanPIN 1.2 OUT2 P1OUT P1IN P1SEL P1DIR Buffers O.B. IN2 bit 2 bit 2 bit 2 bit 2 guageprogrammingto PIN 1.3 OUT3 P1OUT P1IN P1SEL P1DIR machinelanguagean Buffers O.B. IN3 bit 3 bit 3 bit 3 bit 3 assembler,acomPIN 1.4 OUT4 P1OUT P1IN P1SEL P1DIR puterprogramthat Buffers O.B. IN4 bit 4 bit 4 bit 4 bit 4 convertsthemnemonic PIN 1.5 OUT5 P1OUT P1IN P1SEL P1DIR instructionsusedin Buffers O.B. IN5 bit 5 bit 5 bit 5 bit 5 assembly-language PIN 1.6 OUT6 P1OUT P1IN P1SEL P1DIR Buffers O.B. programsintothe1s IN6 bit 6 bit 6 bit 6 bit 6 and0sofmachine OUT7 PIN 1.7 P1OUT P1IN P1SEL P1DIR O.B. Buffers code,isrequired.The IN7 bit 7 bit 7 bit 7 bit 7 assemblerhasbeen developedtorecognize PIN 2.0 Port 2 symbolicrepresenOUTPUT P2OUT O.B. P2SEL P2IN P2DIR Buffers INPUT tationssuchasthe PIN 2.7 mnemonicsusedfor PIN 3.0 theassembly-language OUTPUT Port 3 instructions;suchas INPUT P3OUT O.B. P3IN P3SEL P3DIR Buffers PIN 3.7 symbolicnamesused toidentifyregisterbits, Figure7-12:I/OPorts1,2and3 systemcommands, systemnames,or systemsignals.Whentheassemblerseestherespectivesymbolicnameithasbeenprogrammedtoinsert aspecificbinarynumberthatrepresentsthesymbol.Uniquereferencelistshavebeendevelopedforthe assemblerofaspecificdeviceorfamilyofdevicesthatassignthebinarynumberstosymbolicnamesused forthedevices.Astheassemblerreadstheassembly-languageprogramandencountersasymbolicname,it insertstherespectivebinarynumberand“assembles”themachinecodefortheprogram.
Table7-3isanexampleportiontakenfroma“StandardRegisterandBitDefinitionsfortheTexasInstrumentsMSP430MicrocontrollerFamily”referencelistcontainedintheAppendix.
TEAM LRN
115
ChapterSeven *STATUSREGISTERBITS*
#defineC
(0x0001)
#defineZ
(0x0002)
#defineN
(0x0004)
#defineV
(0x0100)
#defineGIE
(0x0008)
#defineCPUoff
(0x0010)
#defineOSCoff
(0x0020)
#defineSCG0
(0x0040)
#defineSCG1
(0x0080)
/*LowPowerModescodedwithbits4–7inSR*/ *ifndef_IAR_Systems_ICC/Begin#definesforassembler*/
#defineLPM0
(CPUoff)
#defineLPM1
(SCG0+CPUoff)
#defineLPM2
(SCG1+CPUoff)
#defineLPM3
(SCG1+SCG0+CPUoff)
#defineLPM4
(SCG1+SCG0+OSCoff+CPUoff)
Table7-3:Referencelistforassembler
Notice,firstofall,thatthesymbolicnamesinTable7-3arethesameonesusedtoidentifythebitsinthe statusregister,andthereferencelistisdefiningabinarynumberassociatedwiththesymbolicname.Forexample,thebinarynumberforGIEisthe16-bithexadecimalnumber0008h,whichis0000000000001000 instraightbinary.Ifthisnumberisloadedintothestatusregister,itsetstheGIEbit.Thus,iftheprogram wantstheGIEbitset,aninstructioncanuseGIEasthesourceoperandandSRasthedestination,andthe assemblerknows,becauseofthereferencelist,toloadthehexadecimalnumber0008hintoSRwhichsets GIE.Similarly,thebinarynumberassignedinthereferencelistwillsetthebitwiththesymbolicnamein oneofthecontrolregistersifthatsymbolicnameisusedintheappropriateinstruction. Combiningsymbolicnamesandtheirassociatedbinarynumberswillsetmultiplebitsinthecontrolregisters.ThisoccursindefiningthebitstobesetfortheMSP430low-powermodesshowninTable7-3.For example,toplacetheMSP430systemintheLPM3mode,theSRbitsSCG1,SCG0andCPUoffmustbe set.Oneoperandof(SCG1+SCG0+CPUoff)canbespecifiedandtheassemblerwillcombinethebinary numbersspecifiedinthereferencelistandinsertthemintheSRasshowninFigure7-13.Theoperandcalls outthesymbolicnamesandtherespectivebitcorrespondingtothenameisset,evenwhenmultiplenames areusedintheoperand.
FormatandSymbols Afinalthoughtbeforediscussingtheactualprogramming.Theformatforthelinesofcodeisasfollows, shownwithanexampleinstruction:
Label ADCLoop
Instruction bis.b
Operands #CLK,&P2OUT
TEAM LRN
116
Comment ;Clockhigh
ExamplesofAssembly-LanguageProgramming Before Instruction
8
Status Register
V
7
6
SCG1 SCG0
5
4
3
2
1
0
OSC OFF
CPU OFF
GIE
N
Z
C
Bit
Inserted from Reference List SCG1 0080
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
SCG0 0040
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
CPU OFF 0010
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
OSC OFF
CPU OFF
GIE
N
Z
C
After Instruction Status Register
V
SCG1 SCG0
With SCG1 set, SCG0 set and CPU OFF set the MSP430 is in the LPM3 low-power mode.
Figure7-13:Substitutionforsymbolicnamesinstatusregister Figure 7-13: Substitution for Symbolic Names in Status Register
Labels Labelsidentifyparticularpositionsintheprogram.Theyareusedextensivelytoidentifythebeginningofa programsubroutine.Whenaprogramneedsaparticularsubroutine,theprogramcandoasubroutinejump totheparticularlabelassociatedwiththesubroutine.
Instructions Theactualinstructionappearsintheinstructioncolumn.Intheinstruction,bis.b,“setbitsindestination”, the.bmeansitisabyteinstructiondealingonlywitheightbits,thelowerbyte,ofa16-bitword.Whenthe instructionisawordinstructionwhereall16bitsareinvolved,thereneedbenothingor.wcanbeused.
Operands Anoperandisthepartoftheinstructionwhichwilloperatedonbytheinstruction.Operandsaretheportion ofaninstructiondesignatedbyanopcodetobethequantitytobeoperatedonbytheinstruction.Theyappearintheoperandcolumnwiththesourcealwayslistedfirstseparatedfromthedestinationbyacomma. Thesourcemayhaveasymbolinfrontofit,andthesameforthedestination.Thesymbolswillcorrespond tothesyntaxcolumninFigure7-6identifyingtheaddressingmodeused.Inthecodelineexampleshown above,thesourceCLKhasa#signinfrontofit,andthedestination,registerP2OUT,hasan&infrontof it.The#signindicatesimmediateaddressingforthesource,andthe&meansabsoluteaddressingisused forthedestination.
HexadecimalNumbers Hexadecimalnumberswillhavespecialidentificationinmostcases.Asdiscussedpreviously,anyhexadecimalnumberthatstartswithAthroughFwillhaveazeroinfrontofittomakesurethenumberisidentified correctly.Asmallhisincludedinthenumbertoidentifyitashexadecimal,otherwisetheassembler assumesthenumberisadecimalnumber.Or,asintheportionofthereferencelistshowninTable7-3, theformat0x0000mayalsobeusedforahexadecimalnumber. TEAM LRN
117
ChapterSeven
Comments Thecommentscolumncontainshintstosomeonereadingtheprogramwhattheoriginalprogrammerhad inmindwhenthelineofcodewaswritten—whatthelineofcodeshouldaccomplish.Manytimesthecommentcolumnisalsoarefreshertotheoriginalprogrammer.Asemicolonmustprecedeallcomments.Inthe explanationsthatfollowofassembly-languageprogramming,notimewillbespentonthecomments.The readermayusetheseforextraunderstandingoftheprogram.
ProgrammingExamples Introduction Inordertoexplainhowtodevelopaprogramusingassemblylanguage,severalsubprogramsthatperform differenttaskswillbeexplainedindetailtohelpgrasptheconceptofprogramming,learnsomeofthe programmingdetailsandgetfamiliarwiththeformatnecessaryforassembly-languageprogramming. Obviously,sophisticatedprogrammersusehigh-levellanguages,butassembly-languageprogrammingis usedherebecauseitoffersanopportunitytograspthefundamentalsofprogrammingsothathigher-level languageprogrammingcanbeimplementedwithlessdifficulty.Itoffersfundamentalconceptsthataidin theunderstandingofprogramminginthehigher-levellanguages.
SubprogramNo.1 GeneralDescription TheprogramthatwillbedescribedisaportionofatotalprogramusingaTLV0831ADCthatinterfaces toaMSP430F12Xmicrocontroller.Thetotalprogramincludessamplingananaloginputvoltage,convertingittoadigitalcode,shiftingthedataintotheMSP430,andtransmittingthedatatoapersonalcomputer (PC).Thesubprogramthatisdescribedhereistheportionofthetotalprogramthatdealswithinitiatingthe digitalconversionandshiftingthedataintoatemporarystorageregisterintheMSP430.Essentially,this subprogramimplementsashiftregisterusingsoftware. TheblockdiagramofthesystemandtheinterconnectionsareshowninFigure7-14a.Atimingdiagramof theeventsastheyoccurisshowninFigure7-14b. Hereisabriefdescriptionoftheapplication: 1. TheTLV0831isan8-bitADC.Itsamplesitsanaloginput,convertsthesignaltodigitalandstoresthe 8-bitdigitaloutputinanoutputregister. 2. TheTLV0831dataisthenshiftedoutoftheoutputregisterbytheMSP430intotheADCDataregister intheMSP430. 3. TheTLV0831dataiscoupledoutonoutputDO.DOisconnectedtopinP2.3oftheMSP430,whichis programmedtobeaninput. 4. PinsP2.0andP2.1areprogrammedtobeoutputsfromtheMSP430.P2.0providesachipselectsignal toactivatetheTLV0831,whileP2.1providesclockpulsestotheTVL0831. I/OPort2,oneofthethreeavailable,isusedforthisapplication.ThecontentofregisterP2DIRissettodeterminewhichI/Opinsaretobeinputsandwhicharetobeoutputs.TheP2INregisterinputsandcaptures theinputdatafromanypinsthatareinputs,whiletheP2OUTregisteroutputstherespectivedataontothe pinsthatareoutputs.TheP2.3inputiscoupledtoaregisterintheMSP430calledbythesymbolicname ofADCData.The8bitsfromtheoutputdataregisteroftheTLV0831areshiftedoutseriallyontoDOand endupinthisregister.Ittakes9shiftstodothis—oneforastartbitandtheremainderfortheeightbitsof data.ThesignalonP2.1actsastheclockfortheTLV0831toshiftoutthebitsontoDO.Thestarttimingis TEAM LRN
118
ExamplesofAssembly-LanguageProgramming controlledbythesignalonP2.0 oftheMSP430,whichisconnectedtoCSoftheTLV0831. AlogiclowonCSactivatesthe TLV0831andinitiatesthe A-to-Dconversion.The MSP430isoperatedinthe LPM3low-powermode.The watchdogtimerisusedasan intervaltimer,setat64ms,and whenittimesoutitgeneratesan interrupttowakeupthesystem andinitiateaconversion.
Reset RST/NMI
TVL0831 ADC
Analog Input
CLK Output Register
I/O
VCC CS
MSP430 *Microcontroller
Chip Select Shifting Pulses Data
DO GND
ADC DATA
P2.0
P2OUT
P2.1 P2.3
P1.1
VCC
VCC
x IN 32kHz crystal x OUT TXD
Data to PC
P2IN
*MSP430F1232
VSS
a.Blockdiagramshowinginterconnections CS
TheInitialConditions ThesubprogramNo.1assemCLK bly-languageprogramisshown inFigure7-15.Normally,the DO A,B,C,andDnotationsarenot present;theyhavebeenadded toaidinthediscussionofthe program.Thereferencelistthatwas discussedpreviouslyfortheMSP430 appliestothisprogram.Itiscontained intheAppendix.TheAandBportions ofthisprogramarethesametypeof referencelist,buttheyarespecific onlytothisprogram.Theassembler takesthe“#define”andthe“equ”and substitutesthenumbersdefinedforthe symbolicname.Softwareengineers callit“syntaxicsubstitution”—substitutingnumbersforwords(the symbolicnotations)intheprogram.
H
Start bit
L
1
0
1
1
0
1
1
0
b.Timingdiagram b. Timing Diagram
c.Rotateleftthroughcarry Figure7-14:Systemsapplication implementedbySubprogramNo.1 CourtesyofTexasInstrumentsIncorporated
SectionAandB SectionAdefinesthespecificregistersthataregoingtobeused,R6(BitCnt)tocountbits,R5(RxTxData) toreceiveandtransmitdatatothePC,andR11(ADCData)theregistertostorethedatareceivedfromthe ADC.SectionBcontinuesthesametypedefinitionswiththe“equ”notation.Heretheprogrammerhas assignedspecifichexadecimalnumberscomplementingthereferencelistbutspecifictothisprogram. ThesubprogramwilluseADCData,TXD,CS,CLKandDO.Theremainingsubstitutionsareusedbythe portionofthetotalprogramthattransmitsdatatothePCandthatcalibratestheDCO.Thatportionisnot includedforthesakeofbrevity.
TEAM LRN
119
ChapterSeven A.
; Dedicated CPU registers used (1) #define BitCnt R6 (2) #define RXTXData R5 (3) #define ADCData R11 ; B. ; User definitions, 9600 Baud HW/SW UART, MCLK = 37.5x32768 = 1228800 (1) Bitime equ 0128 ; 104 us (2) Delta equ 150 ; Delta = (target DCO)/(32768/4) (3) TXD equ 002h ; TXD on P1.1 (4) CS equ 001h ; P2.0 Chip Select (5) CLK equ 002h ; P2.1 Clock (6) DO equ 008h ; P2.3 Data Out (7) LF equ 0ah ; ASCII Line Feed (8) CR equ 0dh ; ASCII Carriage Return ; Label Instruction Operands Comment ;-----------------------------------------------------------------------C. ORG 0F000h ; Program Start -----------------------------------------------------------------------1. Reset mov #0300h,SP ; Initialize F12x stackpointer 2. call #Init_Sys ; Initialize system D.
;-----------------------------------------------------------------------Init_Sys; Subroutine sets up Modules and Control Registers -----------------------------------------------------------------------Label Instruction Operands Comment 16. StopWDT mov #WDTPW+WDTHOLD,&WDTCTL ; Stop Watchdog Timer 17. SetupBC mov.b #DIVA1+RSEL2+RSEL0,&BCSCTL1 ; ACLK/4 RSEL=5 18. SetupP1_2 bis.b #TXD,&P1SEL ; P1.1/TA0 for TXD function 19. bis.b #TXD,&P1DIR ; TXD output on P1 20. SetupP2 bis.b #CS,&P2OUT ; CS, Set 21. bis.b #CS+CLK,&P2DIR ; CS and Clk Output direction 22. SetupTA mov #TASSEL1+TACLR,&TACTL ; SMCLK, clear timer 23. SetupC0 mov #OUT,&CCTL0 ; TXD Idle as Mark 24. call #Delay ; Time for crystal to stabilize 25. 26. 27. SetupWDT 28. 29. 30.
E.
bis call mov bis.b eint ret
Label Instruction 3. Mainloop bis
#MC1,&TACTL #Set_DCO #WDT_ADLY_16,&WDTCTL #WDTIE,&IE1
; ; ; ; ; ; ;
Start timer in Continous Mode Set DCO to target frequency WDT 16ms*4 Interval Timer Enable WDT Interrupt General Interrupt Enable Return from subroutine
Operands #LPM3,SR
4. Meas_ADC; 5. 6. 7. ADC_Loop 8. 9. 10.
Shift bic.b mov bis.b bic.b bit.b rlc.b
Comment ; Enter LPM3 ; TVL0831 data into ADCData, R15 used as counter #CS,&P2OUT ; Chip Select low #09,R15 ; 9 bits *1 start* + 8 data #CLK,&P2OUT ; Clock high #CLK,&P2OUT ; Clock low #DO,&P2IN ; DO -> C (carry) ADCData ; C -> ADCData
11. 12. 13.
dec jnz bis.b
R15 ADC_Loop #CS,&P2OUT
14. 15.
call jmp
#TX_ADC_2PC Mainloop
; ; ; ; ; ; ;
All shifted in? If not --> ADC_Loop Chip Select high ADC result --> PC Repeat
Figure7-15:SubprogramNo.1—anassembly-languageprogram—asoftwareshiftregister ProgramcourtesyofM.E.BucciniandTexasInstrumentsIncorporated TEAM LRN
120
ExamplesofAssembly-LanguageProgramming
SectionC SectionCbeginswiththefollowingline:
Label
Instruction ORG
Operands 0F000h
Comment
The“ORG”instruction,calledanassemblerdirective,tellstheassemblerwhereinmemorytoputthe startoftheprogram.Forthisprogram,itstartsatthehexadecimallocationF000(1111000000000000in straightbinary). 1. Thefirstlineofcodeis:
Label RESET
Instruction mov
Operands #0300h,SP
RESETisalabeltoidentifyalocationtowhichtheprogramgoeswhenthesystempoweristurnedon.The instruction“movesourcetodestination”meanstomovethesource,thehexadecimalnumber0300h,tothe destinationSP,thesymbolicnameforthestackpointer.TheassemblerknowsthatSPmeansregisterR1in theCPU,asshowninFigure7-2a,andloads0300intoR1.Recallthatthestackpointerstoresthereturn addressfromasubroutinecallsothattheprogramcanproceedafteritfinishesasubroutine.Thesourceis addressedwithimmediateaddressingandthedestinationwithsymbolicaddressing. 2. Thesecondlineofcodeis:
Label
Instruction call
Operands #Init_Sys
Theinstruction“call”isasubroutinecall.Itdirectstheprogram,withimmediateaddressing,toasubroutineatamemorylocationidentifiedas“Init_Sys.”
SectionD SectionDisthesubroutine“Init_Sys.”Itistheportionoftheprogramthatsetstheinitialconditionsofthe systembysettingbitsinthecontrolregistersthatwerediscussedpreviously.Thesubroutinestartsatline16. 16. Thesixteenthlineofcodeis:
Label StopWDT
Instruction mov
Operands #WDTPW+WDTHOLD,&WDTCTL
Thelineofcodeislabeled“StopWDT”asaclueofwhatishappening.Theinstruction“mov”meansto movethesourceWDTPW+WDTHOLDtothedestinationWDTCTL.Immediateaddressing(#sign)is usedforthesourceandabsoluteaddressing(&sign)forthedestination.WDTCTListhewatchdogtimer controlregistershowninFigure7-10.ThesymbolicnamesWDTPWandWDTHOLDload,fromthe referencelistintheAppendix,hexadecimalnumbersthatcorrespondtothesymbolicnames.05A00hisa passwordthatallowstheinstructiontowritetotheWDTCTL,andWDTHOLDsetstheHOLDbittoa1. Thisholds/stopsthewatchdogtimer. 17. Theseventeenthlineofcodeis:
Label SetupBC
Instruction mov.b
Operands #DIVA1+RSEL2+RSEL0,&BCSCTL1
Thelineofcodeislabeled“SetupBC”forsetupbasicclock.Theinstruction“movesourcetodestination,bytemode”meanstomovethelowerbyteofthesourceintothedestination,BCSCTL1,thebasic clocksystemcontrolregister.Immediateaddressingisusedforthesourceandabsoluteaddressingforthe TEAM LRN
121
ChapterSeven destination.Thesymbolicnamesinthesource,DIVA1,RSEL2ANDRSEL0,whenmovedtotheBCSCTL1,settherespectivebitstoa1.ReferringtoFigure7-9,settingDIVA1dividesthesourceforACLK, LFTX1by4,andsettingRSEL2(value=4)andRSEL0(value=1)meansRSEL=5,orthefifthresistor combinationtosetthenominalfrequencyoftheDCO. 18.Theeighteenthlineofcodeis:
Label SetupP1_2
Instruction bis.b
Operands #TXD,&P1SEL
ThelineofcodesetsupPort1,thus,labeled“SetupP1_2.”Theinstruction“setbitsindestination,byte mode”,meansthatthebinarynumberassociatedwiththesymbolicnameTXD,whichis002haccording toSectionB,isusedtosetthecontrolregisterP1SEL.002h,or00000010inbinary,setstheonebitin P1SEL.SettingtheonebitinP1SELmeansthatI/OpinP1.1willbeusedbyanotherfunctionotherthan Port1;inthiscase,fortheTXDfunctiontotransmitdatatothePC. 19. Thenineteenthlineofcodeis:
Label
Instruction bis.b
Operands #TXD,&P1DIR
Theinstructions“setbitsindestination,bytemode”againusesthehexnumberassignedtothesymbol TXD(002h)tosettheonebitinthedirectioncontrolregister,P1DIR,showninFigure7-12.Bitonewhen setmeansthatpinP1.1willbeanoutput. 20. Thetwentiethlineofcodeis:
Label SetupP2
Instruction bis.b
Operands #CS,P2OUT
Thelineofcodeislabeled“SetupP2”toindicateitissettingupPort2.Theinstruction“setbitsindestination,bytemode”meansthehexnumberassignedtosymbolCS(001hperSectionB)isusedtosetthe outputregisterP2OUT.ThezerobitofP2OUTisset,andthus,inthehighstate. 21. Thetwenty-firstlineofcode:
Label
Instruction bis.b
Operands #CS+CLK,&P2DIR
Theinstruction“setbitsindestination,bytemode”meansnowthesourceisCS+CLK;therefore,bothhex numbersassignedtothesymbolsCSandCLKwillsetbitsinthedestination,theP2DIRdirectionregister. ThissetsI/OpinP2.0andpinP2.1asoutputs.SincethezerobitofP2OUTisinthehighstate,pinP2.0will beinthehighstate.P2.0isthechipselectlinefortheTLV0831.Sinceitishigh,theTLV0831isnotactive. 22.Thetwenty-secondlineofcodeis:
Label SetupTA
Instruction mov
Operands #TASSEL1+TACLR,&TACTL
Timer_Aisbeingsetupbythelineofcodelabeled“SetupTA.”Theinstruction“movesourcetodestination”meanstomovethehexnumbersassociatedwiththesymbolicnamesTASSEL1andTACLRtothe Timer_Acontrolregister,TACTL,showninFigure7-11.SettingTASSEL1selectstheSMCLKclockas theTimer_AsourceandsettingtheCLRbitresetsTimer_A. 23. Thetwenty-thirdlineofcodeis:
Label SetupCO
Instruction mov
Operands #OUT,&CCTL0 TEAM LRN
122
ExamplesofAssembly-LanguageProgramming Thelabel“SetupCO”explainsthattheOUTbitinacapture/comparecontrolregisterisbeingset.The instruction“movesourcetodestination”issettingtheOUTbitofthecapture/comparecontrolregister, CCTLO.Effectively,theTXDbitstateisoutputontopinP1.1withthisinstruction.SincetheP1OUTisa 1,TXDwillbea1oraMARKintransmitlanguage.A0isdefinedasaSPACE. 24. Thetwenty-fourthlineofcodeis:
Label
Instruction call
Operands #Delay
Theinstruction“call”meanstheprogramiscallingasubroutinelabeled“Delay.”Thissubroutine,not showninoursubprogram,providesatimedelaywithsoftware.Thecrystaloscillatorusedasthesourcefor theclocksneedstimetostabilize.Theinstructioncallsthesubroutine,whichwhenexecuted,providesthe timedelayneededfortheoscillatortostabilize. 25. Thetwenty-fifthlineofcodeis:
Label
Instruction bis
Operands #MC1,&TACTL
Theinstruction“setbitsindestination”setstheMC1bitintheTACTLcontrolregister,showninFigure 7-11,byinsertingtheassignedhexnumber.WithMC1=1(andMC0=0),TimerAissetintothecontinuousmodeandstartscountingfrom0to0FFFFh.Whenitgetsto0FFFFhitrestartsfrom0. 26. Thetwenty-sixthlineofcodeis:
Label
Instruction call
Operands #Set_DCO
Theinstruction“call”thistimeiscallingthesubroutine“Set_DCO”whichisnotshowninoursubprogram. Itisasubroutinethatcalibratesthehigh-speed,digitally-controlledoscillator(DCO).Forthisprogram,the DCOiscalibratedto1,228,800Hz(cyclespersecond),andconfiguredtobethesourceforthemainsystem clock,MCLK,andsubsystemclock,SMCLK. 27. Thetwenty-seventhlineofcodeis:
Label SetupWDT
Instruction mov
Operands #WDT_ADLY_16,&WDTCTL
Labeled“SetupWDT”toexplainthatthewatchdogtimerisbeingsetup,theinstruction“movesourceto destination”movesthehexnumberassignedtothesourceWDT_ADLY_16bythereferencelisttothedestination,thewatchdogtimercontrolregister,WDTCTL,showninFigure7-10.Theassignedhexnumber 05A1Eprovidesthe5AthatisrequiredwhentheWDTCTLisbeingwrittento,andsetsbitsWDTTMSEL, WDTCNTCL,WDTSSELandWDTIS1.SettingWDTTMSELmakestheWDTanintervaltimer;settingCNCTLclearstheWDTCNTcounterandrestartsitatzero;settingWDTSSELselectsACLKforthe countersource;andsettingWDTIS1choosesa512divisionfactorforthetimeintervalwhichsetsthetime intervalbetweenpulsestobe62.5ms(milliseconds). 28. Thetwenty-eighthlineofcodeis:
Label
Instruction bis.b
Operands #WDTIE,&IE1
Theinstruction“setbitsindestination,bytemode”takesthesourcehexnumberassignedtothesymbolic nameWDTIE(01h)andplacesitintheinterruptenableregister,IE1.Itsetsthezerobit,whichenablesthe watchdogtimerinterrupt.Asaresult,becausethissignalisactivewhenthewatchdogtimerisintheintervaltimermode,thewatchdogtimerinterruptisenabled. TEAM LRN
123
ChapterSeven 29. Thetwenty-ninthlineofcodeis:
Label
Instruction eint
Operands
Theinstruction“enable(general)interrupts”setstheGIEbitinthestatusregistershowninFigure7-7and says“allinterruptsareenabled.”ThisallowstheinterruptgeneratedwhentheWDTintervaltimertimesout tointerruptthesystem,wakeitupfromtheLPM3modeandbeactive. 30. Thethirtiethlineofcodeis:
Label
Instruction ret
Operands
Theinstruction“returnfromsubroutine”tellstheprogramtoreturntothecodeaddressfollowingthesubroutinecall,inthisprogramtoline3.Theprogramhascompletedallinitialconditionsandnowreturnsto doitsmainoperations.
SectionE—MainApplication 3. Thethirdlineofcodeis:
Label Mainloop
Instruction bis
Operands #LPM3,SR
Thelabel“Mainloop”identifiesthislineofcodeasthestartofthemainportionoftheprogram.The instruction“setbitsindestination”takesthehexnumberassignedtothesource,symbolicnameLPM3,by thereferencelist,andsetsbitsinthedestination,SR.AsshowninFigure7-3,thehexnumberforLPM3 setsthebitsSCG1,SCG0andCPUOFFinthestatusregister.ThissetsthesystemintheLPM3low-power mode.RecallthatinLPM3,theCPUisinactivebutperipheralsandtheACLKclockareactive,and,inthis application,thattheWDTintervaltimerawakensthesystem. 4. Thefourthlineofcodeis:
Label Meas_ADC
Comment ;ShiftTLV0831dataintoADCData,R15usedascounter
Thecommentforthelabel“Meas_ADC”identifiesthatpartoftheprogramthatinitiatestheADCmeasurement,and,afterthedataispresent,shiftsthedataintotheregisterADCData.TheregisterR15willbeused tocountoffthenumberofshifts.Itscontentsdeterminethenumberofshifts. 5. Thefifthlineofcodeis:
Label
Instruction bic.b
Operands #CS,&P2OUT
Theinstruction“clearbitsindestination,bytemode”meansthatthehexnumberassignedtoCS(001h)in SectionBwillclearbitsinthedestination,P2OUT,theoutputregister.Immediateaddressingisusedforthe source,absoluteaddressingforthedestination.ThezerobitofP2OUTiscleared,and,asaresult,pinP2.0, isa0,orlow.P2.0istheCSsignaltotheTLV0831.Sinceitislow,itactivatestheTLV0831andstartsthe ADCconversion. 6. Thesixthlineofcodeis:
Label
Instruction mov
Operands #09,R15
Theinstruction“mov”meanstomovethesourcetothedestination.Thereisimmediateaddressingfor thesource;registeraddressingforthedestination.Asaresult,thenumber9isinsertedasthecontentsof TEAM LRN
124
ExamplesofAssembly-LanguageProgramming (movedto)register15todeterminehowmanybitsaregoingtobeshiftedontoDO.Asdiscussedearlier,a startbitisrequiredforoutputtingserialdata.Sincethedataiseightbits,thenumber9isloadedintoR15 withthe“mov”instruction.IftheADCwereconvertingtoalargernumberofbitsthaneight,thenR15 wouldhavetobeloadedwithacorrespondinglylargernumber. 7. Theseventhlineofcodeis:
Label ADC_Loop
Instruction bis.b
Operands #CLK,&P2OUT
“ADC_Loop”isasubroutinelabel.Theprogramwillcontinuetoadecisionpointandthenloopbackto thislabel.Theinstruction“setbitsindestination,bytemode”meansthatthesourcehexnumberassignedto “CLK”inSectionB(002h)willbeusedtosetbitsinthelowerbyteofthedestination,registerP2OUT,the outputregisterforPort2.Thus,theonebitofP2OUTwillbeset,andpinP2.1willhavea1orhighoutput. P2.1isconnectedtoCLKoftheTLV0831;therefore,CLKishigh. 8. Theeighthlineofcodeis:
Label
Instruction bic.b
Operands #CLK,&P2OUT
Theinstruction“clearbitsindestination,bytemode”meansthatthesamesourcehexnumberassignedto “CLK”(002h)willbeusedtoclearbitsinthelowerbyteofthedestination,theoutputregisterP2OUT. Thislineofcodeclearsbitsratherthansetthemasinline7.Asaresult,theonebitofP2OUTiscleared toa0,andpinP2.1willhavea0,oralow,onit.Thus,CLKfortheTLV0831isnowlow.AlowonCLK shiftsthedataontotheoutputDO,ontothepinP2.3oftheMSP430andintoregisterP2IN.Theshiftingof dataoccurswhentheCLKlineoftheTLV0831goeslowasshowninthetimingdiagramofFigure7-14b. 9. Theninthlineofcode:
Label
Instruction
Operands
bit.b
#DO,&P2IN
Theinstruction“testbitsindestination,bytemode”meansthatthesourcehexnumberassignedto“DO”in SectionB(008h)willbeusedtodesignatethattheeightbitofthedestinationP2INwillbetested.Andthe resultoftheoperationwillaffectthecarrybitofthestatusregisterintheMSP430.Onlythestatusregister bitsareaffected.IftheeightbitofP2INisa0,carrywillbea0;iftheeightbitisa1,carrywillbea1. 10. Thetenthlineofcodeis:
Label
Instruction rlc.b
Operands ADCData
Theinstruction“rotateleftthroughcarry”meansthatthecontentsoftheADCDataregisterisrotatedleft onepositionandthecarrybitofthestatusregisterisshiftedintotheLSBandtheMSBisshiftedintothe carrybit.Symbolicaddressingisused.Figure7-14cillustratestheresultoftherlc.binstruction.Thecarry bitfromthepreviousinstructionbecomesthecarrierofthedata.Whenthecarrybitisa0,theADCData registerbitisa0;whenthecarrybitisa1,theADCDataregisterbitisa1.TheADCDataregisterbecomes thetemporarystoragefortheoutputdatafromtheTLV0831untilalldataistransferred.Afterallthedatais collected,theADCDataregistercanbeoperatedonbytheMSP430CPU. 11.Theeleventhlineofcodeis:
Label
Instruction dec
Operands R15
Theinstruction“decrementdestination”meanstosubtractonefromthecontentsofregisterR15.Register addressingisused.RegisterR15hasthenumber9init.NineminusonemeansthecontentofR15isnow8. TEAM LRN
125
ChapterSeven Atthesametime,theregistercontentsaretestedandstatusbitsaresetinthestatusregister.TheZbitisthe onenotedinthenextinstruction,soitisthebitofinterest.HereistheruleforthetestoftheZbit:
StatusBit Z
Rule Setifdestinationregistercontains1,resetotherwise
IfdestinationregisterR15isotherthanzero,thentheZbitissettoa1. 12. Thetwelfthlineofcodeis:
Label
Instruction jnz
Operands ADC_Loop
Theinstruction“jumpifnotzero”teststhestatusregisterZbit.IfZisnot0,theprogramjumpstotheline intheprogramthathasthelabelADC_Loop,whichisline7.Symbolicaddressingisused.Theprogram againrunsthroughline7,8,9,10and11.Thisiscalledasubroutinejump,andthesubroutineloopbeing lines7,8,9,10and11. Whentheprogramreturnstoline7,itagainsetstheTLV0831CLKhigh.Line8thensetsthissameCLK lowtoshiftthesecondbittotheoutputDOandpinP2.3oftheMSP430.TheresultisrotatedintoADCDataandR15isdecremented.TheprogramagainteststheZbitandfindsitisnotzeroandjumpsbackto line7.Theprogramcontinuesinthelooprotatingeachbitinandsubtracting1fromR15untilthecontent ofR15iszero(9counts). WhenthestatusbitZiszeroasaresultofR15beingzero,theprogramnowdoesnotjumpbutcontinues toline13. 13.Thethirteenthlineofcodeis:
Label
Instruction bis.b
Operands #CS,&P2OUT
Theinstruction“setbitsindestination,bytemode”meansthatthehexnumberassignedtoCS(001h) willbeusedtosetbitsinthelowerbyteoftheoutputregisterP2OUT.Thus,thezerobitofP2OUTwill besetandpinP2.0willhaveahighoutput.P2.0isthechipselectfortheTLVO831,andwithithigh,the TLV0831isdeactivated. 14. Thefourteenthlineofcodeis:
Label
Instruction Call
Operands #TX_ADC_2PC
Theinstruction“call”tellstheprogramtogotothelabelTX_ADC_2PCthatisasubroutineintheprogram thattransmitsdatafromtheregisterADCDatatoapersonalcomputerusingaUART.Theprogramwillgo throughthesubroutineTX_ADC_2PC,whichisleftouttokeepthediscussionbrief.Whenitisfinished,it returnstotheprogramstepafterthesubroutinecall,step15. 15. Thefifteenthlineofcodeis:
Label
Instruction jmp
Operands Mainloop
Theinstruction“jmp”iscalledanunconditionaljumpinstruction.Itisaddressedwithsymbolicaddressing. TheprogramjumpstoMainloop,whichisthelabelonline3thatisthestartofSectionE,themeasuring portionofsubprogramNo.1.Thus,theprogramisreadytostartanothermeasuringcyclebyinitiatinga conversionbytheADC.
TEAM LRN
126
ExamplesofAssembly-LanguageProgramming
SubprogramNo.2 GeneralDescription Allsystemsneedaclocktosynchronizetimingofeventsoccurringasthesystemoperates.Thissubprogram setsuptheMSP430clockMCLKtouseLFXT1asitssource.LFXT1isoperatedinthehigh-frequency crystaloscillatormodeusingacrystalbetween1MHzand8MHz.AsmentionedinSubprogramNo.1,the crystaloscillatorrequiresacertaintimetostabilize;therefore,theprogramissetuptotestthecrystaloscillator,andonlyafteritisstable,willituseLFXT1asthesourceforMCLK.MCLKdrivesasoftwareloop thattakesexactly10clockcycles;therefore,itproducesaclocksignalthatdividesMCLKby10. Oneotherfeatureofthe MSP430isthatthereis a“failsafe”mechanism builtintotheclocksystem. Sincethecrystaloscillatorneedstimetostabilize, thereisadefaultmode whichusestheDCOas aclocksourceuntilthe crystaloscillatorisupand runningproperly.Even thoughtheDCOisnot asaccurateasthecrystal timing,theDCOkeepsthe systemtimedandoperatingproperlyfromthestart.
MSP430 *Microcontroller (MSP430F123) RESET RST/NMI
VCC
VCC
X IN Crystal (1 MHz − 8 MHz) X OUT
LFXT1 OSG with *MCLK = high f xtal (See Figure 7-5a)
VSS
P1.1
*MCLK/10
P2.0
ACLK
a.Blockdiagramshowingpinconnections 1— 1
2
3
4
5
6
7
8
9
10 11 12 13 14 15 16 17 18 19 20 21 22
MCLK 0—
time Theblockdiagramfor theapplicationisshown inFigure7-16aandthe MCLK P1.1 10 timingdiagraminFigure 7-16b.PinP1.1ofI/OPort time 1isusedasanoutputfor theMCLKdividedby10 b.Timingdiagram signal,andpinP2.0ofI/O Figure7-16:SubprogramNo.2application—outputtingclocks Port2isusedforanexternalclock,ACLK.Notethat thePinP1.1outputisanasymmetricalwaveform.
SectionA—InitialConditions ThesubprogramisshowninFigure17.Itisunderstoodthatforthissubprogramthesamereferencelistthat wasusedforSubprogramNo.1isusedagain.Otherveryspecificreferencelistscouldbeusedhereasin SubprogamNo.1,butarenotnecessary.Anyreferencelististobeusedbytheassemblertoinsertspecific hexadecimalnumbersassignedtoparticularsymbolicnames. SectionAbeginswiththefollowinglineofcode:
Label
Instruction ORG
Operands 0F000h
Theassemblerdirective“ORG”tellstheassemblertoputthestartoftheprograminmemorylocation 0F000h.ThesamelocationusedforSubprogramNo.1. TEAM LRN
127
ChapterSeven ;*************************************************************************** ;*************************************************************************** Label Instruction Operands Comment Label Instruction Operands Comment ;--------------------------------------------------------------------------A. ;--------------------------------------------------------------------------ORG 0F000h ; Program Start A. ;--------------------------------------------------------------------------ORG 0F000h ; Program Start ;--------------------------------------------------------------------------1. RESET mov.w #300h,SP ; Initialize stackpointer 1. mov.w #300h,SP stackpointer 2. RESET StopWDT #WDTPW+WDTHOLD,&WDTCTL ; Initialize Stop WDT 2. mov.w #WDTPW+WDTHOLD,&WDTCTL ; Stop 3. StopWDT SetupBC bis.b #XTS,&BCSCTL1 LFXT1WDT = HF XTAL 3. bis.b #XTS,&BCSCTL1 ; LFXT1 HF fault XTAL flag 4. SetupBC SetupOsc bic.b #OFIFG,&IFG1 Clear = OSC 4. bic.b #OFIFG,&IFG1 ; Clear fault flag 5. SetupOsc mov.w #0FFh,R15 R15 = OSC Delay 5. #0FFh,R15 ; R15 = Delay 6. SetupOsc1 mov.w dec.w R15 Additional delay to ensure start 6. R15 ; Additional delay to ensure start 7. SetupOsc1 dec.w jnz SetupOsc1 7. jnz SetupOsc1 ; OSC fault flag set? 8. bit.b #OFIFG,&IFG1 8. bit.b #OFIFG,&IFG1 ; OSC fault set? 9. jnz SetupOsc Fault,flag clear flag again 9. jnz SetupOsc clear flag again 10. bis.b #SELM1+SELM0,&BCSCTL2 ; OSC MCLKFault, = LFXT1 10. bis.b #SELM1+SELM0,&BCSCTL2 ; MCLK = LFXT1 ; P2.0 = output direction 11. bis.b #001h,&P2DIR 11. bis.b #001h,&P2DIR ; P2.0 = output direction 12. #001h,&P2SEL ACLK function 12. bis.b #001h,&P2SEL ; P2.0 function 13. #002h,&P1DIR P1.1 = ACLK output direction 13. bis.b #002h,&P1DIR ; P1.1 = output direction ; P1.1 = 1 14. Mainloop bis.b #002h,&P1OUT 14. bis.b #002h,&P1OUT ; P1.1 = 1 15. Mainloop bic.b 0 15. bic.b #002h,&P1OUT ; P1.1 = 0 16. jmp Mainloop Repeat 16. jmp Mainloop ; Repeat
a.AsymmetricalwaveformforoutputclockwithMCLK/10frequency 14. Mainloop 14. 15. Mainloop 15.
xor.b #002h,&P1OUT ; P1.1 = Toggle xor.b #002h,&P1OUT ; P1.1 = Toggle jmp Mainloop Repeat jmp Mainloop ; Repeat ; b.SymmetricalwaveformforoutputclockwithMCLK/12frequency
Figure7-17:SubprogramNo.2—assembly-languageprogram—outputtingclocks
1. Thefirstlineofcodeis:
Label RESET
Instruction mov.w
Operands #300h,SP
Whenpoweristurnedon,theprogramgoestothelineofcodelabeledRESETforitsinstruction“mov.w”. Theinstruction“movesourcetodestination”loadsthenumber0300hintothestackpointer.Thisinitializes thestackpointer.Notethe.wnotationhasbeenusedtoidentifytheinstructionasawordinstruction.Immediateaddressingisusedforthesource,andsymbolicaddressingforthedestination.Thereadershouldnow befamiliarwiththesenotationssoreferencetothemwillbediscontinuedunlesspertinenttothediscussion. 2. Thesecondlineofcodeis:
Label StopWDT
Instruction mov.w
Operands #WDTPW+WDTHOLD,&WDTCTL
Thelabel“StopWDT”explainstheinstructionisstoppingthewatchdogtimer.Theinstruction“mov.w” movesthehexadecimalnumbersassignedtothesymbolicnamesofthesource,WDTPWandWDTHOLD, tothewatchdogtimercontrolregisterWDTCTLtosettherespectivebits.ThepasswordWDTPWis5A00h towritetotheWDTCTLandsetWDTHOLD.Thisholdsorstopsthewatchdogtimer,andthus,itwillnot interruptthesystem. 3. Thethirdlineofcodeis:
Label SetupBC
Instruction bis.b
Operands #XTS,&BCSCTL1 TEAM LRN
128
ExamplesofAssembly-LanguageProgramming Setupbasicclockiswhatthelabel”SetupBC”means.Theinstruction“bis.b”means“setbitsindestination, bytemode”andthebinarynumberassociatedwiththesymbolicnameofthesource,XTS,willsetthatbit inthebasicclockcontrolregisterBCSCTL1showninFigure7-9a.WithXTSset,theLFTXT1clockwill operatewithahigh-frequencycrystaloscillatorasthesource. 4. Thefourthlineofcodeis:
Label SetupOsc
Instruction bic.b
Operands #OFIFG,&IFG1
Asindicatedbythelabel“SetupOsc”,theinstructionisusedtosetupthecrystaloscillatorusedforthe clock.Theinstruction“clearbitsindestination,bytemode”meansthatthebitinthehexnumberassociated withthesourceOFIFGwillbeusedtoclearaflaginthedestinationregisterIFG1.IFG1isaninterruptflag register.ThebitOFIFGisaninterruptflagforthecrystaloscillator.Ifthecrystaloscillatorisnot“upand running”theflagisset.Recallthatthecrystaloscillatorneedsacertaintimedelaybeforeitisoperating properly.WhentheOFIFGflagisnotset,theoscillatorisrunningproperly.Thisinstructionclearstheflag soitisinthecorrectcondition. 5. Thefifthlineofcodeis:
Label
Instruction mov.w
Operands #0FFh,R15
Theinstruction“movesourcetodestination,wordmode”meansthatthehexnumber0FFhwillbeloaded intoregisterR15.R15isgoingtobeusedasacounterwhosecontentdeterminesthetimedelaythatis setuptoallowthecrystaloscillatortostabilize. 6. Thesixthlineofcodeis:
Label SetupOsc1
Instruction dec.w
Operands R15
“SetupOsc1”isalabelidentifyingasubroutineloopthatisassociatedwiththecrystaloscillatordelaythat isrequired.Theinstruction“decrementdestination”subtractsonefromthecontentsofR15. 7. Theseventhlineofcodeis:
Label
Instruction jnz
Operands SetupOsc1
Theinstruction“jumpifnotzero”teststheZ(zero)bitinthestatusregister.Iftheresultoftheoperation inline6isnotzero,Zwillbezero,andtheprogramwilljumptothesubroutinelabel“SetupOsc1”which isline6.TheprogramwillstayinthissubroutineloopuntilRegister15contentsaredecrementedtozero. ThisproducesatimedelayofthetimethatisrequiredtocyclethroughtheloopuntilR15=0.Thetime delayisdeterminedbythevalueloadedintoR15inline5. WhenR15=0,thentheZbitwillbesetandtheprogramdoesnotjumptoline6butcontinuestoline8. 8. Theeighthlineofcodeis:
Label
Instruction bit.b
Operands #OFIFG,&IFG1
Theinstruction“testbitsindestination,bytemode”meansthatthesourcebit,theoscillatorfaultinterrupt flag,OFIFG,inthedestinationinterruptflagregisterIFG1,willbetested.Ifthecrystaloscillatorisnot completelystable,theflagwillbeset. 9. Theninthlineofcodeis:
Label
Instruction jnz
Operands SetupOsc TEAM LRN
129
ChapterSeven Theinstruction“jumpifnotzero”againteststheZbit.Iftheresultoftheoperationinline8isnotzero,i.e. theflagisset,Z=0andtheprogramwilljumptothesubroutinelabel“SetupOsc”whichisline4.Thus, theprogramreturnstoline4whereitclearstheoscillatorfaultinterruptflagbit,OFIFG,inregisterIFG1 andreloadsR15foranadditionaldelaytime.Theloopofline6and7decrementsR15untilthedelayis complete.ThefaultflagOFIFGistestedagaintoseeifitissetbyline8.Iftheoscillatorisstable,OFIFG willnotbeset,theresultwillbezeroandtheprogramdoesnotjumpbackonline9,butcontinuestoline 10.Iftheflagisset,thentheoscillatorisstillnotstable,andanotherpassthroughline4,5,6,7,8and9 addsadditionaldelay. 10.Thetenthlineofcodeis:
Label
Instruction bis.b
Operands #SELM1+SELM0,&BCSCTL2
Theinstruction“setbitsindestination,bytemode”willsetthebitsSELM1andSELM0ofthesource,in thedestinationregisterBCSCTL2asaresultofassignedhexnumbersfromthereferencelist.Referringto Figure7-9b,withSELM1andSELM0bothequalto1,thesourceLFXT1isselectedfortheMCLKclock. Whathashappenedistheprogramhasassuredthatthehigh-frequencycrystaloscillatorisupandrunning andstablebeforeitisusedasasourceforthemainsystemclock,MCLK. 11.Theeleventhlineofcodeis:
Label
Instruction bis.b
Operands #001h,&P2DIR
Theinstruction“setbitsindestination,bytemode”loadsthesource001hintothedestinationPort2directionregister,P2DIR.ThissetsthezerobitinP2DIRandmakespinP2.0anoutput. 12.Thetwelfthlineofcodeis:
Label
Instruction bis.b
Operands #001h,&P2SEL
Theinstruction“setbitsindestination,bytemode”loadsthesource,again001hintothespecialfunction registerP2SELandsetsthezerobit.ThismeansthatthepinP2.0isanoutputforanexternalclockACLK, ratherthanthePort2outputregisterP2OUT. 13.Thethirteenthlineofcodeis:
Label
Instruction bis.b
Operands #002h,&P1DIR
Theinstruction“setbitsindestination,bytemode”meansthatthesource002hisloadedintothedestination,thedirectionregister,P1DIR,tosettheonebit.ThissetspinP1.1asanoutput.
SectionB—Mainloop 14. Thefourteenthlineofcodeis:
Label Instruction Mainloop bis.b
Operands #002h,&P1OUT
Thelabel“Mainloop”indicatesthisisthestartofasubroutine.Theinstruction“setbitsindestination,byte mode”loads002hintothedestination,theoutputregisterP1OUT,andsetspinP1.1.ThismeansthatP1.1 isinthehighstate. 15.Thefifteenthlineofcodeis:
Label
Instruction bic.b
Operands #002h,&P1OUT TEAM LRN
130
ExamplesofAssembly-LanguageProgramming Theinstruction“clearbitsindestination,bytemode”clearstheonebit,identifiedbythesource002,inthe destinationP1OUToutputregister.Thus,pinP1.1isclearedtozero,alowstate. 16.Thesixteenthlineofcodeis:
Label
Instruction jmp
Operands Mainloop
Theinstruction“jumpunconditionally”directstheprogramtojumptothelineofcodelabeled“Mainloop”, line14.Thus,theprogramremainsintheloopandcyclesfromline14toline15toline16andbacktoline 14resultinginasquarewaveclockoutputonpinP1.1asshowninFigure7-16b.Theclockdrivingthe CPUisMCLK.Ittakesfourclockcyclesfortheprogramtoexecuteline14,fourclockcyclesforexecutingline15,andtwocyclestoexecuteline16;thusproducinganasymmetricalsquarewaveclockoutputon P1.1thatisone-tenththefrequencyofMCLK.ThisrelationshipisshowninthetimingdiagramofFigure 7-16b.Thus,twoclocksresultfromthesubprogram,oneonP1.1whichisone-tenththefrequencyofthe high-frequencycrystaloscillator,LFXT1,andtheotheranexternalclock,ACLK,onP2.0.
SectionB—MainloopModification BecausetheprograminFigure7-17aproducesanasymmetricalwaveformitmaynotbeasdesirableasa symmetricalwave;therefore,themainloopinstructionscanbemodifiedtoproduceasymmetricalwave. Steps14and15canbemodifiedasshowninFigure7-17b,andstep16isommitted. Withsteps14and15modified,theprogramproceedsfromstep14asfollows: 14.Thefourteenthlineofcodeis:
Label Mainloop
Instruction xor.b
Operands #002,&P1OUT
Thelabel“Mainloop”isthesameaspreviouslyandindicatesthisisthestartofasubroutine.Theinstruction“ExclusiveORofsourcewithdestination,bytemode”doesanexclusiveORlogicoperationwiththe source002handtheoutputregisterP1OUTandplacestheresultinthedestination,theP1OUTregister. SincepinP1.1isthe1bitoftheP1OUTregister,theresultoftheexclusiveORwillappearonpinP1.1.In thefirstexecutionofline14,ifthe1bitis0,theXORwilltogglethestateofthe1bit—itwillbea1and pin1.1willbea1.Inthenextpass,thebitwillbetoggledtoa0. 15.Thefifteenthlineofcodeis:
Label
Instruction jmp
Operands Mainloop
Theinstruction“jumpunconditionally”directstheprogramtojumptothelineofcodelabeled“Mainloop”,line14.Thus,theprogramremainsintheloopandcyclesfromstep14tostep15andbackagain. Theclock,aspreviously,drivingtheCPUisMCLK.Asaresult,forthismodification,ittakesfourcycles toexecuteline14andtwocyclestoexecuteline15.P1.1willnowhaveasymmetricalsquarewaveoutput withafrequencyequaltoMCLK/12.
SubprogramNo.3 GeneralDescription Hereisaprogramthatoutputsavisualsignalwhenaninputvoltageisatorgreaterthanaparticularvalue. TheblockdiagramisshowninFigure7-18a.ThistimeaTLC549ADCisused.Itisan8-bitanalog-to-digital converterthatconvertstheinputanalogvoltageintoan8-bitcodethatisshiftedintotheMSP430microcontrollerregisterR11labeledADCData.ThereisanLED(light-emittingdiode)onI/OoutputpinP1.0. TEAM LRN
131
ChapterSeven
Theassembly-languageprogram isshowninFigure7-19.Againas withSubprogramsNo.1andNo.2, “SectionA,”“SectionB,”“Section C,”“SectionD”and“SectionE” havebeenaddedtoaidindescribing theprogram.
SectionsAandB SectionAandBarespecifictothis subprogram.SectionAagainis clarifyingthatregisterR11isidentifiedwithalabel“ADCData”and thatregisterR12isidentifiedwitha label“Counter.”Theyaretwoofthe 16-bitworkingregistersasshownin Figure7-2a.
VCC
ADC VCC
P2.0 P2.1 P2.3
CS CLK DO
VIN
X IN
RST/NMI R11
ADC DATA AIN+
VCC
MSP430 Microcontroller (MSP430F123)
RESET
TLC549
X OUT
R
LED
P1.0
P2OUT
INVERTER
P2IN
a.Blockdiagramshowinginterconnections 256 224 Register R11 Contents
Whentheinputvoltageisequalor greaterthan+0.5VCC,thenthevalue ofthecontentsofR11willbeequal toorgreaterthan+0.5VCC,andthe LEDwillbelit.Foranyinputvoltagelessthan+0.5VCC,theLEDwill notlight;therefore,onecanstartat VIN=0andadjusttheinputvoltage towardVCC.Whentheinputvoltage isat+0.5VCCtheLEDwillglowto indicate+0.5VCChadbeenreached.
192
0BF
160 128
07F
96 64
03F
32
25%
50%
75%
100%
% VCC
b.R11contentversus%VCC
SectionBisagainanadditiontothe Figure7-18:SystemapplicationimplementedbySubprogramNo.3 standardreferencelistintheAppen- energizinganoutputwheninputisgreaterthan+0.5V CC dixfortheMSP430.Inthesection, thespecifichexadecimalnumbersshownareassignedtosymbolicnamesthattheassemblersubstitutesinto theprogramwhenthesymbolicnamesareusedintheprogram.
SectionC—InitialConditions Theprogramstartsinmemoryataddress0F000hestablishedbytheORGinstruction.
Label
Instruction ORG
Operands 0F000h
Theassemblerbeginsthisprogramatthesamelocationinmemory(0F000h)usedforSubprogramsNo.1 andNo.2.Theninitialconditionsaresetupfortheprogramwithsteps1through5.BitsinthecontrolregistersdiscussedinFigures7-7to7-11willbesettocontroltheinitialconditions. 1. Thefirstlineofcodeis:
Label RESET
Instruction mov.w
Operands #0300h,SP
Thetypeofaddressingmodeshouldnowbefairlywellunderstoodsoreferencetotheaddressingmodes willbeomittedtosimplifythediscussion.Thelabel“RESET”identifieswheretheprogramstartswhen TEAM LRN
132
ExamplesofAssembly-LanguageProgramming ; A. #define ADCData R11 #define Counter R12 B. CS equ 001h ; P2.0 − Chip Select CLK equ 002h ; P2.1 − Clock DO equ 008h ; P2.3 − Data Out ;--------------------------------------------------------------------------C. ORG 0F000h ; Program Start ;--------------------------------------------------------------------------1. RESET mov.w #300h,SP ; Initialize 'x112x stack 2. StopWDT mov.w #WDTPW+WDTHOLD,&WDTCTL ; Stop Watchdog Timer 3. SetupP2 mov.b #CS,&P2OUT ; /CS set, − P2.x reset 4. bis.b #CS+CLK,&P2DIR ; /CS and CLK outputs 5. SetupP1 bis.b #001h,&P1DIR ; P1.0 output D. 6. Mainloop 18. 19. 20. 21. 22.
call bic.b cmp.w jlo bis.b jmp
#Meas_549 #01h,&P1OUT #07Fh,ADCData Mainloop #01h,&P1OUT Mainloop
; Call subroutine ; P1.0 = 0 ; ADCData > 0.5Vcc? ; Again ; P1.0 = 1 ; Again ; ;--------------------------------------------------------------------------E. Meas_549; Subroutine to read TLC549, data is shifted into ADCData ; (R11), Counter (R12) is used as a bit counter. ;--------------------------------------------------------------------------7. mov.w #8,Counter ; 8 data bits 8. clr.w ADCData ; Clear data buffer 9. bic.b #CS,&P2OUT ; /CS reset, enable ADC 10. ADC_Loop bit.b #DO,&P2IN ; (4) DO -> C (carry) 11. rlc.w ADCData ; (1) C -> ADCData 12. bis.b #CLK,&P2OUT ; (4) Clock high 13. bic.b #CLK,&P2OUT ; (4) Clock low 14. dec.w Counter ; (1) All bits shifted in? 15. jnz ADC_Loop ; (2) If not --> ADC_Loop 16. bis.b #CS,&P2OUT ; /CS set, disable ADC 17. ret ; Return from subroutine ;
Figure7-19:SubprogramNo.3—Anassembly-languageprogramenergizingan outputwheninputisgreaterthan+0.5VCC
poweristurnedon,oraresetisperformed.Theinstruction“movesourcetodestination”movesthesource 0300htothestackpointer,thespecialfunctionregisteridentifiedbythesymbolicnameSP.Whenaprogramcompletesasubroutineitwillreturntotheaddressonthestack. 2. Thesecondlineofcodeis:
Label StopWDT
Instruction mov.w
Operands #WDTPW+WDTHOLD,&WDTCTL
Thewordinstruction“movesourcetodestination”setsbitinthedestination,thewatchdogtimercontrol registerWDTCTL,sothatthewatchdogtimerisputonhold.ThesymbolicnameWDTPW(5A00h)allows writingtoWDTCTLandthesymbolicnameWDTHOLDsetsthatbitinWDTCTLtoholdthewatchdog timerandstopitfrominterruptingthesystem. 3. Thethirdlineofcodeis:
Label SetupP2
Instruction mov.b
Operands #CS,&P2OUT TEAM LRN
133
ChapterSeven Thelabel“SetupP2”identifiestheinstructionasonetosetuptheI/OP2.The“movesourcetodestination, bytemode”takes001hassignedtothesourceCSandmovesittotheP2OUTregistertosetthezerobitof P2OUTorpinP2.0toa1.P2.0isthechipselectlinetotheTLC549. 4. Thefourthlineofcodeis:
Label
Instruction bis.b
Operands #CS+CLK,&P2DIR
Theinstruction“setbitsindestination,bytemode”meansthatbitsintheP2DIRcontrolregisterwillbeset tocontrolwhetherthepinsoftheP2I/OwillbeoutputsperFigure7-12.Ifthepinsarenotsettheywillbe inputs.001hofCSsetsthezerobitofP2DIRand002hofCLKsetstheonebitofP2DIR;therefore,pin P2.0andpinP2.1areoutputsfromtheMSP430.SinceP2.0isa1,orhigh,andisthechipselectlineforthe TLC549,theTLC549isinactive. 5. Thefifthlineofcodeis:
Label SetupP1
Instruction bis.b
Operands #001h,&P1DIR
ThislineofcodeisgoingtosetupI/OP1asindicatedbythelabel“SetupP1”.Theinstruction“setbitsin destination,bytemode”withthesource,001h,setsthezerobitofthedirectioncontrolregisterP1DIRso thatpinP1.0isanoutput.
SectionD—MainApplication 6. Thesixthlineofcodeis:
Label Mainloop
Instruction call
Operands #Meas_549
Thelabel”Mainloop”identifiesthelocationintheprogramasthestartofthemainpartoftheprogram—the partoftheprogramthatmeasurestheinputtotheTLC549ADC.The“call”instructiontellstheprogramto jumptothesubroutinelabeled“Meas_549.”The“Meas_549subroutinestartswiththeseventhlineofcode. 7. Theseventhlineofcodeis:
Label
Instruction mov.w
Operands #8,Counter
Theinstruction“movesourcetodestination,wordmode”meansthatthesource,thehexnumber8willbe movedtoregister12whichhasbeenassignedthesymbolicname“Counter.”Itwillbeusedtocountthe eightbitsofthedataoutputoftheTLC549ADC. 8. Theeighthlineofcodeis:
Label
Instruction clr.w
Operands ADCData
Theinstruction“cleardestination,wordmode”meansthatregisterR11identifiedwiththesymbolicname “ADCData”willbeclearedtozero. 9. Theninthlineofcodeis:
Label
Instruction bic.b
Operands #CS,&P2OUT
Theinstruction“clearbitsindestination,bytemode”meansthatthehexnumberassignedtoCS(001h)will beusedtoclearthezerobitofthedestination,theoutputregisterP2OUT;therefore,pinP2.0willbereset to0oralow.SinceP2.0isthechipselectlineoftheTLC549,thisactivatestheTLC549tomeasureits inputanalogvoltageandconvertittoan8-bitdigitalcoderepresentingthevalueoftheinputvoltage. TEAM LRN
134
ExamplesofAssembly-LanguageProgramming 10.Thetenthlineofcodeis:
Label ADC_loop
Instruction bit.b
Operands #DO,&P2IN
Thelabel“ADC_loop”identifiesthelineofcodeasthestartofasubroutineloop.Theinstruction“testbits indestination,bytemode”meansthatthesourcehexnumberassignedto“DO”insectionB(008h)willbe usedtodesignatethattheeightbitofthedestinationP2INwillbetested.Theresultoftheoperationwill affectthecarrybitofthestatusregisterintheMSP430.Onlythestatusregisterbitsareaffected.Iftheeight bitofP2INisa0,carrywillbea0;iftheeightbitisa1,carrywillbea1. 11.Theeleventhlineofcodeis:
Label
Instruction rlc.w
Operands ADCData
Theinstruction“rotateleftthroughcarry”meansthattheADCDataregisterisrotatedleftonepositionand thecarrybitofthestatusregisterisshiftedintotheLSBandtheMSBisshiftedintothecarrybit.Referto thediagraminFigure7-14c.Thecarrybitfromthepreviousinstructionbecomesthecarrierofthedata. Whenthecarrybitisa0,theADCDataregisterbitisa0;whenthecarrybitisa1,theADCDataregister bitisa1.TheADCDataregisterbecomesthetemporarystorageforthedataastheeightbitsofdataare shiftedintotheregister. 12.Thetwelfthlineofcodeis:
Label
Instruction bis.b
Operands #CLK,&P2OUT
Theinstruction“setbitsindestination,bytemode”meansthehexnumberassignedtothesourceCLK (002h)willbeusedtosettheonebitoftheP2OUTregistersothatpinP2.1willbeatahighlevel.P2.1is tiedtotheCLKinputoftheTLC549. 13.Thethirteenthlineofcodeis:
Label
Instruction bic.b
Operands #CLK,&P2OUT
Theinstruction“clearbitsindestination”meansthatthesamebitintheP2OUTregisterasintheprevious instructionisnowclearedbackto0,oralowlevel.ThepinP2.1,beingtheclockfortheTLC549,means thatwhentheclockgoeslowthenextbitfromtheADCdataisshiftedoutontheDOlineoftheTLC549. 14.Thefourteenthlineofcodeis:
Label
Instruction dec.w
Operands Counter
Theinstruction“decrementdestination”meanstosubtractonefromthecontentsofregisterR12,theregisteridentifiedbythesymbolicname“Counter.”Sincethisisthefirstpassthroughtheloop,R12willnow haveacontentsequaltoseven,sincetheregisterwasoriginallyloadedwiththevalueeight. 15.Thefifteenthlineofcodeis:
Label
Instruction jnz
Operands ADC_loop
Theinstruction“jumpifnotzero”teststhestatusregisterZbitwhichwillbea1or0basedontheresultof theinstructioninline14.Iftheresultofline14isnotzero,Zwillbe0,andtheprogramjumpstotheline intheprogramthathasthelabelADC_loop,whichisline10.Whentheresultofline14iszero,Zwillbe 1,andtheprogramwillnotjump,butcontinueontothenextinstruction.Theprogramwillcontinueinthe TEAM LRN
135
ChapterSeven loopfromline10toline15untilthecontentsofR12,thecounterregister,reachzero.Whenthecontents havethevalueofzero,itmeansthattheeightdatabitshavebeenshiftedoutontoDO.Whenthecontentsof R12iszero,theprogramdoesnotjump,butcontinuestoline16. 16.Thesixteenthlineofcodeis:
Label
Instruction bis.b
Operands #CS,&P2OUT
Theinstruction“setbitsindestination,bytemode”meansthehexnumber001hassignedtoCSisusedto setthezerobitoftheP2OUTregistersothatpinP2.0issettoahighlevel.SinceP2.0isthechipselectof theTLC549,theTLC549isdisabledanditsconversionceases. 17.Theseventeenthlineofcodeis:
Label
Instruction ret
Operands
Theinstruction“returnfromsubroutine”meanstheprogrampicksupthereturnaddressfromthestack pointerwhichistheaddressofthenextlineofcodeafterthesubroutinecall.Asaresult,theprogramreturnstoline18,thenextinstructionafterline6. 18.Theeighteenthlineofcodeis:
Label
Instruction bic.b
Operands #01h,&P1OUT
Theinstruction“clearbitsindestination,bytemode”meansthatthezerobitoftheP1OUTregisterdesignatedbythesource01hwillbecleared;therefore,pinP1.0willbeclearedtoazero,orlowlevel. 19.Thenineteenthlineofcodeis:
Label
Instruction cmp.w
Operands #07Fh,ADCData
Theinstruction“comparesourceanddestination”meansthatADCDataiscomparedtothehexnumber 07Fh,andthebitsinthestatusregisteraresetaccordingly. 20.Thetwentiethlineofcodeis:
Label
Instruction jlo
Operands Mainloop
Theinstruction“jumpiflower”meansthattheresultoftheoperationinline19governswhathappensin thisinstruction.IfADCDataregistercontentsarelowerthan07Fh,thentheprogramjumpsto“Mainloop”, anothersubroutineMeas_549iscalledandanotherADCconversionisaccomplishedastheprogramgoes throughthesubroutinefromline7throughline17.ThiscontinuesagainifADCDatacontentsarestill lowerthan07FH(whichis127ofatotalof256ofthefull-scalecontentofADCData.Thevalue127isless than0.5VCC,whereVCCisrepresentedbythefull-scalevalueof256. WhentheADCDataregistercontentsaregreaterthan07Fh,thentheprogramdoesnotjumpbackto“Mainloop”butcontinuesontoline21. 21.Thetwenty-firstlineofcodeis:
Label
Instruction bis.b
Operands #01h,&P1OUT
Theinstruction“setbitsindestination,bytemode”meansthatthezerobitoftheP1OUTregisterdesignatedbythesource01hwillbesettoaone,orahighlevel.Asaresult,pinP1.0willbesettoa1.Thishigh levelonP1.0willlighttheLEDthatisconnectedtoP1.0. TEAM LRN
136
ExamplesofAssembly-LanguageProgramming 22.Thetwenty-secondlineofcodeis:
Label
Instruction jmp
Operands Mainloop
Theinstruction“jump”tellstheprogramtojumpunconditionallytothelineofcodelabeled“Mainloop”or line6.Line6callsthesubroutine“Meas_549”andthewholemeasuringprocessbeginsagain.
VariationofThreshold ThethresholdvoltageatwhichthesystemturnsontheLEDcanbeadjustedbasedonthebinarynumberused forthecomparisonintheinstructionofline19.TherelationshipofthecontentsofR11,theregisterlabeled asADCData,tothepercentageofVCCisshowninFigure7-18b.For+0.5VCC,thebinarynumberusedinthe comparisoninstructionwas07Fh,oronelessthanthebinarynumberof08Frepresentingexactly+0.5VCC. Inlikefashion,thebinarynumberusedforline19is03Fhfor+0.25VCCand0BFh+0.75VCC.Otherbinary numbersperFigure7-18bwouldadjustthetriggerthresholdtoaselectedpercentagelevelofVCC.
Summary Inthischapterthereaderisexposedtothetechniquesusedtoprograminassemblylanguage.TheTexas InstrumentsMSP430microcontrollerwaschosenasthedigitalprocessortousetoexplainassembly-language programming.Usingitsspecificinstructionset,thebasicsofwritinganassembly-languageprogramwere discussed.Threeassembly-languageprogramswerediscussedindetailtohelpthereaderunderstandthe conceptsofassembly-languageprogramming.Withanassembly-languageprogram,anassembler—aspecific softwareprogramwrittentoconverttheassembly-languageprogramintomachinecode—mustbeusedbefore theprogramcanbeappliedinasystem.Thenextchapterwilldealwiththetechniquesofdatatransmission.
TEAM LRN
137
ChapterSeven
Chapter7Quiz 1. 2. 3. 4. 5. 6. 7. 8. 9.
ARISCmicrocontrolleris: a. areduced,minimizedcomponentCPU. b. amuchmorecomplicatedCPUdesign. c. basedonareduced-instruction-setCPU. d. aCPUwithreducedperipheralsaroundit. AvonNeumannarchitecture: a. isrectangularandtriangularinnature. b. hasaseparatebusforprogrammemoryanddatamemory. c. hasaseparatebusjustforperipherals. d. hasprogram,datamemoryandperipheralsallsharingacommonbusstructure. AperipheralmoduleintheMSP430familycanbe: a. eithera16-bitoran8-bitmodule. b. canonlybea16-bitmodule. c. canonlybean8-bitmodule. d. amodulewithonly5-bits. TheperipheralsintheMSP430family: a. use16-bitsexclusivelyforaddressing. b. useboth8-bitand16-bitaddresses. c. use8-bitsexclusivelyforaddressing. d. use12-bitsexclusivelyforaddressing. TheoperatingmodeoftheMSP430microcontrolleris: a. determinedbytheI/Oinputnumberone. b. determinedbythestateoftheCPU. c. determinedbyfourcontrolbitsinthestatusregister. d. allofabove. Interruptscontrolthedigitalprocessor: a. atspecificwelldefinedtimes. b. atunexpectedorrandomtimes. c. atthesametimeeverytime. d. atregularpredeterminedrepeatingtimes. TimersareusedinaMSP430system: a. tokeeptrackofelapsedtime. b. tosettimeintervalswithinwhichspecificactionsoccuroraretooccur. c. toproduceresets,alertsorwarnings. d. noneofabove. e. allofabove. WhenasourceordestinationinaMSP430instructionhavetheform&ADDR,theaddressingmodeis: a. symbolicmode. b. registermode. c. absolutemode. d. indexedmode. TheMSP430statusregister,R2: a. hasnineactivebits. b. hasbitswhosestatedictatesthataparticularactionhasoccurred. TEAM LRN
138
ExamplesofAssembly-LanguageProgramming c. isoneofsixteen16-bitregistersintheCPU. d. allofabove. c. noneofabove. 10.TheMSP430statusregisterbit: a. Nissetwhentheresultofabyteorwordoperationisnegative. b. Zissetwhentheresultofabyteorwordoperationiszero. c. Cissetwhentheresultofabyteorwordoperationproducesacarry. d. alloftheabove. e. noneoftheabove. 11.TheMSP430clocksystemcontrolregistersare: a. registersR4,R5andR6. b. BCSCTL1,BCSCTL2andDCOCTL. c. registersR7,R8andR9. d. registersR13,R14andR15. 12.IftheXTSbitintheBCSCTL1controlregisterissettoa1: a. TheLFXT1oscillatorintheclocksystemcanoperatewithahigh-frequencycrystal. b. theLFXT1oscillatorisOFF. c. theLFXT1oscillatorintheclocksystemcanoperatewithalow-frequencycrystal. d. itisa“don’tcare”conditionfortheLFXT1oscillator. 13.WhentheSELSbitintheBCSCTL2controlregisterisresetto0: a. theDCOCLKisOFF. b. theSMCLKisdividedby8. c. thesourcefortheSMCLKclockisLFXT1oscillator. d. thesourcefortheSMCLKclockisDCOCLK. 14.IntheMSP430,thewatchdogtimercontrolbitWDTTMSEL: a. issetto1sothatthewatchdogtimerisanintervaltimer. b. isresetto0tohavethewatchdogtimerinactive. c. isnotafactorintheoperationofthewatchdogtimer. d. isthebitthatrestartsthewatchdogtimer. 15.TheWDTCTLcontrolregistermusthave: a. allitshigh-bytebitsat0. b. a069hpasswordautomaticallyinsertedinthehighbytewhenWDTCTLisread. c. apasswordof05AhinthehighbyteiftheinstructionistowritetoWDTCL. d. allitshigh-bytebitsat1. e. onlybandcabove. f. onlyaabove. 16.IntheMSP430systemallI/Oports: a. areinitiallyoutputswhenthesystempowersup. b. remainconstantastheapplicationsprogramproceeds. c. varywitheachstepoftheprogram. d. areinitiallyinputswhenthesystempowersup. 17.TosetanexternalpinofanI/Oporttobeanoutput: a. theassociatedbitofPxDIRdirectionregistermustbesetto1. b. theassociatedbitofPxSELfunction-selectregistermustbesettoa1. c. theassociatedbitofthePxINregistermustbesettoa1. TEAM LRN
139
ChapterSeven d. theassociatedbitofthePxOUTregistermustbesettoa1. 18.WhenanexternalpinontheMSP430I/Oportisprogrammedtobeaninput: a. thedirectionregisterbitassociatedwiththepinisresettoa0. b. thePxINregisterbitassociatedwiththepinissettowhatevertheinputdatadictates. c. thePxOUTregisterbitassociatedwiththepinisinactive. d. allofabove. e. aandconlyabove. f. noneofabove. 19.WhenanassemblerprogramfortheMSP430seesasymbolicname: a. ithasbeenprogrammedtointerrupttheprocessor. b. ithasbeenprogrammedtoresetthesystem. c. ithasbeenprogrammedtoinsertaspecificbinarynumberthatrepresentsthesymbol. d. ithasbeenprogrammedtodisregardthesymbolicname. 20.SymbolicnamereferencelistspreparedfortheMSP430family: a. areusedexclusivelyfortheI/Obits. b. areusedextensivelyforsettingupinitialconditionsforthesystem. c. areusedsparinglyinassembly-languageprogramming. d. areusedtodevelopspecialsymbolsunrelatedtoactualregisterbits. 21.Labels: a. identifyparticularpositionsinaprogram. b. bearnorelationshiptotheprogram. c. areonlyusedattheendofaprogram. d. arenotveryusefulinprogrammingmicrocontrollers. 22.The.binaninstructionmeans: a. itisdealingwitha16-bitword. b. theinstructionispartofasubroutine. c. theinstructionistobeusedlaterintheprogram. d. itisabyteinstructiondealingonlywiththe8bitsinthelowerbyteofaword. 23.Operandsare: a. specialtypesofANDlogiccircuits. b. theportionoftheinstructionthatidentifieswhatquantitieswillbeoperatedonusingthe instruction. c. specialamplifiersusedinsignalconditioningasignal. d. thefirstcomponentinaninstructionline. 24.Hexadecimalnumbers: a. usebitpositionsthatareentirelydifferentthanbinarycodes. b. cannotbemanipulatedeasilyinbinarysystems. c. usenumbersfrom0to9andlettersfromAtoFtoidentifythe16possiblecodeswhenusinga 4-bitcode. d. usenospecialnotationstoidentifytheminprograms. 25.Assembly-languageprogramming: a.helpstograsptheconceptofprogramming. b.helpstolearnprogrammingdetails. c.helpstogetfamiliarwithprogrammingformat. d.allofabove. TEAM LRN
140
ExamplesofAssembly-LanguageProgramming e. bandconlyabove. 26.Inassembly-languageprogrammingfortheMSP430: a. “syntaxicsubstitution”isthetechniqueofsubstitutingnumbersforwordsinaprogram. b. theprograminstructionsareconvertedtomachinecodebyanassembler. c. specificregistersusedforgiventasksmaybedefinedinareferencelist. d. thenumbersusedinthe“syntaxicsubstitution”aredefinedinareferencelist. e. allofabove. f. canddonlyabove. 27.Inassembly-languageprogrammingfortheMSP430,alabel: a. hasmanyusesbutoneimportantoneistoidentifyasubroutine. b. onlyprovidesreferencetoaparticularactioninaprogram. c. haslittlemeaninginaprogram. d. isthemostprominentwaytosetinitialconditions. 28.Inanassembly-languageprogramfortheMSP430: a. a.wafteraninstructionmeansadecimalinstruction. b. a.wafteraninstructionmeansahexadecimalinstruction. c. a.wafteraninstructionmeanstobranchtoanotherlocation. d. a.wafteraninstructionmeansitisanoperationusingaword(twobytes). 29.Inassembly-languageprogrammingfortheMSP430: a. a#signbeforeanoperandmeansitisregister-modeaddressing. b. a#signbeforeanoperandmeansitisimmediateaddressing. c. a#signbeforeanoperandmeansitisabsolute-modeaddressing. d. a#signbeforeanoperandmeansitissymbolic-modeaddressing. 30.InMSP430programmingusingassemblylanguage: a. areferencelistisveryimportanttosyntaxicsubstitution. b. theprogrammingdependstotallyonsyntaxicsubstitution. c. areferencelistisnotimportanttosyntaxicsubstitution. d. allsyntaxicsubstitutionreferencelistsareconstantforanyapplication.
Answers:1.c,2.d,3.a,4.b,5.c,6.b,7.e,8.c,9.d,10.d,11.b,12.a,13.d,14.a,15.e,16.d,17.a,18.d,19.c, 20.b,21.a,22.d,23.b,24.c,25.d,26.e,27.a,28.d,29.b,30.a. TEAM LRN
141
C H APTER 8
DataCommunications Introduction Atypicalrequirementofsystemsdescribedinthisbookisthatdigitalinformationmustbetransported fromonelocationtoanother,fromonepieceofdigitalequipmenttoanother.Thetwolocationsmaybe veryclosetoeachother,ortheymaybeseparatedbyagreatdistance.Inthischapter,datacommunication systemswillbediscussedandseveraltechniquesusedtotransmitandreceivedigitaldatawillbeexamined.
TheDataTransmissionSystem Figure8-1showsatypical digitaldatacommunications Transmitter Receiver system.AnydigitalcommuniModem Modem cationmusthaveatransmitter, Transmission Main Frame receiverandatransmission Computer DTE DCE DCE DTE Computer Link medium.Thetransmitterpre(wire or wireless) paresthedigitalinformation DTE DTE fortransmission,thereceiver DTE DTE DTE DTE Video Video Printer Scanner Printer Copier detectsandpresentsthedigital Monitor Monitor informationinoriginalform, andthetransmissionmedium Receiver Transmitter transportstheinformation, Figure8-1:Datacommunicationsystem hopefullywithoutmodifyingit orproducingerrors.Thetransmissionmediummaybetwistedpairwire,wiresincables,fiberopticcableorwirelesstransmissions.
DTEandDCE InFigure8-1,adataterminalequipment,DTE,iscoupledtoapieceofdatacommunicationsequipment,a DCE.ThemostcommonDCEisamodemthatconvertsthedigitaldataintosignalsthatmatchtherequirementsofthetransmissionmedium.Averycommonarrangementisamodemthatcouplestoatelephone line.TheDTEinthiscommoncaseisacomputer.Infact,theDCE(modem)iscontainedrightinthecomputer,andtheDTEandDCEcombinationbecomesthetransmitterforthisdatacommunicationssystem. Atthereceivingend,anotherDCE(again,anothermodem)receivesthedatafromthetransmissionmedium,decodesitandpresentsittoaDTEfortransformation,manipulation,modificationand/ordisplay.As showninFigure8-1,eachcombinationofDTEandDCEcaneitherbeatransmitterorareceiverdepending onthedirectionoftransferofdata. AlsoshowninFigure8-1isthefactthataDTEcanbeacomputer,aprinter,oravideomonitor,andthat besidetheDTEtoDCEandDCEtoDTEdatacommunication,thereisandcanbedatatransfersfroma DTEtoaDTE.
ParallelandSerialTransmission Therearetwomainmethodsofcommunicatingdigitaldatafromoneplacetoanother,eitherparalleltransferorserialtransfer.Figure8-2showsthedifferencebetweenthetwo.ParalleltransferisshowninFigure TEAM LRN
142
DataCommunications 8-2a.Herethereareasmany separatesignallinesasthereare bitsofdatainthedigitalsignal. Ifthebitsinthedatachange, allbitschangeatthesame time.Inotherwords,thereis aninformationfrontthatmoves togetheronthelines,andwhen achangeinthedataismadeall lineschangeatthesametime.
t = tx
Wire 8 Wire 7 Wire 6 Wire 5 Wire 4 Wire 3 Wire 2 Wire 1
Transmitter
Bit 8 = 0 (odd parity) Bit 7 = 1 MSB Bit 6 = 0 Bit 5 = 1 Bit 4 = 0 Bit 3 = 1 Bit 2 = 1 Bit 1 = 1 LSB
Receiver
Contrastthistoserialtransferof Info flow datashowninFigure8-2b.Here a.ParalleltransferofinformationforASCII“W”(oddparity) thereisonlyoneline,andifone t = tx wouldsitontheline,thedigital 7 character bits bitsrepresentingtheinformation Start Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 Bit 7 Parity Stop wouldpassbyonebitafterthe (1) Mark bit bit other—inseries,thus,thename serialdata.Additionaldatamust (0) Space LSB MSB beaddedtothedigitaldatato 8 data bits makesureitisrecognized.A 11 bits per character startbitmustbeaddedtotell whenthedatastarts,andastop b.SerialtransferofinformationforASCII“W”(oddparity) bitisaddedtotellwhenthedata Figure8-2:Parallelandserialdatatransmission stops.Aparitybit,whichwillbe discussedlater,isaddedtoaidincorrectingerrors.
Stop
MajorDifferences PARALLEL SERIAL Themajordifferencesbetween Lines Required One line/bit Single line parallelandserialtransferare Bit Sequence On all lines at same time One bit following another showninFigure8-3.Asnoted, Speed Faster Slower serialtransfersrequireonlyone Transmission line length Usually a short distance Both long and short distances line,whileparalleltransfers Cost More expensive Less expensive Critical Characteristic Time relationship of bits Needs start, stop bit requirealineforeachbitof themultiple-bitcharacterbeing Figure8-3:Comparisonofparallelandserialcommunications Figure 8-3: Comparison of Parallel and Serial Communications transferred.Ifamomentoftime ispicked,txinFigure8-2a,each linewillhaveabitvaluecorrespondingtothedigitalcodeforthecharacterbeingtransferred,1110101for Figure8-2a.Whileinaserialtransfer,asshowninFigure8-2b,thebitvalueswillcomeoneafteranother att=tx.First,thestartbit,thenthecharacterbits,aparitybitandthenthestopbit.Thus,thespeedoftransferringofdataforserialcommunicationsisslowerthanforparallel.Inparallelcommunications,allthebits arriveatthesametime,whileinserialcommunications,onemustwaituntilallbitsarrive.
Itisverydifficultinparallelcommunicationstokeepthetimerelationbetweenbitsthesameforeachlineas thedistanceofthetransmissionincreases;therefore,theconnectingcablesareusuallyshort—acomputerto aprinter,oronecomputertoanother,oracomputertoavideomonitor.Thereareparallelcommunications thatoccuroverlongdistancesthatusewhatiscalledapackettechniqueandoverspecialtransmissionlines oronmicrowavelinks.Thesearediscussedbriefly,andthenexplainedabitfurtherfortheUSBprotocol, TEAM LRN
143
ChapterEight butarereallybeyondthescopeofthisbook.Moredetailedtextsarerequiredtoexplainitfully.Serialcommunications,ontheotherhand,usingthelatesttechnology,normallyoccursoververylongdistances. Theequipmentrequiredforserialcommunicationsislessexpensivesinceonlyonelineisofconcern ratherthanmultiplelinesinparallelcommunications.If10-bitcharactersarebeingtransmittedinparallel,theequipmentmultipliesbyatleast10timesoverwhatitisforserialcommunications.Inparallel communications,oneofthecriticalcharacteristicsisthetimerelationshipofsignalsontheline.Inserial communications,additionalinformation—astartandstopbit—mustbeaddedtobeabletorecognizeand detecttheinformation.
Example1.ShiftRightfromRegister ShowthebitstorageinthelowerbyteofRegisterR5foranASCIIcapitalNandthewaveformgeneratedastheASCIIcodeisshiftedrightoutoftheregister.Oddparityistobeused.TheASCIIcodeis showninFigure8-5. Solution:
This bit inserted for error correction (odd parity) 8
7
0
1
Register 5 lower byte 6 5 4 3 2
0
0
1
MSB
1
1
stop
1
Parity 1 1
0
0
1
1
1
0 start
0 LSB
time Clock
Chapter 8 Example 1 Illustration
Protocols
“Protocolisthenamegiventohardwareandsoftwarerulesandproceduresformakingsurethatany transmissionerrorsaredetected.” 1 Datacommunicationsmustfollowcertainrulesandproceduresasnoted bytheabovequote whetheritbethehardwareused,theelectricalsignallevels,thesignaltiming,orthe softwareused.Figure8-4showsoneoftheearliestprotocols,theRS-232interface.Itwasused,andisstill usedtoday,toconnecttogetheralltypesofdatacommunicationsequipment.
PROTECTIVE GROUND
+25 V
SECONDARY TRANSMITTED DATA TRANSMIT CLOCK SECONDARY RECEIVED DATA
SPACE
RECEIVER CLOCK
+5 V*
+3 V** 0V − 3 V**
−5 V*
UNASSIGNED SECONDARY REQUEST TO SEND DATA TERMINAL READY SIGNAL QUALITY DETECTOR
MARK
RING INDICATOR
−25 V**
DATA RATE SELECT
* Transmitter ** Receiver
TRANSMIT CLOCK UNASSIGNED
TRANSMITTED DATA RECEIVED DATA REQUEST TO SEND CLEAR TO SEND DATA SET READY SIGNAL GROUND DATA CARRIER DETECT RESERVED RESERVED UNASSIGNED SECONDARY DATA CARRIER DETECT SECONDARY CLEAR TO SEND
a.Signallevels b.Physicalconnections(female) Figure8-4:RS-232protocol 1
UnderstandingDataCommunications,G.E.Friend,etal.©1984,TexasInstrumentsIncorporated. TEAM LRN
144
DataCommunications InFigure8-4a,theelectricalcharacteristicsofanRS-232signalareshown.Thetwobinarylevelsareidentifiedas“Mark”and“Space.”IntheRS-232protocol,thereceiverrecognizesanypositivesignalfrom+3V to+25Vasaspace,andanynegativesignalfrom–3Vto–25Vasamark.Thetransmitter,ontheotherhand, byspecification,producesaspacesignallevelbetween+5Vand+25V,andamarksignallevelbetween–5V and–25V.ThemechanicalconnectoranditsassociatedpinconnectionsareshowninFigure8-4b. NowlookagainatFigure8-2b.Herethemarkisidentifiedasthe1levelandthespacethe0level.Inmoderndayelectronics,duetotheinfluenceofintegratedcircuits,andduetoT2LandCMOSlogiccircuitry,the 1ormarkisahighlevelfrom+2.4Vto+5V,andthe0orspacelevelisalowlevelof+0.4Vto0V.When theRS-232protocolwasset,themaximumtransferspeedwas20,000bitspersecond,andthemodem speedswerenohigherthan9600baudpersecond.USB,whichwillbediscussedlater,isamuchmore recentprotocolforserialdatacommunicationsandcantransferdataat4millionbitspersecond.
High-SpeedDataTransmissions Asindicated,paralleldatacommunicationsarelimitedbythelengthoftheparallelwirecables;therefore, differenttechniquesareusedforsuchcommunications.Microwave,fiberoptics,satellitesareusedforthe transmissionmedium.Thedigitaldataisgroupedintoframesandpacketstoallowthedatatobetransmittedatmillionsofbitspersecond.Errordetectionandcorrectionbitsareaddedtotheformatsothatthe datacanbecommunicatedefficientlyandwithouterroratgreatspeeds.Thisispossiblebecauseofthevery widebandwidthprovidedbymicrowave,fiberopticandsatellitetransmissionlinks.Eventhoughdigital datacommunicationsrequiremorebandwidththananalogsignals,theverywidebandwidthissufficient andavailabletoallowhigh-speeddigitaldatatransmissionsateverincreasingspeeds.
SerialDataCommunicationsAdvances Themostcommondatacommunicationstodayareserialcommunications.Eventhoughthebitsofacharacterflowinseriesoneafteranother,theadvancesintechnology,especiallyinthespeedatwhichdigitalICs canprocessdigitalinformation,haveadvancedsothatthetransferspeedshavekeptupwiththeindustry. Asaresult,theemphasisfortherestofthischapterwillbeonserialdatacommunications.Thediscussion startswithareturntoFigure8-2b.
AReturntotheFormat Thetwolevels,MarkandSpace,willbeexaminedfurther.Thesetermscomefromthetelegraphera.A penattachedtothearmatureofthesounderinatelegraphsystemwouldmakeamarkonpapermoving underthepenasthearmaturewasactivatedwiththeincomingsignal.Withnoactivationofthearmature, thepaperwouldjustspace.Asthenamesforthetwolevelscontinuedtobeused,themarkwasthestate,of twoavailable,inwhichtherewasacurrent.Spacewasidentifiedasthestateofnocurrent.Stillfurtheruse gavetheidlingstatethenameof“Mark”eventhoughcurrentwasflowing.Inthisbook,correspondingto acceptedIClogiclevel,a“Mark”isthehighlevelora1,anda“Space”isthelowlevelora0.TheRS-232 levelsdiscussedbeforearereallynegativelogiclevelswitha“Mark”beingthemostnegativevoltagelevel ora1,andtheleastnegativevoltagelevel(themostpositivelevel)a“Space”ora0.
Start,DataandStopBits AsshowninFigure8-2b,astartbitidentifiesthestartofthedatatransfer.Itisgeneratedbychangingthe levelfroma1toa0.Followingthestartbitarethebitsusedtodeterminethedata.Sevenbitsareusedinthis examplebecauseacommonbinarycodeusedfortextdatatransferistheASCII(AmericanStandardCode forInformationInterchange)codeshowninFigure8-5.TheASCIIcodefor“W”wasusedinFigure8-2.
TEAM LRN
145
ChapterEight Bit Positions: 7 6
0 0 0
5 4
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
3 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
2 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
DLE SP DC1 ! DC2 ” DC3 # DC4 $ NAK % SYN & ETB ‘ CAN ( ) EM SUB * ESC + FS , GS − RS . US /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [
’ a b c d e f g h i j k l m n o
p q r s t u v w x y z { | }
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI
]
^ —
Examples:
A a j k zero space (SP) CR EOT
7
6
5
4
3
2
1
bit
1 1 1 1 0 0 0 0
0 1 1 1 1 1 0 0
0 0 0 0 1 0 0 0
0 0 1 1 0 0 1 0
0 0 0 0 0 0 1 1
0 0 1 1 0 0 0 0
1 1 0 1 0 0 1 0
(carriage return) (end of transmission)
~ DEL
Figure8-5:ASCIIcode Figure 8-5: ASCII Code Followingthesevenbitsofdata,thereisaparitybitandoneortwostopbits.Incasethedataiseightbits, therewouldbeaparitybitandonlyonestopbit.Thestopbitisacontinuous1leveloridlecondition.
ParityBit Theparitybitisabitofinformationaddedtotheoriginaldata toallowforerrordetection.Thebitisaddedbythetransmitter tomakethesumofall1bitsinthecharactertransmissioneither oddoreven.Theerrordetectionmethodiscalledoddparityifthe sumofthe1bitsismadeodd;itiscalledevenparityifthesum ofthe1bitsismadeeven.Figure8-6showsexamplesofhowthe transmitteraddsthebitstomakeoddandevenparity.
7-bit ASCII Code Bit
1
2
3
4
5
6
7
B Q 3 z
0 1 1 0
1 0 1 1
0 0 0 0
0 0 0 1
0 1 1 1
0 0 1 1
1 1 0 1
Parity Parity Bit Bit (odd) (even) 1 0 1 0
0 1 0 1
These bits added by transmitter
Atthereceiver,circuitscountthenumberof1bitsinthecharacter Figure 8-6: Odd and Even Parity Figure8-6:Oddandevenparity thatistransferred.Thesystemhasbeensetuppreviouslytooperateeitherwithoddorevenparity.Supposethesystemisoperating usingoddparity.Ifthecountersalwayscountoddnumbersof1sasthecharactersaretransmitted,the receiverprocessesthedataascorrect.If,however,the1countturnsupeven,thereceiverflagstheinformationasincorrectandprobablyasksforittoberetransmitted.Evenparitycallsforthereceivertocountan evennumberof1s,andthedatawillbeprocessedascorrectaslongasthecountremainseven.Thereceiver onlyflagsthedataasincorrectwhenthecountisodd.
Example2.OddandEvenParity Whatwilltheoddandevenparitybitbeforthedigitalcodesgiven? Codes Solution: 8
0 0 0 0 0 0
7
0 0 1 0 1 0
6
0 1 0 1 1 1
5
0 0 0 1 1 1
4
1 1 1 1 1 1
3
0 0 1 0 1 0
2
1 1 1 1 1 1
1
bit
0 0 1 0 0 1
TEAM LRN
Chapter 8 Example 2146 Illustration
Parity Bit for
Odd Parity 1 0 0 1 1 0
Even Parity 0 1 1 0 0 1
DataCommunications
BaudRate InFigure8-2bsevenbitsareusedfortheASCIIcharacterandfourbitsareadded—astart,parityandtwo stopbits.Thetotalbitspercharacteriseleven;therefore,thenumberofbaudis11.Supposetherateof transmissionis10characterspersecond.Thebaudratewillbecharacterspersecond×totalbitspercharacter,or,inthisexample,10×11=110baudpersecond.Moderntelephonemodemsoperatecommonlyat 56,000baudpersecond.
Example3.BaudRate Whatisthebaudrateofan8-bitdatawordwithastart,parityandonestopbitwhenthetransmission rateis500characterspersecond? Solution: No.ofbitsinserialword=8+1+1+1=11characters Transmissionrate=500/sec Baudrate=500×11=5500baud/sec
ShiftRegisters Theshiftregisterwasdiscussed previouslyinChapter6.Itisamain componentofaserialcommunication system,anddatacanbemanipulated inanumberofways,asshownin Figure8-7,inordertoarriveasserial data.InChapter7,themethodshown inFigure8-7f,rotatedataleft,was usedtotransferdatatothedataregisterinthemicrocontroller,andisthe sameasthecirculateexample,inthis case,left,discussedpreviously inChapter6.
PARALLEL DATA OUT
SERIAL DATA OUT
SERIAL DATA IN
a.Serialshiftright
SERIAL DATA IN
SERIAL DATA OUT
b.Serialshiftleft—serialin, serialorparallelout
PARALLEL DATA IN
SERIAL DATA OUT
PARALLEL DATA IN
Also, usually has serial data input.
c.Parallel-in,serial-out
PARALLEL DATA OUT
d.Parallel-in,parallel-out
e.Rotatedataright
f.Rotatedataleft
Figure8-7:Varioustypesofshiftregisters CourtesyofMasterPublishing,Inc.
Example4.ParallelIn—SerialOutShifting ShowthecontentsofregisterR10foreach clockcycleasa4-bitwordistransferred inaparalleltransferandstoredinR10.A logicalshiftrightisthenmadetoexamine thebits,onebyone.The4-bitcodeloaded inR10is0110.
Solution: 0
1
1
0
0
1
1
0
0
0
1
1
0
0
0
0
1
10
0
0
0
0
110
0
0
0
0
0110
RI0 Clock 1 2
Insert 0
3
Insert 0
4
Insert 0
5
Insert 0
TEAM LRN
147
Parallel In
Chapter 8 Example 4 Illustration
ChapterEight
USARTSerialCommunications Auniversalsynchronous/asynchronousreceiver/transmittercalledaUSARTisaDCEusedextensivelyfor serialcommunications.Therearetwoprotocolsused—oneforsynchronoustransmit/receiveandtheother forasynchronous.Intheasynchronousmode,theserialbitstreamisataprogrammedtransmissionratedeterminedbyaninternalclockinthetransmitter.Inthesynchronousmode,thetransmissionrateisprovided byacommonclock,eitherinthetransmitterorthereceiver. AsimplifiedblockdiagramofaUSARTisshowninFigure8-8a,andtheformatforthedata,atypical serialformat,isshowninFigure8-8b.Theblockdiagramshowsanoutput,TXD,forthetransmitteddata, andaninput,RXD,forthereceiveddata.MostUSARTscantransmitandreceiveatthesametime.If theycannotdo thedualfuncsync Sync = 0 Asynchronous Mode tion,thereisa Sync = 1 Synchronous Mode R/W(read/write) Receive Buffer R/W (Read, write) controllinethat Receive determinesthe RXD (Receive) Shift Register modeofoperation.TheUSART Baud Control hasasyncsignal CLK Rate Generator tosetwhetherthe operatingmode issynchronous Transmit Parity TXD Shift Register Mark (Transmit) orasynchronous, D D D D D D D D A P S S andsomeadTransmit Space Buffer ditionalcontrol Data Bits Start Address Stop bit signals.The bit bits USARTisin b.Signalformat a.Blockdiagram b. Signal format a. Block Diagram thesynchronous modewhenthe Figure8-8:SimplifiedUSART Figure 8-8: Simplified USART syncsignalisa1. 0
1
2
3
4
5
6
7
D
A
SynchronousSerialCommunications Forsynchronousserialcommunicationsthereisamasterunitandaslaveunit.Sincethereisacommon clock,the MASTER mastergenerSLAVE SIMO SIMO atestheclock Receive Buffer Transmit Buffer Transmit Buffer Receive Buffer SYNC SYNC andtheslave dependson STE thisclockfor STE itstiming.The SOMI SOMI dataformatis Receive Shift Register Transmit Shift Register Transmit Shift Register Receive Shift Register stillasshownin MSB LSB MSB LSB MSB LSB MSB LSB Figure8-8b. CLK Clock CLK USART
Figure8-9isa blockdiagram oftwoUSARTs communicating
Generator
USART
SYNC = 1 for synchronous operation Courtesy of Texas Instruments Incorporated
Figure8-9:TwoUSARTscommunicatinginsynchronousmode FigureCourtesyofTexasInstrumentsIncorporated 8-9: Two USARTs Communicating in Synchronous Mode
TEAM LRN
148
DataCommunications witheachotherinthesynchronousmode. Theleftunitisthemaster,whichsupplies theclock,andtherightunitistheslave.The mastertransmitsdataattheclockrate.The slaveusestheclocktoshiftinformationin andout.TheSTEsignal,controlledbythe master,enablestheslavetotransmitdataas wellasreceivedata.Themasterandslave sendandreceivedataatthesametime.Data isshiftedoutofthetransmitshiftregisteron oneclockedgeandshiftedintothereceive shiftregisterontheoppositeedge.ThetimingisshowninFigure8-10.
Tx Data
Rx Data
Clock
Shift out Tx Data
Shift in Rx Data
Figure 8-10: Shifting Out Tx Data and Shifting In Rx Data Figure8-10:ShiftingoutTxdataandshiftinginRxdata
Themasteroutputofthetransmitshift registeriscoupledthroughtheslave-in,master-out(SIMO)linetotheslavereceiveshiftregister,whilethe slaveoutofthetransmitshiftregisteriscoupledthroughtheslave-out,master-in(SOMI)linetothemaster receiveshiftregister.Thedatamovesatasynchronizedratedeterminedbytheclocksuppliedbythemaster. Therightunitcouldjustaswellbethemasterandthelefttheslave,andtheoperationisthesame.Thebaud rateisprogrammedintoandcontrolledbyabaud-rategeneratorthatisderivedfromtheclockinthemaster.
AsynchronousSerialCommunications Asynchronous MASTER SLAVE SIMO SIMO serialcommunications Receive Buffer Transmit Buffer Receive Buffer Transmit Buffer SYNC SYNC betweentwo STE USARTsis STE shownin Figure8-11. SOMI SOMI Receive Shift Register Transmit Shift Register Transmit Shift Register Receive Shift Register Thereagainis LSB MSB LSB MSB LSB MSB LSB amasteranda MSB CLK Clock Clock CLK slave,andthe USART Generator Generator USART dataformatis SYNC = 0 for asynchronous operation thesameas Figure8-11:TwoUSARTscommunicatinginasynchronousmode Figure8-8b, buttheframes CourtesyofTexasInstrumentsIncorporated ofdatadonot alwaysarriveinregularperiods.Theremaybesignificantrandomidleperiodsbetweenframes(greaterthan 10bittimes)asshowninFigure8-12.Thereisnophysicalinterconnectionofclocksignalsfrommasterto slave.Theprogrammedmasterclocksetsthetransmissionasynchronousserialcommunicationsrate. AsshowninFigure8-11,themasteristhetransmitterandtheslaveisthereceiver.Whenthefirstsignals arereceived,thereceiveradjustsitsclocktomatchtheclockrateofthereceivedsignalandusesthisclock idle time > 10t1
idle time > 10t1
XXX
XXXXXXX
XXXXXXX
Frame
Frame
t1
idle time > 10t1
XXXXXXX
XXXXXXX
XXX
Frame
Frame
Frame
Figure8-12:Asynchronousserialcommunication TEAM LRN Figure 8-12: Asynchronous Serial Communication
149
ChapterEight toshiftinthereceiveddata.Transmissionintheasynchronousmodeisonlyoneway.Inorderfortheslave totransmittothemaster,therolesoftheslaveandmastermustbereversed.Theslavebecomesthemaster, thatoriginatestheclock,andthemasterbecomestheslave.Nointerconnectionsneedchange,butcontrol signalsmustchange.Dependingonthedirectionthatthedataistoflow,therolesofthemasterandslave reverseastheflowofdatareverses.
TheUARTFunctionwithSoftware. SubprogramNo.1ofChapter7essentiallyimplementedashiftregisterusingsoftware.Expandingonthe techniqueusedthere,theUARTfunctioncanbeimplementedwithsoftware.Itisnotcoveredhere,butthis wouldbeachallengingprojectforateamofstudentsthatcomeincontactwiththisbook.
TechnologyAdvances Twoadvancesintechnologywillbecitedtodemonstratenewtechniquesthathavebeendevelopedtoincreasethetransferrateofdigitalinformationusingserialcommunications.ThefirstistheInter-ICserialbus.
I2CBus AserialcommunicationsproprietaryprotocolthatwasdevelopedbyPhilipsSemiconductor2,istheI2Cbus. Itwasdevelopedprincipallyforinter-ICcontrol,thusthenameI2C.AllICsthatareI2C-buscompatible haveon-chipinterfacesthatcommunicatedirectlywithotherI2C-buscompatibledevices.Serial,8-bit,bidirectionaldatatransferscanbemadeinthreemodes:
1. Standard—100kbits/sec 2. Fast—400kbits/sec 3. High-Speed—3.4Mbits/sec
Master UNIT A (transmitter)
Master addresses slave Transmits data to receiver
Slave UNIT B (receiver)
Thetwo-linebushasaserialdataline(SDA)andaserial a.UnitAsendsinformationtoUnitB clockline(SCL).Itisasynchronoussystemandrequiresa Master addresses slave Master Slave clock.Theunitthatinitiatesthedatatransferisthemaster. UNIT A UNIT B Italsoistheunitthatgeneratestheclock,andinitiates, (receiver) Slave transmits to master receiver (transmitter) permits,andterminatesthetransfer.Ifthemasterwantsto communicatewithanotherunit,itsendstheaddressofthat b.UnitAreceivesinformationfromUnitB unitonthedataline.Theunitthatisaddressediscalledthe Figure8-13:I2Cmasterandslave slave.Themasterandtheslavecanbeeitheratransmitter canbetransmitterorreceiver orareceiver.ExamplesareshowninFigure8-13.Figure 8-13ashowsamastertransmittingtoaslavereceiver;andFigure8-13bshowstheslavetransmittingback tothemaster,nowusedasareceiver.Thebusdesignallowsmultiplemastersandslavesonthebus.
I2CProtocol ElectricalConnections Figure8-14ashowstheinterconnectionofdevicesinsideunitsconnectedtothebus.Essentially,theSDA lineandtheSCLlineareheldinthehighlevelbypull-upresistorsuntilcontroltransistorsareactivated topullthelinelow.ItisalargewiredANDconnectionwithopencollector(bipolar)oropendrain(MOS) connectionsfromthedevicestothelines.AsSDAisactivatedbydataandSCLbyclockpulses,thelines arepulledlowbytheactivedevices.Alowlevelisdefinedasamaximumof0.3Vdd,andahighlevelasa minimumof0.7Vdd.VddistypicallytheT2Llogiclevelof5V.
2
I2C-BusSpecification,V2.1,PhilipsSemiconductor. TEAM LRN
150
DataCommunications Open Drain AND + VDD RP
RP
Data Line SDA
Pull-up resistors
L − Write H − Read Slave R A Data Address W
S
Clock Line SCL
A
A
P
t
S − Start Data In
Data
R/W − Read/write
sense
A − Acknowledge A − Not Acknowledge
sense
Clock In
P − Stop
a.I2Cbusschematic
c.Exampleofformatformastertransmitterslave-receiver
Valid Data SCL = H SDA = L or H SDA
0.7VDD 0.3VDD
SCL
0.7VDD 0.3VDD Stop SDA = L to H SCL = H
Data Transition SDA = H to L L to H SCL = L
Start SDA = H to L SCL = H
b.Start,stop,validdataanddatatransitiontiming Figure8-14:I2Cprotocol
SignalTiming Figure8-14bshowsthenecessarytimingofinformationonthebus.Togeneratethenecessarystartbit, SDAmustbepulledfromhightolowwhiletheSCLlineishigh.DataonSDAisvalidonlywhileSCL ishigh,anddatacannotchange(withouterror)unlessSCLislow.AstopbitisgeneratedwhenSDAgoes fromlowtohighwhenSCLishigh.Thus,thestartbit,databitandstopbitrequirementoftheserialformat issatisfied.
Example5.I2CData Determinethedatabitsin theI2Cwaveformshown. SeeFigure8-14bforsignal protocol.
H
Data Waveform
SDA L H SCL L time
Solution: SDA:
H to L L to H
H
H
H
H to L
L
L
L
L to H
H
H
H
H
L
H
L
H
L
H
L
H
L
H
L
H
L
H
Start
*
1
*
1
*
0
*
0
*
1
*
1
*
Stop
SCL: Bit:
* Transition
TEAM LRN
151
H to L L to H
ChapterEight
Format Anexampleoftheserialformatforamaster-transmittertoaslave-receiverisshowninFigure8-14c.The formatstartswithastartbit,thentheaddressfromthemastertoidentifytheslave,thenalowontheR/W bit,andfinallythedata.Datacontinuestobesentbythetransmitterasacknowledgementbits(A)areplaced onthebusbythereceiver.Whennoacknowledgementisreceived,themaster-transmittersendsastopbit.
USB Anotherstillmoreadvancedserialdatacommunicationsprotocolistheuniversalserialbus(USB).Itis beingusedextensivelytocommunicatedatafromDTEtoDTE,fromDTEtoDCEandfromDCEtoDTE. UsingUSB,serialdatacanbetransferredatthreedifferentrates.UsingUSBlowspeed,thetransferrateis 1.5millionbits/sec;usingUSBfullspeed,thetransferrateincreasesupto12millionbits/sec;andusing USBhighspeed,thetransferrateisupto480millionbits/sec.Thediscussionsinthischaptercenteron USBlowspeedandfullspeed.ThereaderislefttoinvestigatethespecificationsforUSBhighspeed. TheconnectingcableusedisshowninFigure8-15.It isa4-wiresystem,usingatwistedpairforD+and D–datalines,andpowerlinesofVBUSandGND.Ituses auniquefeatureofdifferentialdetectionofdataonthe D+andD–lines.
USBNetwork
Twisted pair +5V
VBUS
VBUS
D+ D−
D+ D− GND
GND
Figure8-15:4-wireUSBcable Figure 8-15: 4-Wire USB Cable
AtypicalUSBnetworkisshowninFigure8-16.It consistsofahost,whichcontainsahostcontroller,and separateUSBdevices.Thesedevices,asshown,caneitherbeafunctionorahub.AfunctionisaUSB devicethatisabletotransmitorreceivedataorcontrolinformationoverthebus.Itcontainsinformation aboutitscapabilitiesandtheresourcesthatitneeds.Examplesoffunctionsaremousecontrollers,light pens,keyboards,printers,scanners,andsoforth. HubsareUSBdevicesthatexpandtheUSBbusinterconnections.Theyallowtheattachmentofmultiple USBdevices.Thehost,asshowninFigure8-16,canbeconnectedtoafunctionorahub,andthathubcan beconnectedtootherhubsorotherfunctions.Inaddition,thereisoverridingsoftwarethatmanagesthe bus.USBpermitsthehosttoconfigureahubandmonitorandcontrolitsports. Thehostisresponsibleforknowingwhendevicesareconnectedordisconnectedfromthebus,formanagingthedataflowbetweenUSB devices,andforthestatusofthe Upstream bus.Thehostassignsaunique USB Device addresstoadeviceattachedtoit. (Function) Host Itdeterminesifthenewdeviceisa (Host USB Device Controller) huborafunction.Ifthedeviceis (Function) USB Device afunction,thehostrecognizesthis (HUB) andconfiguresit.Ifthedeviceis Downstream USB Device ahub,thehost’ssoftwareestab(Function) USB Device lishestheuniqueaddressesandend (HUB) pointsforalldevicesattachedto USB Device (Function) thehub.AllUSBdevicessupport acommonmeansforaccessinginFigure 8-16: USB Network Figure8-16:USBnetwork formationtocontroltheendpoints. TEAM LRN
152
DataCommunications
USBElectricalConnections Figure8-17showstheUSB electricalinterconnections ofthebus.Thehostcontrollerisrequiredtohavearoot hubthatcontainsatransceiver.Allhubs,including theroothub,arerequiredto supportbothfull-speedand low-speeddatatransfers. Functionsmayjustsupport lowspeed.
Upstream +5V
VBUS +5V
+3.0 − 3.6V * 1.5K
D+ Root Hub with Transceiver
Host Controller
D+ 15K
D−
ZO = 90 Ω
* Full-Speed ** Low-Speed Transceiver
** 1.5K D−
15K GND
GND Function or Hub Downstream
Figure 8-17: USB Interconnections Figure8-17:USBinterconnections Transmissionfromthe hostiscalleddownstream; transmissiontothehostiscalledupstream.Atthehost,roothub,andanyexternalhub,theD+andD–lines atdownstreamportseachhavea15kΩpull-downresistortoground.Onaportfeedingupstreamfroma deviceorhub,a1.5kΩpull-upresistorisconnectedbetweentheD+lineandavoltagesupplyfrom+3.0V to+3.6V.Ifitisalow-speeddevice,the1.5kΩresistorisconnectedfromtheD–linetothevoltagesource. Anexternalhubisaspecialcasethathasboth1.5kΩresistorsonup-streamportsand15kΩpull-down resistorsonthedownstreamports.TheimpedanceoftheUSBcableis90Ω.VBUSisnominally+5Vatthe source.ThehostsuppliespowertoUSBdevicesdirectlyconnectedtoit.Ahubsuppliespowertoitsconnecteddevices;however,someconnecteddeviceshaveinternalpowersources.
BusTransceivers Thedetailsofthetrans3.0V