287 58 3MB
English Pages 329 Year 2004
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 dst
Description
The source operand is added to the destination operand. The source operand is not affected. The previous contents of the destination are lost.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
R5 is increased by 10. The jump to TONI is performed on a carry.
ADD.W
src,dst
#10,R5 TONI
; Carry occurred ; No carry
R5 is increased by 10. The jump to TONI is performed on a carry. ADD.B JC ......
3-22
or
Set if result is negative, reset if positive Set if result is zero, reset otherwise Set if there is a carry from the result, cleared if not Set if an arithmetic overflow occurs, otherwise reset
ADD JC ...... Example
src,dst src,dst
#10,R5 TONI
; Add 10 to Lowbyte of R5 ; Carry occurred, if (R5) ≥ 246 [0Ah+0F6h] ; No carry
RISC 16–Bit CPU
TEAM LRN
206
TheMSP430InstructionSet Instruction Set
ADDC[.W] ADDC.B
Add source and carry to destination Add source and carry to destination
Syntax
ADDC ADDC.B
Operation
src + dst + C –> dst
Description
The source operand and the carry bit (C) are added to the destination operand. The source operand is not affected. The previous contents of the destination are lost.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The 32-bit counter pointed to by R13 is added to a 32-bit counter, eleven words (20/2 + 2/2) above the pointer in R13.
or
ADDC.W
src,dst
Set if result is negative, reset if positive Set if result is zero, reset otherwise Set if there is a carry from the MSB of the result, reset otherwise Set if an arithmetic overflow occurs, otherwise reset
ADD ADDC ... Example
src,dst src,dst
@R13+,20(R13) @R13+,20(R13)
; ADD LSDs with no carry in ; ADD MSDs with carry ; resulting from the LSDs
The 24-bit counter pointed to by R13 is added to a 24-bit counter, eleven words above the pointer in R13. ADD.B ADDC.B ADDC.B ...
@R13+,10(R13) @R13+,10(R13) @R13+,10(R13)
; ADD LSDs with no carry in ; ADD medium Bits with carry ; ADD MSDs with carry ; resulting from the LSDs
RISC 16–Bit CPU
TEAM LRN
207
3-23
AppendixA Instruction Set
AND[.W] AND.B
Source AND destination Source AND destination
Syntax
AND AND.B
Operation
src .AND. dst –> dst
Description
The source operand and the destination operand are logically ANDed. The result is placed into the destination.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The bits set in R5 are used as a mask (#0AA55h) for the word addressed by TOM. If the result is zero, a branch is taken to label TONI. #0AA55h,R5 R5,TOM TONI
; Load mask into register R5 ; mask word addressed by TOM with R5 ; ; Result is not zero
or
#0AA55h,TOM TONI
The bits of mask #0A5h are logically ANDed with the low byte TOM. If the result is zero, a branch is taken to label TONI. AND.B JZ ......
3-24
or AND.W src,dst
Set if result MSB is set, reset if not set Set if result is zero, reset otherwise Set if result is not zero, reset otherwise ( = .NOT. Zero) Reset
MOV AND JZ ...... ; ; ; ; ; AND JZ Example
src,dst src,dst
#0A5h,TOM TONI
RISC 16–Bit CPU
TEAM LRN
208
; mask Lowbyte TOM with 0A5h ; ; Result is not zero
TheMSP430InstructionSet Instruction Set
BIC[.W] BIC.B
Clear bits in destination Clear bits in destination
Syntax
BIC BIC.B
Operation
.NOT.src .AND. dst –> dst
Description
The inverted source operand and the destination operand are logically ANDed. The result is placed into the destination. The source operand is not affected.
Status Bits
Status bits are not affected.
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The six MSBs of the RAM word LEO are cleared. BIC
Example
src,dst src,dst
or BIC.W src,dst
#0FC00h,LEO
; Clear 6 MSBs in MEM(LEO)
The five MSBs of the RAM byte LEO are cleared. BIC.B
#0F8h,LEO
; Clear 5 MSBs in Ram location LEO
RISC 16–Bit CPU
TEAM LRN
209
3-25
AppendixA Instruction Set
BIS[.W] BIS.B
Set bits in destination Set bits in destination
Syntax
BIS BIS.B
Operation
src .OR. dst –> dst
Description
The source operand and the destination operand are logically ORed. The result is placed into the destination. The source operand is not affected.
Status Bits
Status bits are not affected.
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The six LSBs of the RAM word TOM are set. BIS
Example
or BIS.W
src,dst
#003Fh,TOM; set the six LSBs in RAM location TOM
The three MSBs of RAM byte TOM are set. BIS.B
3-26
src,dst src,dst
#0E0h,TOM
RISC 16–Bit CPU
TEAM LRN
210
; set the 3 MSBs in RAM location TOM
TheMSP430InstructionSet Instruction Set
BIT[.W] BIT.B
Test bits in destination Test bits in destination
Syntax
BIT
Operation
src .AND. dst
Description
The source and destination operands are logically ANDed. The result affects only the status bits. The source and destination operands are not affected.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
If bit 9 of R8 is set, a branch is taken to label TOM.
src,dst
Set if MSB of result is set, reset otherwise Set if result is zero, reset otherwise Set if result is not zero, reset otherwise (.NOT. Zero) Reset
BIT JNZ ... Example
#0200h,R8 TOM
; bit 9 of R8 set? ; Yes, branch to TOM ; No, proceed
If bit 3 of R8 is set, a branch is taken to label TOM. BIT.B JC
Example
or BIT.W src,dst
#8,R8 TOM
A serial communication receive bit (RCV) is tested. Because the carry bit is equal to the state of the tested bit while using the BIT instruction to test a single bit, the carry bit is used by the subsequent instruction; the read information is shifted into register RECBUF. ; ; Serial communication with LSB is shifted first: ; xxxx xxxx xxxx xxxx BIT.B #RCV,RCCTL ; Bit info into carry RRC RECBUF ; Carry –> MSB of RECBUF ; cxxx xxxx ...... ; repeat previous two instructions ...... ; 8 times ; cccc cccc ; ^ ^ ; MSB LSB ; Serial communication with MSB shifted first: BIT.B #RCV,RCCTL ; Bit info into carry RLC.B RECBUF ; Carry –> LSB of RECBUF ; xxxx xxxc ...... ; repeat previous two instructions ...... ; 8 times ; cccc cccc ;| LSB ; MSB
RISC 16–Bit CPU
TEAM LRN
211
3-27
AppendixA Instruction Set
* BR, BRANCH
Branch to .......... destination
Syntax
BR
Operation
dst –> PC
Emulation
MOV
Description
An unconditional branch is taken to an address anywhere in the 64K address space. All source addressing modes can be used. The branch instruction is a word instruction.
Status Bits
Status bits are not affected.
Example
Examples for all addressing modes are given.
3-28
dst
dst,PC
BR
#EXEC
;Branch to label EXEC or direct branch (e.g. #0A4h) ; Core instruction MOV @PC+,PC
BR
EXEC
; Branch to the address contained in EXEC ; Core instruction MOV X(PC),PC ; Indirect address
BR
&EXEC
; Branch to the address contained in absolute ; address EXEC ; Core instruction MOV X(0),PC ; Indirect address
BR
R5
; Branch to the address contained in R5 ; Core instruction MOV R5,PC ; Indirect R5
BR
@R5
; Branch to the address contained in the word ; pointed to by R5. ; Core instruction MOV @R5,PC ; Indirect, indirect R5
BR
@R5+
; Branch to the address contained in the word pointed ; to by R5 and increment pointer in R5 afterwards. ; The next time—S/W flow uses R5 pointer—it can ; alter program execution due to access to ; next address in a table pointed to by R5 ; Core instruction MOV @R5,PC ; Indirect, indirect R5 with autoincrement
BR
X(R5)
; Branch to the address contained in the address ; pointed to by R5 + X (e.g. table with address ; starting at X). X can be an address or a label ; Core instruction MOV X(R5),PC ; Indirect, indirect R5 + X
RISC 16–Bit CPU
TEAM LRN
212
TheMSP430InstructionSet Instruction Set
CALL
Subroutine
Syntax
CALL
dst
Operation
dst SP – 2 PC tmp
–> tmp –> SP –> @SP –> PC
dst is evaluated and stored PC updated to TOS dst saved to PC
Description
A subroutine call is made to an address anywhere in the 64K address space. All addressing modes can be used. The return address (the address of the following instruction) is stored on the stack. The call instruction is a word instruction.
Status Bits
Status bits are not affected.
Example
Examples for all addressing modes are given. CALL
#EXEC
; Call on label EXEC or immediate address (e.g. #0A4h) ; SP–2 → SP, PC+2 → @SP, @PC+ → PC
CALL
EXEC
; Call on the address contained in EXEC ; SP–2 → SP, PC+2 → @SP, X(PC) → PC ; Indirect address
CALL
&EXEC
; Call on the address contained in absolute address ; EXEC ; SP–2 → SP, PC+2 → @SP, X(0) → PC ; Indirect address
CALL
R5
; Call on the address contained in R5 ; SP–2 → SP, PC+2 → @SP, R5 → PC ; Indirect R5
CALL
@R5
; Call on the address contained in the word ; pointed to by R5 ; SP–2 → SP, PC+2 → @SP, @R5 → PC ; Indirect, indirect R5
CALL
@R5+
; Call on the address contained in the word ; pointed to by R5 and increment pointer in R5. ; The next time—S/W flow uses R5 pointer— ; it can alter the program execution due to ; access to next address in a table pointed to by R5 ; SP–2 → SP, PC+2 → @SP, @R5 → PC ; Indirect, indirect R5 with autoincrement
CALL
X(R5)
; Call on the address contained in the address pointed ; to by R5 + X (e.g. table with address starting at X) ; X can be an address or a label ; SP–2 → SP, PC+2 → @SP, X(R5) → PC ; Indirect, indirect R5 + X
RISC 16–Bit CPU
TEAM LRN
213
3-29
AppendixA Instruction Set
* CLR[.W] * CLR.B
Clear destination Clear destination
Syntax
CLR CLR.B
Operation
0 –> dst
Emulation
MOV MOV.B
Description
The destination operand is cleared.
Status Bits
Status bits are not affected.
Example
RAM word TONI is cleared. CLR
Example
#0,dst #0,dst
TONI
; 0 –> TONI
R5
RAM byte TONI is cleared. CLR.B
3-30
or CLR.W dst
Register R5 is cleared. CLR
Example
dst dst
TONI
; 0 –> TONI
RISC 16–Bit CPU
TEAM LRN
214
TheMSP430InstructionSet Instruction Set
* CLRC
Clear carry bit
Syntax
CLRC
Operation
0 –> C
Emulation
BIC
Description
The carry bit (C) is cleared. The clear carry instruction is a word instruction.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The 16-bit decimal counter pointed to by R13 is added to a 32-bit counter pointed to by R12.
#1,SR
Not affected Not affected Cleared Not affected
CLRC DADD DADC
; C=0: defines start @R13,0(R12) ; add 16-bit counter to low word of 32-bit counter 2(R12) ; add carry to high word of 32-bit counter
RISC 16–Bit CPU
TEAM LRN
215
3-31
AppendixA Instruction Set
* CLRN
Clear negative bit
Syntax
CLRN
Operation
0→N or (.NOT.src .AND. dst –> dst)
Emulation
BIC
Description
The constant 04h is inverted (0FFFBh) and is logically ANDed with the destination operand. The result is placed into the destination. The clear negative bit instruction is a word instruction.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The Negative bit in the status register is cleared. This avoids special treatment with negative numbers of the subroutine called.
SUBR
SUBRET
3-32
#4,SR
Reset to 0 Not affected Not affected Not affected
CLRN CALL ...... ...... JN ...... ...... ...... RET
SUBR
SUBRET
; If input is negative: do nothing and return
RISC 16–Bit CPU
TEAM LRN
216
TheMSP430InstructionSet Instruction Set
* CLRZ
Clear zero bit
Syntax
CLRZ
Operation
0→Z or (.NOT.src .AND. dst –> dst)
Emulation
BIC
Description
The constant 02h is inverted (0FFFDh) and logically ANDed with the destination operand. The result is placed into the destination. The clear zero bit instruction is a word instruction.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The zero bit in the status register is cleared.
#2,SR
Not affected Reset to 0 Not affected Not affected
CLRZ
RISC 16–Bit CPU
TEAM LRN
217
3-33
AppendixA Instruction Set
CMP[.W] CMP.B
Compare source and destination Compare source and destination
Syntax
CMP CMP.B
Operation
dst + .NOT.src + 1 or (dst – src)
Description
The source operand is subtracted from the destination operand. This is accomplished by adding the 1s complement of the source operand plus 1. The two operands are not affected and the result is not stored; only the status bits are affected.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
R5 and R6 are compared. If they are equal, the program continues at the label EQUAL.
CMP.W
R5,R6 EQUAL
; R5 = R6? ; YES, JUMP
MOV MOV MOV CMP JNZ INCD DEC JNZ
#NUM,R5 #BLOCK1,R6 #BLOCK2,R7 @R6+,0(R7) ERROR R7 R5 L$1
; number of words to be compared ; BLOCK1 start address in R6 ; BLOCK2 start address in R7 ; Are Words equal? R6 increments ; No, branch to ERROR ; Increment R7 pointer ; Are all words compared? ; No, another compare
The RAM bytes addressed by EDE and TONI are compared. If they are equal, the program continues at the label EQUAL. CMP.B EDE,TONI JEQ EQUAL
3-34
src,dst
Two RAM blocks are compared. If they are not equal, the program branches to the label ERROR.
L$1
Example
or
Set if result is negative, reset if positive (src >= dst) Set if result is zero, reset otherwise (src = dst) Set if there is a carry from the MSB of the result, reset otherwise Set if an arithmetic overflow occurs, otherwise reset
CMP JEQ Example
src,dst src,dst
RISC 16–Bit CPU
TEAM LRN
218
; MEM(EDE) = MEM(TONI)? ; YES, JUMP
TheMSP430InstructionSet Instruction Set
* DADC[.W] * DADC.B
Add carry decimally to destination Add carry decimally to destination
Syntax
DADC DADC.B
Operation
dst + C –> dst (decimally)
Emulation
DADD DADD.B
Description
The carry bit (C) is added decimally to the destination.
Status Bits
N: Set if MSB is 1 Z: Set if dst is 0, reset otherwise C: Set if destination increments from 9999 to 0000, reset otherwise Set if destination increments from 99 to 00, reset otherwise V: Undefined
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The four-digit decimal number contained in R5 is added to an eight-digit decimal number pointed to by R8.
dst dst
or
Example
src,dst
#0,dst #0,dst
CLRC DADD DADC
DADC.W
R5,0(R8) 2(R8)
; Reset carry ; next instruction’s start condition is defined ; Add LSDs + C ; Add carry to MSD
The two-digit decimal number contained in R5 is added to a four-digit decimal number pointed to by R8. CLRC DADD.B DADC
R5,0(R8) 1(R8)
; Reset carry ; next instruction’s start condition is defined ; Add LSDs + C ; Add carry to MSDs
RISC 16–Bit CPU
TEAM LRN
219
3-35
AppendixA Instruction Set
DADD[.W] DADD.B
Source and carry added decimally to destination Source and carry added decimally to destination
Syntax
DADD DADD.B
Operation
src + dst + C –> dst (decimally)
Description
The source operand and the destination operand are treated as four binary coded decimals (BCD) with positive signs. The source operand and the carry bit (C) are added decimally to the destination operand. The source operand is not affected. The previous contents of the destination are lost. The result is not defined for non-BCD numbers.
Status Bits
N: Set if the MSB is 1, reset otherwise Z: Set if result is zero, reset otherwise C: Set if the result is greater than 9999 Set if the result is greater than 99 V: Undefined
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The eight-digit BCD number contained in R5 and R6 is added decimally to an eight-digit BCD number contained in R3 and R4 (R6 and R4 contain the MSDs). CLRC DADD DADD JC
Example
src,dst src,dst
or DADD.W
src,dst
; clear carry R5,R3 ; add LSDs R6,R4 ; add MSDs with carry OVERFLOW ; If carry occurs go to error handling routine
The two-digit decimal counter in the RAM byte CNT is incremented by one. CLRC DADD.B
#1,CNT
; clear carry ; increment decimal counter
#0,CNT
; ≡ DADC.B
or SETC DADD.B
3-36
RISC 16–Bit CPU
TEAM LRN
220
CNT
TheMSP430InstructionSet Instruction Set
* DEC[.W] * DEC.B
Decrement destination Decrement destination
Syntax
DEC DEC.B
Operation
dst – 1 –> dst
Emulation Emulation
SUB SUB.B
Description
The destination operand is decremented by one. The original contents are lost.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
R10 is decremented by 1
dst dst
or
DEC.W
dst
#1,dst #1,dst
Set if result is negative, reset if positive Set if dst contained 1, reset otherwise Reset if dst contained 0, set otherwise Set if an arithmetic overflow occurs, otherwise reset. Set if initial value of destination was 08000h, otherwise reset. Set if initial value of destination was 080h, otherwise reset.
DEC
R10
; Decrement R10
; Move a block of 255 bytes from memory location starting with EDE to memory location starting with ;TONI. Tables should not overlap: start of destination address TONI must not be within the range EDE ; to EDE+0FEh ; MOV #EDE,R6 MOV #255,R10 L$1 MOV.B @R6+,TONI–EDE–1(R6) DEC R10 JNZ L$1 ; Do not transfer tables using the routine above with the overlap shown in Figure 3–12.
Figure 3–12. Decrement Overlap EDE
TONI EDE+254
TONI+254
RISC 16–Bit CPU
TEAM LRN
221
3-37
AppendixA Instruction Set
* DECD[.W] * DECD.B
Double-decrement destination Double-decrement destination
Syntax
DECD DECD.B
Operation
dst – 2 –> dst
Emulation Emulation
SUB SUB.B
Description
The destination operand is decremented by two. The original contents are lost.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
R10 is decremented by 2.
dst dst
or
DECD.W
dst
#2,dst #2,dst
Set if result is negative, reset if positive Set if dst contained 2, reset otherwise Reset if dst contained 0 or 1, set otherwise Set if an arithmetic overflow occurs, otherwise reset. Set if initial value of destination was 08001 or 08000h, otherwise reset. Set if initial value of destination was 081 or 080h, otherwise reset.
DECD
R10
; Decrement R10 by two
; Move a block of 255 words from memory location starting with EDE to memory location ; starting with TONI ; Tables should not overlap: start of destination address TONI must not be within the ; range EDE to EDE+0FEh ; MOV #EDE,R6 MOV #510,R10 L$1 MOV @R6+,TONI–EDE–2(R6) DECD R10 JNZ L$1 Example
Memory at location LEO is decremented by two. DECD.B
LEO
Decrement status byte STATUS by two. DECD.B
3-38
STATUS
RISC 16–Bit CPU
TEAM LRN
222
; Decrement MEM(LEO)
TheMSP430InstructionSet Instruction Set
* DINT
Disable (general) interrupts
Syntax
DINT
Operation
0 → GIE or (0FFF7h .AND. SR → SR
/
.NOT.src .AND. dst –> dst)
Emulation
BIC
Description
All interrupts are disabled. The constant 08h is inverted and logically ANDed with the status register (SR). The result is placed into the SR.
Status Bits
Status bits are not affected.
Mode Bits
GIE is reset. OSCOFF and CPUOFF are not affected.
Example
The general interrupt enable (GIE) bit in the status register is cleared to allow a nondisrupted move of a 32-bit counter. This ensures that the counter is not modified during the move by any interrupt. DINT NOP MOV MOV EINT
#8,SR
; All interrupt events using the GIE bit are disabled COUNTHI,R5 ; Copy counter COUNTLO,R6 ; All interrupt events using the GIE bit are enabled
Note: Disable Interrupt If any code sequence needs to be protected from interruption, the DINT should be executed at least one instruction before the beginning of the uninterruptible sequence, or should be followed by a NOP instruction.
RISC 16–Bit CPU
TEAM LRN
223
3-39
AppendixA Instruction Set
* EINT
Enable (general) interrupts
Syntax
EINT
Operation
1 → GIE or (0008h .OR. SR –> SR / .src .OR. dst –> dst)
Emulation
BIS
Description
All interrupts are enabled. The constant #08h and the status register SR are logically ORed. The result is placed into the SR.
Status Bits
Status bits are not affected.
Mode Bits
GIE is set. OSCOFF and CPUOFF are not affected.
Example
The general interrupt enable (GIE) bit in the status register is set.
#8,SR
; Interrupt routine of ports P1.2 to P1.7 ; P1IN is the address of the register where all port bits are read. P1IFG is the address of ; the register where all interrupt events are latched. ; PUSH.B &P1IN BIC.B @SP,&P1IFG ; Reset only accepted flags EINT ; Preset port 0 interrupt flags stored on stack ; other interrupts are allowed BIT #Mask,@SP JEQ MaskOK ; Flags are present identically to mask: jump ...... MaskOK BIC #Mask,@SP ...... INCD SP ; Housekeeping: inverse to PUSH instruction ; at the start of interrupt subroutine. Corrects ; the stack pointer. RETI Note:
Enable Interrupt
The instruction following the enable interrupt instruction (EINT) is always executed, even if an interrupt service request is pending when the interrupts are enable.
3-40
RISC 16–Bit CPU
TEAM LRN
224
TheMSP430InstructionSet Instruction Set
* INC[.W] * INC.B
Increment destination Increment destination
Syntax
INC INC.B
Operation
dst + 1 –> dst
Emulation
ADD
Description
The destination operand is incremented by one. The original contents are lost.
Status Bits
N: Set if result is negative, reset if positive Z: Set if dst contained 0FFFFh, reset otherwise Set if dst contained 0FFh, reset otherwise C: Set if dst contained 0FFFFh, reset otherwise Set if dst contained 0FFh, reset otherwise V: Set if dst contained 07FFFh, reset otherwise Set if dst contained 07Fh, reset otherwise
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The status byte, STATUS, of a process is incremented. When it is equal to 11, a branch to OVFL is taken.
dst dst
or INC.W dst
#1,dst
INC.B CMP.B JEQ
STATUS #11,STATUS OVFL
RISC 16–Bit CPU
TEAM LRN
225
3-41
AppendixA Instruction Set
* INCD[.W] * INCD.B
Double-increment destination Double-increment destination
Syntax
INCD INCD.B
Operation
dst + 2 –> dst
Emulation Emulation
ADD ADD.B
Example
The destination operand is incremented by two. The original contents are lost.
Status Bits
N: Set if result is negative, reset if positive Z: Set if dst contained 0FFFEh, reset otherwise Set if dst contained 0FEh, reset otherwise C: Set if dst contained 0FFFEh or 0FFFFh, reset otherwise Set if dst contained 0FEh or 0FFh, reset otherwise V: Set if dst contained 07FFEh or 07FFFh, reset otherwise Set if dst contained 07Eh or 07Fh, reset otherwise
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The item on the top of the stack (TOS) is removed without using a register.
dst dst
....... PUSH
R5
INCD
SP
; R5 is the result of a calculation, which is stored ; in the system stack ; Remove TOS by double-increment from stack ; Do not use INCD.B, SP is a word-aligned ; register
The byte on the top of the stack is incremented by two. INCD.B
3-42
dst
#2,dst #2,dst
RET Example
or INCD.W
0(SP)
; Byte on TOS is increment by two
RISC 16–Bit CPU
TEAM LRN
226
TheMSP430InstructionSet Instruction Set
* INV[.W] * INV.B
Invert destination Invert destination
Syntax
INV INV.B
Operation
.NOT.dst –> dst
Emulation Emulation
XOR XOR.B
Description
The destination operand is inverted. The original contents are lost.
Status Bits
N: Set if result is negative, reset if positive Z: Set if dst contained 0FFFFh, reset otherwise Set if dst contained 0FFh, reset otherwise C: Set if result is not zero, reset otherwise ( = .NOT. Zero) Set if result is not zero, reset otherwise ( = .NOT. Zero) V: Set if initial destination operand was negative, otherwise reset
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
Content of R5 is negated (twos complement). MOV #00AEh,R5 ; INV R5 ; Invert R5, INC R5 ; R5 is now negated,
Example
Content of memory byte LEO is negated. MOV.B INV.B INC.B
dst dst
#0FFFFh,dst #0FFh,dst
R5 = 000AEh R5 = 0FF51h R5 = 0FF52h
#0AEh,LEO ; MEM(LEO) = 0AEh LEO ; Invert LEO, MEM(LEO) = 051h LEO ; MEM(LEO) is negated,MEM(LEO) = 052h
RISC 16–Bit CPU
TEAM LRN
227
3-43
AppendixA Instruction Set
JC JHS
Jump if carry set Jump if higher or same
Syntax
JC JHS
Operation
If C = 1: PC + 2 × offset –> PC If C = 0: execute following instruction
Description
The status register carry bit (C) is tested. If it is set, the 10-bit signed offset contained in the instruction LSBs is added to the program counter. If C is reset, the next instruction following the jump is executed. JC (jump if carry/higher or same) is used for the comparison of unsigned numbers (0 to 65536).
Status Bits
Status bits are not affected.
Example
The P1IN.1 signal is used to define or control the program flow. BIT JC ......
Example
#01h,&P1IN PROGA
; State of signal –> Carry ; If carry=1 then execute program routine A ; Carry=0, execute program here
R5 is compared to 15. If the content is higher or the same, branch to LABEL. CMP JHS ......
3-44
label label
#15,R5 LABEL
; Jump is taken if R5 ≥ 15 ; Continue here if R5 < 15
RISC 16–Bit CPU
TEAM LRN
228
TheMSP430InstructionSet Instruction Set
JEQ, JZ
Jump if equal, jump if zero
Syntax
JEQ
Operation
If Z = 1: PC + 2 × offset –> PC If Z = 0: execute following instruction
Description
The status register zero bit (Z) is tested. If it is set, the 10-bit signed offset contained in the instruction LSBs is added to the program counter. If Z is not set, the instruction following the jump is executed.
Status Bits
Status bits are not affected.
Example
Jump to address TONI if R7 contains zero. TST JZ
Example
Example
label,
JZ
label
R7 TONI
; Test R7 ; if zero: JUMP
Jump to address LEO if R6 is equal to the table contents. CMP
R6,Table(R5)
JEQ ......
LEO
; Compare content of R6 with content of ; MEM (table address + content of R5) ; Jump if both data are equal ; No, data are not equal, continue here
Branch to LABEL if R5 is 0. TST JZ ......
R5 LABEL
RISC 16–Bit CPU
TEAM LRN
229
3-45
AppendixA Instruction Set
JGE
Jump if greater or equal
Syntax
JGE
Operation
If (N .XOR. V) = 0 then jump to label: PC + 2 × offset –> PC If (N .XOR. V) = 1 then execute the following instruction
Description
The status register negative bit (N) and overflow bit (V) are tested. If both N and V are set or reset, the 10-bit signed offset contained in the instruction LSBs is added to the program counter. If only one is set, the instruction following the jump is executed.
label
This allows comparison of signed integers. Status Bits
Status bits are not affected.
Example
When the content of R6 is greater or equal to the memory pointed to by R7, the program continues at label EDE. CMP JGE ...... ...... ......
3-46
@R7,R6 EDE
; R6 ≥ (R7)?, compare on signed numbers ; Yes, R6 ≥ (R7) ; No, proceed
RISC 16–Bit CPU
TEAM LRN
230
TheMSP430InstructionSet Instruction Set
JL
Jump if less
Syntax
JL
Operation
If (N .XOR. V) = 1 then jump to label: PC + 2 × offset –> PC If (N .XOR. V) = 0 then execute following instruction
Description
The status register negative bit (N) and overflow bit (V) are tested. If only one is set, the 10-bit signed offset contained in the instruction LSBs is added to the program counter. If both N and V are set or reset, the instruction following the jump is executed.
label
This allows comparison of signed integers. Status Bits
Status bits are not affected.
Example
When the content of R6 is less than the memory pointed to by R7, the program continues at label EDE. CMP JL ...... ...... ......
@R7,R6 EDE
; R6 < (R7)?, compare on signed numbers ; Yes, R6 < (R7) ; No, proceed
RISC 16–Bit CPU
TEAM LRN
231
3-47
AppendixA Instruction Set
JMP
Jump unconditionally
Syntax
JMP
Operation
PC + 2 × offset –> PC
Description
The 10-bit signed offset contained in the instruction LSBs is added to the program counter.
Status Bits
Status bits are not affected.
Hint:
This one-word instruction replaces the BRANCH instruction in the range of – 511 to +512 words relative to the current program counter.
3-48
label
RISC 16–Bit CPU
TEAM LRN
232
TheMSP430InstructionSet Instruction Set
JN
Jump if negative
Syntax
JN
Operation
if N = 1: PC + 2 × offset –> PC if N = 0: execute following instruction
Description
The negative bit (N) of the status register is tested. If it is set, the 10-bit signed offset contained in the instruction LSBs is added to the program counter. If N is reset, the next instruction following the jump is executed.
Status Bits
Status bits are not affected.
Example
The result of a computation in R5 is to be subtracted from COUNT. If the result is negative, COUNT is to be cleared and the program continues execution in another path.
L$1
SUB JN ...... ...... ...... ...... CLR ...... ...... ......
label
R5,COUNT L$1
; COUNT – R5 –> COUNT ; If negative continue with COUNT=0 at PC=L$1 ; Continue with COUNT≥0
COUNT
RISC 16–Bit CPU
TEAM LRN
233
3-49
AppendixA Instruction Set
JNC JLO
Jump if carry not set Jump if lower
Syntax
JNC JLO
Operation
if C = 0: PC + 2 × offset –> PC if C = 1: execute following instruction
Description
The status register carry bit (C) is tested. If it is reset, the 10-bit signed offset contained in the instruction LSBs is added to the program counter. If C is set, the next instruction following the jump is executed. JNC (jump if no carry/lower) is used for the comparison of unsigned numbers (0 to 65536).
Status Bits
Status bits are not affected.
Example
The result in R6 is added in BUFFER. If an overflow occurs, an error handling routine at address ERROR is used.
ERROR
CONT
Example
ADD JNC ...... ...... ...... ...... ...... ...... ......
R6,BUFFER CONT
; BUFFER + R6 –> BUFFER ; No carry, jump to CONT ; Error handler start
; Continue with normal program flow
Branch to STL 2 if byte STATUS contains 1 or 0. CMP.B JLO ......
3-50
label label
#2,STATUS STL2
; STATUS < 2 ; STATUS ≥ 2, continue here
RISC 16–Bit CPU
TEAM LRN
234
TheMSP430InstructionSet Instruction Set
JNE JNZ
Jump if not equal Jump if not zero
Syntax
JNE JNZ
Operation
If Z = 0: PC + 2 × offset –> PC If Z = 1: execute following instruction
Description
The status register zero bit (Z) is tested. If it is reset, the 10-bit signed offset contained in the instruction LSBs is added to the program counter. If Z is set, the next instruction following the jump is executed.
Status Bits
Status bits are not affected.
Example
Jump to address TONI if R7 and R8 have different contents. CMP JNE ......
label label
R7,R8 TONI
; COMPARE R7 WITH R8 ; if different: jump ; if equal, continue
RISC 16–Bit CPU
TEAM LRN
235
3-51
AppendixA Instruction Set
MOV[.W] MOV.B
Move source to destination Move source to destination
Syntax
MOV MOV.B
Operation
src –> dst
Description
The source operand is moved to the destination. The source operand is not affected. The previous contents of the destination are lost.
Status Bits
Status bits are not affected.
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The contents of table EDE (word data) are copied to table TOM. The length of the tables must be 020h locations.
Loop
Example
Loop
MOV MOV MOV DEC JNZ ...... ...... ......
src,dst src,dst
or
MOV.W
#EDE,R10 #020h,R9 @R10+,TOM–EDE–2(R10) R9 Loop
; Prepare pointer ; Prepare counter ; Use pointer in R10 for both tables ; Decrement counter ; Counter ≠ 0, continue copying ; Copying completed
The contents of table EDE (byte data) are copied to table TOM. The length of the tables should be 020h locations MOV #EDE,R10 MOV #020h,R9 MOV.B @R10+,TOM–EDE–1(R10) DEC JNZ
R9 Loop
...... ...... ......
3-52
src,dst
RISC 16–Bit CPU
TEAM LRN
236
; Prepare pointer ; Prepare counter ; Use pointer in R10 for ; both tables ; Decrement counter ; Counter ≠ 0, continue ; copying ; Copying completed
TheMSP430InstructionSet Instruction Set
* NOP
No operation
Syntax
NOP
Operation
None
Emulation
MOV
Description
No operation is performed. The instruction may be used for the elimination of instructions during the software check or for defined waiting times.
Status Bits
Status bits are not affected.
#0, R3
The NOP instruction is mainly used for two purposes: � To fill one, two, or three memory words � To adjust software timing
Note: Emulating No-Operation Instruction Other instructions can emulate the NOP function while providing different numbers of instruction cycles and code words. Some examples are: Examples: MOV MOV MOV BIC JMP BIC
#0,R3 0(R4),0(R4) @R4,0(R4) #0,EDE(R4) $+2 #0,R5
; 1 cycle, 1 word ; 6 cycles, 3 words ; 5 cycles, 2 words ; 4 cycles, 2 words ; 2 cycles, 1 word ; 1 cycle, 1 word
However, care should be taken when using these examples to prevent unintended results. For example, if MOV 0(R4), 0(R4) is used and the value in R4 is 120h, then a security violation will occur with the watchdog timer (address 120h) because the security key was not used.
RISC 16–Bit CPU
TEAM LRN
237
3-53
AppendixA Instruction Set
* POP[.W] * POP.B
Pop word from stack to destination Pop byte from stack to destination
Syntax
POP POP.B
Operation
@SP –> temp SP + 2 –> SP temp –> dst
Emulation Emulation
MOV MOV.B
Description
The stack location pointed to by the stack pointer (TOS) is moved to the destination. The stack pointer is incremented by two afterwards.
Status Bits
Status bits are not affected.
Example
The contents of R7 and the status register are restored from the stack. POP POP
Example
R7 SR
or
MOV.W
@SP+,dst
; Restore R7 ; Restore status register
LEO
; The low byte of the stack is moved to LEO.
The contents of R7 is restored from the stack. POP.B
Example
@SP+,dst @SP+,dst
The contents of RAM byte LEO is restored from the stack. POP.B
Example
dst dst
R7
; The low byte of the stack is moved to R7, ; the high byte of R7 is 00h
The contents of the memory pointed to by R7 and the status register are restored from the stack. POP.B
0(R7)
POP
SR
Note:
; The low byte of the stack is moved to the ; the byte which is pointed to by R7 : Example: R7 = 203h ; Mem(R7) = low byte of system stack : Example: R7 = 20Ah ; Mem(R7) = low byte of system stack ; Last word on stack moved to the SR
The System Stack Pointer
The system stack pointer (SP) is always incremented by two, independent of the byte suffix.
3-54
RISC 16–Bit CPU
TEAM LRN
238
TheMSP430InstructionSet Instruction Set
PUSH[.W] PUSH.B
Push word onto stack Push byte onto stack
Syntax
PUSH PUSH.B
Operation
SP – 2 → SP src → @SP
Description
The stack pointer is decremented by two, then the source operand is moved to the RAM word addressed by the stack pointer (TOS).
Status Bits
Status bits are not affected.
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The contents of the status register and R8 are saved on the stack. PUSH PUSH
Example
src src
or
SR R8
PUSH.W
src
; save status register ; save R8
The contents of the peripheral TCDAT is saved on the stack. PUSH.B
&TCDAT
; save data from 8-bit peripheral module, ; address TCDAT, onto stack
Note: The System Stack Pointer The system stack pointer (SP) is always decremented by two, independent of the byte suffix.
RISC 16–Bit CPU
TEAM LRN
239
3-55
AppendixA Instruction Set
* RET
Return from subroutine
Syntax
RET
Operation
@SP→ PC SP + 2 → SP
Emulation
MOV
Description
The return address pushed onto the stack by a CALL instruction is moved to the program counter. The program continues at the code address following the subroutine call.
Status Bits
Status bits are not affected.
3-56
@SP+,PC
RISC 16–Bit CPU
TEAM LRN
240
TheMSP430InstructionSet Instruction Set
RETI
Return from interrupt
Syntax
RETI
Operation
TOS SP + 2 TOS SP + 2
Description
The status register is restored to the value at the beginning of the interrupt service routine by replacing the present SR contents with the TOS contents. The stack pointer (SP) is incremented by two.
→ SR → SP → PC → SP
The program counter is restored to the value at the beginning of interrupt service. This is the consecutive step after the interrupted program flow. Restoration is performed by replacing the present PC contents with the TOS memory contents. The stack pointer (SP) is incremented. Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are restored from system stack.
Example
Figure 3–13 illustrates the main program interrupt.
restored from system stack restored from system stack restored from system stack restored from system stack
Figure 3–13. Main Program Interrupt
PC –6 PC –4 PC –2 PC PC +2 PC +4
Interrupt Request Interrupt Accepted PC+2 is Stored Onto Stack
PC = PCi PCi +2 PCi +4
PC +6 PC +8
PCi +n–4 PCi +n–2 PCi +n
RETI
RISC 16–Bit CPU
TEAM LRN
241
3-57
AppendixA Instruction Set
* RLA[.W] * RLA.B
Rotate left arithmetically Rotate left arithmetically
Syntax
RLA RLA.B
Operation
C C
Figure 3–16. Destination Operand—Arithmetic Right Shift Word
15
0
15
0
C Byte
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
R5 is shifted right one position. The MSB retains the old value. It operates equal to an arithmetic division by 2.
Set if result is negative, reset if positive Set if result is zero, reset otherwise Loaded from the LSB Reset
RRA ; ;
Example
3-60
R5
; R5/2 –> R5
The value in R5 is multiplied by 0.75 (0.5 + 0.25). PUSH RRA ADD RRA ......
R5 R5 @SP+,R5 R5
; Hold R5 temporarily using stack ; R5 × 0.5 –> R5 ; R5 × 0.5 + R5 = 1.5 × R5 –> R5 ; (1.5 × R5) × 0.5 = 0.75 × R5 –> R5
The low byte of R5 is shifted right one position. The MSB retains the old value. It operates equal to an arithmetic division by 2. RRA.B
R5
PUSH.B RRA.B ADD.B ......
R5 @SP @SP+,R5
; R5/2 –> R5: operation is on low byte only ; High byte of R5 is reset ; R5 × 0.5 –> TOS ; TOS × 0.5 = 0.5 × R5 × 0.5 = 0.25 × R5 –> TOS ; R5 × 0.5 + R5 × 0.25 = 0.75 × R5 –> R5
RISC 16–Bit CPU
TEAM LRN
244
TheMSP430InstructionSet Instruction Set
RRC[.W] RRC.B
Rotate right through carry Rotate right through carry
Syntax
RRC RRC
Operation
C –> MSB –> MSB–1 .... LSB+1 –> LSB –> C
Description
The destination operand is shifted right one position as shown in Figure 3–17. The carry bit (C) is shifted into the MSB, the LSB is shifted into the carry bit (C).
dst dst
or
RRC.W
dst
Figure 3–17. Destination Operand—Carry Right Shift Word
15
0
7
0
C Byte
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
R5 is shifted right one position. The MSB is loaded with 1.
Set if result is negative, reset if positive Set if result is zero, reset otherwise Loaded from the LSB Set if initial destination is positive and initial carry is set, otherwise reset
SETC RRC Example
R5
; Prepare carry for MSB ; R5/2 + 8000h –> R5
R5 is shifted right one position. The MSB is loaded with 1. SETC RRC.B
R5
; Prepare carry for MSB ; R5/2 + 80h –> R5; low byte of R5 is used
RISC 16–Bit CPU
TEAM LRN
245
3-61
AppendixA Instruction Set
* SBC[.W] * SBC.B
Subtract source and borrow/.NOT. carry from destination Subtract source and borrow/.NOT. carry from destination
Syntax
SBC SBC.B
Operation
dst + 0FFFFh + C –> dst dst + 0FFh + C –> dst
Emulation
SUBC SUBC.B
Description
The carry bit (C) is added to the destination operand minus one. The previous contents of the destination are lost.
Status Bits
N: Set if result is negative, reset if positive Z: Set if result is zero, reset otherwise C: Set if there is a carry from the MSB of the result, reset otherwise. Set to 1 if no borrow, reset if borrow. V: Set if an arithmetic overflow occurs, reset otherwise.
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The 16-bit counter pointed to by R13 is subtracted from a 32-bit counter pointed to by R12. SUB SBC
Example
dst dst
or
SBC.W
#0,dst #0,dst
@R13,0(R12) 2(R12)
; Subtract LSDs ; Subtract carry from MSD
The 8-bit counter pointed to by R13 is subtracted from a 16-bit counter pointed to by R12. SUB.B SBC.B Note:
@R13,0(R12) 1(R12)
; Subtract LSDs ; Subtract carry from MSD
Borrow Implementation.
The borrow is treated as a .NOT. carry :
3-62
dst
RISC 16–Bit CPU
TEAM LRN
246
Borrow Yes No
Carry bit 0 1
TheMSP430InstructionSet Instruction Set
* SETC
Set carry bit
Syntax
SETC
Operation
1 –> C
Emulation
BIS
Description
The carry bit (C) is set.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
Emulation of the decimal subtraction: Subtract R5 from R6 decimally Assume that R5 = 03987h and R6 = 04137h
DSUB
ADD
#06666h,R5
INV
R5
SETC DADD
R5,R6
#1,SR
Not affected Not affected Set Not affected
; Move content R5 from 0–9 to 6–0Fh ; R5 = 03987h + 06666h = 09FEDh ; Invert this (result back to 0–9) ; R5 = .NOT. R5 = 06012h ; Prepare carry = 1 ; Emulate subtraction by addition of: ; (010000h – R5 – 1) ; R6 = R6 + R5 + 1 ; R6 = 0150h
RISC 16–Bit CPU
TEAM LRN
247
3-63
AppendixA Instruction Set
* SETN
Set negative bit
Syntax
SETN
Operation
1 –> N
Emulation
BIS
Description
The negative bit (N) is set.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
3-64
#4,SR
Set Not affected Not affected Not affected
RISC 16–Bit CPU
TEAM LRN
248
TheMSP430InstructionSet Instruction Set
* SETZ
Set zero bit
Syntax
SETZ
Operation
1 –> Z
Emulation
BIS
Description
The zero bit (Z) is set.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
#2,SR
Not affected Set Not affected Not affected
RISC 16–Bit CPU
TEAM LRN
249
3-65
AppendixA Instruction Set
SUB[.W] SUB.B
Subtract source from destination Subtract source from destination
Syntax
SUB SUB.B
Operation
dst + .NOT.src + 1 –> dst or [(dst – src –> dst)]
Description
The source operand is subtracted from the destination operand by adding the source operand’s 1s complement and the constant 1. The source operand is not affected. The previous contents of the destination are lost.
Status Bits
N: Set if result is negative, reset if positive Z: Set if result is zero, reset otherwise C: Set if there is a carry from the MSB of the result, reset otherwise. Set to 1 if no borrow, reset if borrow. V: Set if an arithmetic overflow occurs, otherwise reset
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
See example at the SBC instruction.
Example
See example at the SBC.B instruction. Note:
src,dst src,dst
or
SUB.W
Borrow Is Treated as a .NOT.
The borrow is treated as a .NOT. carry :
3-66
src,dst
RISC 16–Bit CPU
TEAM LRN
250
Borrow Yes No
Carry bit 0 1
TheMSP430InstructionSet Instruction Set
SUBC[.W]SBB[.W] SUBC.B,SBB.B
Subtract source and borrow/.NOT. carry from destination Subtract source and borrow/.NOT. carry from destination
Syntax
SUBC SBB SUBC.B
Operation
dst + .NOT.src + C –> dst or (dst – src – 1 + C –> dst)
Description
The source operand is subtracted from the destination operand by adding the source operand’s 1s complement and the carry bit (C). The source operand is not affected. The previous contents of the destination are lost.
Status Bits
N: Set if result is negative, reset if positive. Z: Set if result is zero, reset otherwise. C: Set if there is a carry from the MSB of the result, reset otherwise. Set to 1 if no borrow, reset if borrow. V: Set if an arithmetic overflow occurs, reset otherwise.
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
Two floating point mantissas (24 bits) are subtracted. LSBs are in R13 and R10, MSBs are in R12 and R9. SUB.W SUBC.B
Example
src,dst src,dst src,dst
or or or
SUBC.W SBB.W SBB.B
src,dst src,dst src,dst
or
R13,R10 ; 16-bit part, LSBs R12,R9 ; 8-bit part, MSBs
The 16-bit counter pointed to by R13 is subtracted from a 16-bit counter in R10 and R11(MSD). SUB.B SUBC.B ...
@R13+,R10 @R13,R11
; Subtract LSDs without carry ; Subtract MSDs with carry ; resulting from the LSDs
Note: Borrow Implementation The borrow is treated as a .NOT. carry :
Borrow Yes No
Carry bit 0 1
RISC 16–Bit CPU
TEAM LRN
251
3-67
AppendixA Instruction Set
SWPB
Swap bytes
Syntax
SWPB
Operation
Bits 15 to 8 bits 7 to 0
Description
The destination operand high and low bytes are exchanged as shown in Figure 3–18.
Status Bits
Status bits are not affected.
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
dst
Figure 3–18. Destination Operand Byte Swap 15
8
7
Example MOV SWPB Example
; 0100000010111111 –> R7 ; 1011111101000000 in R7
The value in R5 is multiplied by 256. The result is stored in R5,R4. SWPB MOV BIC BIC
3-68
#040BFh,R7 R7
R5 R5,R4 #0FF00h,R5 #00FFh,R4
; ;Copy the swapped value to R4 ;Correct the result ;Correct the result
RISC 16–Bit CPU
TEAM LRN
252
0
TheMSP430InstructionSet Instruction Set
SXT
Extend Sign
Syntax
SXT
Operation
Bit 7 –> Bit 8 ......... Bit 15
Description
The sign of the low byte is extended into the high byte as shown in Figure 3–19.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
dst
Set if result is negative, reset if positive Set if result is zero, reset otherwise Set if result is not zero, reset otherwise (.NOT. Zero) Reset
Figure 3–19. Destination Operand Sign Extension 15
Example
8
7
0
R7 is loaded with the P1IN value. The operation of the sign-extend instruction expands bit 8 to bit 15 with the value of bit 7. R7 is then added to R6. MOV.B SXT
&P1IN,R7 R7
; P1IN = 080h: ; R7 = 0FF80h:
. . . . . . . . 1000 0000 1111 1111 1000 0000
RISC 16–Bit CPU
TEAM LRN
253
3-69
AppendixA Instruction Set
* TST[.W] * TST.B
Test destination Test destination
Syntax
TST TST.B
Operation
dst + 0FFFFh + 1 dst + 0FFh + 1
Emulation
CMP CMP.B
Description
The destination operand is compared with zero. The status bits are set according to the result. The destination is not affected.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
R7 is tested. If it is negative, continue at R7NEG; if it is positive but not zero, continue at R7POS.
#0,dst #0,dst
TST JN JZ ...... ...... ......
R7 R7NEG R7ZERO
; Test R7 ; R7 is negative ; R7 is zero ; R7 is positive but not zero ; R7 is negative ; R7 is zero
The low byte of R7 is tested. If it is negative, continue at R7NEG; if it is positive but not zero, continue at R7POS.
R7POS R7NEG R7ZERO
3-70
or TST.W dst
Set if destination is negative, reset if positive Set if destination contains zero, reset otherwise Set Reset
R7POS R7NEG R7ZERO Example
dst dst
TST.B JN JZ ...... ..... ......
R7 R7NEG R7ZERO
RISC 16–Bit CPU
TEAM LRN
254
; Test low byte of R7 ; Low byte of R7 is negative ; Low byte of R7 is zero ; Low byte of R7 is positive but not zero ; Low byte of R7 is negative ; Low byte of R7 is zero
TheMSP430InstructionSet Instruction Set
XOR[.W] XOR.B
Exclusive OR of source with destination Exclusive OR of source with destination
Syntax
XOR XOR.B
Operation
src .XOR. dst –> dst
Description
The source and destination operands are exclusive ORed. The result is placed into the destination. The source operand is not affected.
Status Bits
N: Z: C: V:
Mode Bits
OSCOFF, CPUOFF, and GIE are not affected.
Example
The bits set in R6 toggle the bits in the RAM word TONI.
XOR.W
src,dst
R6,TONI
; Toggle bits of word TONI on the bits set in R6
The bits set in R6 toggle the bits in the RAM byte TONI. XOR.B
Example
or
Set if result MSB is set, reset if not set Set if result is zero, reset otherwise Set if result is not zero, reset otherwise ( = .NOT. Zero) Set if both operands are negative
XOR Example
src,dst src,dst
R6,TONI
; Toggle bits of byte TONI on the bits set in ; low byte of R6
Reset to 0 those bits in low byte of R7 that are different from bits in RAM byte EDE. XOR.B INV.B
EDE,R7 R7
; Set different bit to “1s” ; Invert Lowbyte, Highbyte is 0h
RISC 16–Bit CPU
TEAM LRN
255
3-71
AppendixA Instruction Set
3.4.4
Instruction Cycles and Lengths The number of CPU clock cycles required for an instruction depends on the instruction format and the addressing modes used - not the instruction itself. The number of clock cycles refers to the MCLK.
Interrupt and Reset Cycles Table 3–14 lists the CPU cycles for interrupt overhead and reset.
Table 3–14.Interrupt and Reset Cycles No. of Cycles
5
Length of Instruction 1
Interrupt accepted
6
–
WDT reset
4
–
Reset (RST/NMI)
4
–
Action Return from interrupt (RETI)
Format-II (Single Operand) Instruction Cycles and Lengths Table 3–15 lists the length and CPU cycles for all addressing modes of format-II instructions.
Table 3–15.Format-II Instruction Cycles and Lengths No. of Cycles
RRA, RRC SWPB, SXT
PUSH
CALL
1
3
4
Length of Instruction 1
@Rn
3
4
4
1
@Rn+
3
4
5
1
SWPB @R10+
(See note)
4
5
2
CALL #81H
X(Rn)
4
5
5
2
CALL 2(R7)
EDE
4
5
5
2
PUSH EDE
&EDE
4
5
5
2
SXT &EDE
Addressing Mode Rn
#N
Note:
Example SWPB R5
RRC @R9
Instruction Format II Immediate Mode
Do not use instructions RRA, RRC, SWPB, and SXT with the immediate mode in the destination field. Use of these in the immediate mode results in an unpredictable program operation.
Format-III (Jump) Instruction Cycles and Lengths All jump instructions require one code word, and take two CPU cycles to execute, regardless of whether the jump is taken or not.
3-72
RISC 16–Bit CPU
TEAM LRN
256
TheMSP430InstructionSet Instruction Set
Format-I (Double Operand) Instruction Cycles and Lengths Table 3–16 lists the length and CPU cycles for all addressing modes of format-I instructions.
Table 3–16.Format 1 Instruction Cycles and Lengths No. of Cycles
Length of Instruction
1
1
MOV
PC
2
1
BR
R9
x(Rm)
4
2
ADD
R5,3(R6)
EDE
4
2
XOR
R8,EDE
&EDE
4
2
MOV
R5,&EDE
Rm
2
1
AND
@R4,R5
PC
3
1
BR
@R8
x(Rm)
5
2
XOR
@R5,8(R6)
EDE
5
2
MOV
@R5,EDE
&EDE
5
2
XOR
@R5,&EDE
Rm
2
1
ADD
@R5+,R6
Addressing Mode Src Rn
@Rn
@Rn+
#N
x(Rn)
EDE
&EDE
Dst Rm
Example R5,R8
PC
3
1
BR
@R9+
x(Rm)
5
2
XOR
@R5,8(R6)
EDE
5
2
MOV
@R9+,EDE
&EDE
5
2
MOV
@R9+,&EDE
Rm
2
2
MOV
#20,R9
PC
3
2
BR
#2AEh
x(Rm)
5
3
MOV
#0300h,0(SP)
EDE
5
3
ADD
#33,EDE
&EDE
5
3
ADD
#33,&EDE
Rm
3
2
MOV
2(R5),R7
PC
3
2
BR
2(R6)
TONI
6
3
MOV
4(R7),TONI
x(Rm)
6
3
ADD
3(R4),6(R9)
&TONI
6
3
MOV
3(R4),&TONI
Rm
3
2
AND
EDE,R6
PC
3
2
BR
EDE
TONI
6
3
CMP
EDE,TONI
x(Rm)
6
3
MOV
EDE,0(SP)
&TONI
6
3
MOV
EDE,&TONI
Rm
3
2
MOV
&EDE,R8
PC
3
2
BRA
&EDE
TONI
6
3
MOV
&EDE,TONI
x(Rm)
6
3
MOV
&EDE,0(SP)
&TONI
6
3
MOV
&EDE,&TONI
RISC 16–Bit CPU
TEAM LRN
257
3-73
AppendixA Instruction Set
3.4.5
Instruction Set Description The instruction map is shown in Figure 3–20 and the complete instruction set is summarized in Table 3–17.
Figure 3–20. Core Instruction Map 000 0xxx 4xxx 8xxx Cxxx 1xxx 14xx 18xx 1Cxx 20xx 24xx 28xx 2Cxx 30xx 34xx 38xx 3Cxx 4xxx 5xxx 6xxx 7xxx 8xxx 9xxx Axxx Bxxx Cxxx Dxxx Exxx Fxxx
3-74
040
080
0C0
RRC RRC.B SWPB
100
RRA
140
180
RRA.B
SXT
1C0
200
240
PUSH
PUSH.B
JNE/JNZ JEQ/JZ JNC JC JN JGE JL JMP MOV, MOV.B ADD, ADD.B ADDC, ADDC.B SUBC, SUBC.B SUB, SUB.B CMP, CMP.B DADD, DADD.B BIT, BIT.B BIC, BIC.B BIS, BIS.B XOR, XOR.B AND, AND.B
RISC 16–Bit CPU
TEAM LRN
258
280
CALL
2C0
300
RETI
340
380
3C0
TheMSP430InstructionSet Instruction Set
Table 3–17.MSP430 Instruction Set Mnemonic ADC(.B)†
V
N
Z
C
dst
Add C to destination
dst + C → dst
*
*
*
*
ADD(.B)
src,dst
Add source to destination
src + dst → dst
*
*
*
*
ADDC(.B)
src,dst
Add source and C to destination
src + dst + C → dst
*
*
*
*
AND(.B)
src,dst
AND source and destination
src .and. dst → dst
0
*
*
*
BIC(.B)
src,dst
Clear bits in destination
.not.src .and. dst → dst
–
–
–
– –
Description
BIS(.B)
src,dst
Set bits in destination
src .or. dst → dst
–
–
–
BIT(.B) BR†
src,dst
Test bits in destination
src .and. dst
0
*
*
*
dst
Branch to destination
dst → PC
–
–
–
–
dst
Call destination
PC+2 → stack, dst → PC
–
–
–
–
dst
Clear destination
0 → dst
–
–
–
–
Clear C
0→C
–
–
–
0
CALL CLR(.B)† CLRC† CLRN† CLRZ†
Clear N
0→N
–
0
–
–
Clear Z
0→Z
–
–
0
– *
CMP(.B)
src,dst
Compare source and destination
dst – src
*
*
*
DADC(.B)†
dst
Add C decimally to destination
dst + C → dst (decimally)
*
*
*
*
DADD(.B) DEC(.B)†
src,dst
Add source and C decimally to dst.
src + dst + C → dst (decimally)
*
*
*
*
dst
Decrement destination
dst – 1 → dst
*
*
*
*
dst
Double-decrement destination
dst – 2 → dst
*
*
*
*
Disable interrupts
0 → GIE
–
–
–
–
DECD(.B)† DINT† EINT† INC(.B)†
Enable interrupts
1 → GIE
–
–
–
–
dst
Increment destination
dst +1 → dst
*
*
*
*
INCD(.B)† INV(.B)†
dst
Double-increment destination
dst+2 → dst
*
*
*
*
dst
Invert destination
.not.dst → dst
*
*
*
*
JC/JHS
label
Jump if C set/Jump if higher or same
–
–
–
–
JEQ/JZ
label
Jump if equal/Jump if Z set
–
–
–
–
JGE
label
Jump if greater or equal
–
–
–
–
JL
label
Jump if less
JMP
label
Jump
JN
label
Jump if N set
–
–
–
–
JNC/JLO
label
Jump if C not set/Jump if lower
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
PC + 2 x offset → PC
–
–
–
–
–
–
–
–
JNE/JNZ
label
Jump if not equal/Jump if Z not set
MOV(.B) NOP†
src,dst
Move source to destination
POP(.B)†
dst
Pop item from stack to destination
@SP → dst, SP+2 → SP
–
–
–
–
PUSH(.B) RET†
src
Push source onto stack
SP – 2 → SP, src → @SP
–
–
–
–
Return from subroutine
@SP → PC, SP + 2 → SP
src → dst
No operation
RETI
–
–
–
–
Return from interrupt
*
*
*
* *
RLA(.B)† RLC(.B)†
dst
Rotate left arithmetically
*
*
*
dst
Rotate left through C
*
*
*
*
RRA(.B)
dst
Rotate right arithmetically
0
*
*
*
RRC(.B) SBC(.B)†
dst
Rotate right through C
*
*
*
*
dst
Subtract not(C) from destination
dst + 0FFFFh + C → dst
*
*
*
*
SETC† SET†
Set C
1→C
–
–
–
1
Set N
1→N
–
1
–
–
SETZ†
Set Z
1→C
–
–
1
–
SUB(.B)
src,dst
Subtract source from destination
dst + .not.src + 1 → dst
*
*
*
*
SUBC(.B)
src,dst
Subtract source and not(C) from dst.
dst + .not.src + C → dst
*
*
*
* –
SWPB
dst
Swap bytes
–
–
–
SXT
dst
Extend sign
0
*
*
*
TST(.B)†
dst
Test destination
dst + 0FFFFh + 1
0
*
*
1
XOR(.B)
src,dst
Exclusive OR source and destination
src .xor. dst → dst
*
*
*
*
† Emulated Instruction
RISC 16–Bit CPU
TEAM LRN
259
3-75
APPENDIX B
StandardRegisterandBitDefinitions fortheMSP430Microcontrollers ThisreferencelistofstandardregisterandbitdefinitionsfortheMSP430microcontrollersisthebasisof muchofthesyntaxicsubstitutionbytheassemblerwhenassemblingandcompilinganassembly-language program.ItisalsoveryusefulwhendevelopingprogramsfortheMSP430familyofmicrocontrollersusing theClanguage. /******************************************************************** * *StandardregisterandbitdefinitionsfortheTexasInstruments *MSP430microcontroller. * *ThisfilesupportsassemblerandCdevelopmentfor *MSP430x12xdevices. * *TexasInstruments,Version2.1 * *Rev.1.1,CorrectedLPMx_EXITtoreferencenewintrinsic_BIC_SR_IRQ * ChangedTAIVtoberead-only * *Rev.1.2,Encloseall#definestatementswithparentheses * *Rev.1.3,DefinedvectorsforUSART(inadditiontoUART) * *Rev.1.4,AddedUSARTspecialfunctionlabels(UxME,UxIE,UxIFG) * *Rev.2.1,AlignmentofdefintionsinUsersGuideandofversionnumbers * ********************************************************************/ #ifndef__msp430x12x #define__msp430x12x #if(((__TID__>>8)&0x7F)!=0x2b)/*0x2b=43dec*/ #errorMSP430X44X.HfileforusewithICC430/A430only #endif
#ifdef__IAR_SYSTEMS_ICC__ #include #pragmalanguage=extended #defineDEFC(name,address)__no_initvolatileunsignedcharname@address; #defineDEFW(name,address)__no_initvolatileunsignedshortname@address; TEAM LRN
260
StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers #endif/*__IAR_SYSTEMS_ICC__*/
#ifdef__IAR_SYSTEMS_ASM__ #defineDEFC(name,address)sfrbname=address; #defineDEFW(name,address)sfrwname=address; #endif/*__IAR_SYSTEMS_ASM__*/ #ifdef__cplusplus #defineREAD_ONLY #else #defineREAD_ONLYconst #endif /************************************************************ *STANDARDBITS ************************************************************/ #defineBIT0 #defineBIT1 #defineBIT2 #defineBIT3 #defineBIT4 #defineBIT5 #defineBIT6 #defineBIT7 #defineBIT8 #defineBIT9 #defineBITA #defineBITB #defineBITC #defineBITD #defineBITE #defineBITF
(0x0001) (0x0002) (0x0004) (0x0008) (0x0010) (0x0020) (0x0040) (0x0080) (0x0100) (0x0200) (0x0400) (0x0800) (0x1000) (0x2000) (0x4000) (0x8000)
/************************************************************ *STATUSREGISTERBITS ************************************************************/ #defineC #defineZ #defineN #defineV #defineGIE #defineCPUOFF #defineOSCOFF #defineSCG0 #defineSCG1
(0x0001) (0x0002) (0x0004) (0x0100) (0x0008) (0x0010) (0x0020) (0x0040) (0x0080)
/*LowPowerModescodedwithBits4-7inSR*/ TEAM LRN
261
AppendixB #ifndef__IAR_SYSTEMS_ICC/*Begin#definesforassembler*/ #defineLPM0 (CPUOFF) #defineLPM1 (SCG0+CPUOFF) #defineLPM2 (SCG1+CPUOFF) #defineLPM3 (SCG1+SCG0+CPUOFF) #defineLPM4 (SCG1+SCG0+OSCOFF+CPUOFF) /*End#definesforassembler*/ #else/*Begin#definesforC*/ #defineLPM0_bits (CPUOFF) #defineLPM1_bits (SCG0+CPUOFF) #defineLPM2_bits (SCG1+CPUOFF) #defineLPM3_bits (SCG1+SCG0+CPUOFF) #defineLPM4_bits (SCG1+SCG0+OSCOFF+CPUOFF) #include #defineLPM0 _BIS_SR(LPM0_bits) /*EnterLowPowerMode0*/ #defineLPM0_EXIT_BIC_SR_IRQ(LPM0_bits)/*ExitLowPowerMode0*/ #defineLPM1 _BIS_SR(LPM1_bits) /*EnterLowPowerMode1*/ #defineLPM1_EXIT_BIC_SR_IRQ(LPM1_bits)/*ExitLowPowerMode1*/ #defineLPM2 _BIS_SR(LPM2_bits) /*EnterLowPowerMode2*/ #defineLPM2_EXIT_BIC_SR_IRQ(LPM2_bits)/*ExitLowPowerMode2*/ #defineLPM3 _BIS_SR(LPM3_bits) /*EnterLowPowerMode3*/ #defineLPM3_EXIT_BIC_SR_IRQ(LPM3_bits)/*ExitLowPowerMode3*/ #defineLPM4 _BIS_SR(LPM4_bits) /*EnterLowPowerMode4*/ #defineLPM4_EXIT_BIC_SR_IRQ(LPM4_bits)/*ExitLowPowerMode4*/ #endif/*End#definesforC*/ /************************************************************ *PERIPHERALFILEMAP ************************************************************/ /************************************************************ *SPECIALFUNCTIONREGISTERADDRESSES+CONTROLBITS ************************************************************/ #defineIE1_ DEFC( IE1 #defineWDTIE #defineOFIE #defineNMIIE #defineACCVIE
(0x0000) /*InterruptEnable1*/ ,IE1_) (0x01) (0x02) (0x10) (0x20)
#defineIFG1_ DEFC( IFG1 #defineWDTIFG #defineOFIFG #defineNMIIFG
(0x0002) /*InterruptFlag1*/ ,IFG1_) (0x01) (0x02) (0x10)
#defineIE2_ DEFC( IE2
(0x0001) /*InterruptEnable2*/ ,IE2_) TEAM LRN
262
StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers #defineU0IE #defineURXIE0 #defineUTXIE0
IE2 (0x01) (0x02)
/*UART0InterruptEnableRegister*/
#defineIFG2_ DEFC( IFG2 #defineU0IFG #defineURXIFG0 #defineUTXIFG0
(0x0003) /*InterruptFlag2*/ ,IFG2_) IFG2 /*UART0InterruptFlagRegister*/ (0x01) (0x02)
#defineME2_ DEFC( ME2 #defineU0ME #defineURXE0 #defineUSPIE0 #defineUTXE0
(0x0005) /*ModuleEnable2*/ ,ME2_) ME2 /*UART0ModuleEnableRegister*/ (0x01) (0x01) (0x02)
/************************************************************ *WATCHDOGTIMER ************************************************************/ #defineWDTCTL_ (0x0120) /*WatchdogTimerControl*/ DEFW( WDTCTL ,WDTCTL_) /*Thebitnameshavebeenprefixedwith“WDT”*/ #defineWDTIS0 (0x0001) #defineWDTIS1 (0x0002) #defineWDTSSEL (0x0004) #defineWDTCNTCL (0x0008) #defineWDTTMSEL (0x0010) #defineWDTNMI (0x0020) #defineWDTNMIES (0x0040) #defineWDTHOLD (0x0080) #defineWDTPW(0x5A00) /*WDT-intervaltimes[1ms]codedwithBits0-2*/ /*WDTisclockedbyfMCLK(assumed1MHz)*/ #defineWDT_MDLY_32 (WDTPW+WDTTMSEL+WDTCNTCL) 32msinterval(default)*/ #defineWDT_MDLY_8 (WDTPW+WDTTMSEL+WDTCNTCL+WDTIS0) 8ms “*/ #defineWDT_MDLY_0_5 (WDTPW+WDTTMSEL+WDTCNTCL+WDTIS1) 0.5ms “*/ #defineWDT_MDLY_0_064 (WDTPW+WDTTMSEL+WDTCNTCL+WDTIS1+WDTIS0) 0.064ms “*/ /*WDTisclockedbyfACLK(assumed32KHz)*/ #defineWDT_ADLY_1000 (WDTPW+WDTTMSEL+WDTCNTCL+WDTSSEL) 1000ms“*/ #defineWDT_ADLY_250 (WDTPW+WDTTMSEL+WDTCNTCL+WDTSSEL+WDTIS0) 250ms “*/ #defineWDT_ADLY_16 (WDTPW+WDTTMSEL+WDTCNTCL+WDTSSEL+WDTIS1) 16ms “*/ TEAM LRN
263
/*
/*
/*
/*
/*
/*
/*
AppendixB #defineWDT_ADLY_1_9 (WDTPW+WDTTMSEL+WDTCNTCL+WDTSSEL+WDTIS1+WDTIS0) 1.9ms “*/ /*Watchdogmode->resetafterexpiredtime*/ /*WDTisclockedbyfMCLK(assumed1MHz)*/ #defineWDT_MRST_32 (WDTPW+WDTCNTCL) 32msinterval(default)*/ #defineWDT_MRST_8 (WDTPW+WDTCNTCL+WDTIS0) 8ms “*/ #defineWDT_MRST_0_5 (WDTPW+WDTCNTCL+WDTIS1) 0.5ms “*/ #defineWDT_MRST_0_064 (WDTPW+WDTCNTCL+WDTIS1+WDTIS0) 0.064ms “*/ /*WDTisclockedbyfACLK(assumed32KHz)*/ #defineWDT_ARST_1000 (WDTPW+WDTCNTCL+WDTSSEL) 1000ms “*/ #defineWDT_ARST_250 (WDTPW+WDTCNTCL+WDTSSEL+WDTIS0) 250ms “*/ #defineWDT_ARST_16 (WDTPW+WDTCNTCL+WDTSSEL+WDTIS1) 16ms “*/ #defineWDT_ARST_1_9 (WDTPW+WDTCNTCL+WDTSSEL+WDTIS1+WDTIS0) 1.9ms “*/ /*INTERRUPTCONTROL*/ /*ThesetwobitsaredefinedintheSpecialFunctionRegisters*/ /*#defineWDTIE 0x01*/ /*#defineWDTIFG 0x01*/ /************************************************************ *DIGITALI/OPort1/2 ************************************************************/ #defineP1IN_ (0x0020) /*Port1Input*/ READ_ONLYDEFC(P1IN ,P1IN_) #defineP1OUT_ (0x0021) /*Port1Output*/ DEFC( P1OUT ,P1OUT_) #defineP1DIR_(0x0022) /*Port1Direction*/ DEFC( P1DIR,P1DIR_) #defineP1IFG_ (0x0023) /*Port1InterruptFlag*/ DEFC( P1IFG,P1IFG_) #defineP1IES_ (0x0024) /*Port1InterruptEdgeSelect*/ DEFC( P1IES ,P1IES_) #defineP1IE_ (0x0025) /*Port1InterruptEnable*/ DEFC( P1IE ,P1IE_) #defineP1SEL_ (0x0026) /*Port1Selection*/ DEFC( P1SEL ,P1SEL_) #defineP2IN_ READ_ONLYDEFC(P2IN #defineP2OUT_ DEFC( P2OUT #defineP2DIR_ DEFC( P2DIR
(0x0028) /*Port2Input*/ ,P2IN_) (0x0029) /*Port2Output*/ ,P2OUT_) (0x002A) /*Port2Direction*/ ,P2DIR_) TEAM LRN
264
/*
/* /* /* /*
/* /* /* /*
StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers #defineP2IFG_ DEFC( P2IFG #defineP2IES_ DEFC( P2IES #defineP2IE_ DEFC( P2IE #defineP2SEL_ DEFC( P2SEL
(0x002B)/*Port2InterruptFlag*/ ,P2IFG_) (0x002C)/*Port2InterruptEdgeSelect*/ ,P2IES_) (0x002D)/*Port2InterruptEnable*/ ,P2IE_) (0x002E)/*Port2Selection*/ ,P2SEL_)
/************************************************************ *DIGITALI/OPort3 ************************************************************/ #defineP3IN_ READ_ONLYDEFC(P3IN #defineP3OUT_ DEFC( P3OUT #defineP3DIR_ DEFC( P3DIR #defineP3SEL_ DEFC( P3SEL
(0x0018) /*Port3Input*/ ,P3IN_) (0x0019) /*Port3Output*/ ,P3OUT_) (0x001A) /*Port3Direction*/ ,P3DIR_) (0x001B) /*Port3Selection*/ ,P3SEL_)
/************************************************************ *USART ************************************************************/ /*UxCTL*/ #definePENA #definePEV #defineSPB #defineCHAR #defineLISTEN #defineSYNC #defineMM #defineSWRST
(0x80) (0x40) (0x20) (0x10) (0x08) (0x04) (0x02) (0x01)
/*Parityenable*/ /*Parity0:odd/1:even*/ /*StopBits0:one/1:two*/ /*Data0:7-bits/1:8-bits*/ /*Listenmode*/ /*UART/SPImode*/ /*MasterModeoff/on*/ /*USARTSoftwareReset*/
/*UxTCTL*/ #defineCKPH #defineCKPL #defineSSEL1 #defineSSEL0 #defineURXSE #defineTXWAKE #defineSTC #defineTXEPT
(0x80) (0x40) (0x20) (0x10) (0x08) (0x04) (0x02) (0x01)
/*SPI:ClockPhase*/ /*ClockPolarity*/ /*ClockSourceSelect1*/ /*ClockSourceSelect0*/ /*ReceiveStartedgeselect*/ /*TXWakeupmode*/ /*SPI:STCenable0:on/1:off*/ /*TXBufferempty*/
/*UxRCTL*/ #defineFE #definePE #defineOE #defineBRK #defineURXEIE
(0x80) (0x40) (0x20) (0x10) (0x08)
/*FrameError*/ /*ParityError*/ /*OverrunError*/ /*Breakdetected*/ /*RXErrorinterruptenable*/ TEAM LRN
265
AppendixB #defineURXWIE #defineRXWAKE #defineRXERR
(0x04) (0x02) (0x01)
/*RXWakeupinterruptenable*/ /*RXWakeupdetect*/ /*RXErrorError*/
/************************************************************ *USART0 ************************************************************/ #defineU0CTL_ DEFC( U0CTL #defineU0TCTL_ DEFC( U0TCTL #defineU0RCTL_ DEFC( U0RCTL #defineU0MCTL_ DEFC( U0MCTL #defineU0BR0_ DEFC( U0BR0 #defineU0BR1_ DEFC( U0BR1 #defineU0RXBUF_ READ_ONLYDEFC(U0RXBUF #defineU0TXBUF_ DEFC( U0TXBUF
(0x0070) /*USART0Control*/ ,U0CTL_) (0x0071) /*USART0TransmitControl*/ ,U0TCTL_) (0x0072) /*USART0ReceiveControl*/ ,U0RCTL_) (0x0073) /*USART0ModulationControl*/ ,U0MCTL_) (0x0074) /*USART0BaudRate0*/ ,U0BR0_) (0x0075) /*USART0BaudRate1*/ ,U0BR1_) (0x0076) /*USART0ReceiveBuffer*/ , U0RXBUF_) (0x0077) /*USART0TransmitBuffer*/ ,U0TXBUF_)
/*Alternateregisternames*/ #defineUCTL0 #defineUTCTL0 #defineURCTL0 #defineUMCTL0 #defineUBR00 #defineUBR10 #defineRXBUF0 #defineTXBUF0 #defineUCTL0_ #defineUTCTL0_ #defineURCTL0_ #defineUMCTL0_ #defineUBR00_ #defineUBR10_ #defineRXBUF0_ #defineTXBUF0_ #defineUCTL_0 #defineUTCTL_0 #defineURCTL_0 #defineUMCTL_0 #defineUBR0_0 #defineUBR1_0 #defineRXBUF_0 #defineTXBUF_0 #defineUCTL_0_
U0CTL U0TCTL U0RCTL U0MCTL U0BR0 U0BR1 U0RXBUF U0TXBUF U0CTL_ U0TCTL_ U0RCTL_ U0MCTL_ U0BR0_ U0BR1_ U0RXBUF_ U0TXBUF_ U0CTL U0TCTL U0RCTL U0MCTL U0BR0 U0BR1 U0RXBUF U0TXBUF U0CTL_
/*USART0Control*/ /*USART0TransmitControl*/ /*USART0ReceiveControl*/ /*USART0ModulationControl*/ /*USART0BaudRate0*/ /*USART0BaudRate1*/ /*USART0ReceiveBuffer*/ /*USART0TransmitBuffer*/ /*USART0Control*/ /*USART0TransmitControl*/ /*USART0ReceiveControl*/ /*USART0ModulationControl*/ /*USART0BaudRate0*/ /*USART0BaudRate1*/ /*USART0ReceiveBuffer*/ /*USART0TransmitBuffer*/ /*USART0Control*/ /*USART0TransmitControl*/ /*USART0ReceiveControl*/ /*USART0ModulationControl*/ /*USART0BaudRate0*/ /*USART0BaudRate1*/ /*USART0ReceiveBuffer*/ /*USART0TransmitBuffer*/ /*USART0Control*/ TEAM LRN
266
StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers #defineUTCTL_0_ U0TCTL_ /*USART0TransmitControl*/ #defineURCTL_0_ U0RCTL_ /*USART0ReceiveControl*/ #defineUMCTL_0_ U0MCTL_ /*USART0ModulationControl*/ #defineUBR0_0_ U0BR0_ /*USART0BaudRate0*/ #defineUBR1_0_ U0BR1_ /*USART0BaudRate1*/ #defineRXBUF_0_ U0RXBUF_ /*USART0ReceiveBuffer*/ #defineTXBUF_0_ U0TXBUF_ /*USART0TransmitBuffer*/ /************************************************************ *TimerA3 ************************************************************/ #defineTAIV_ READ_ONLYDEFW(TAIV #defineTACTL_ DEFW( TACTL #defineTACCTL0_ DEFW( TACCTL0 #defineTACCTL1_ DEFW( TACCTL1 #defineTACCTL2_ DEFW( TACCTL2 #defineTAR_ DEFW( TAR #defineTACCR0_ DEFW( TACCR0 #defineTACCR1_ DEFW( TACCR1 #defineTACCR2_ DEFW( TACCR2
(0x012E) /*TimerAInterruptVectorWord*/ ,TAIV_) (0x0160) /*TimerAControl*/ ,TACTL_) (0x0162) /*TimerACapture/CompareControl0*/ ,TACCTL0_) (0x0164) /*TimerACapture/CompareControl1*/ ,TACCTL1_) (0x0166) /*TimerACapture/CompareControl2*/ ,TACCTL2_) (0x0170) /*TimerA*/ ,TAR_) (0x0172) /*TimerACapture/Compare0*/ ,TACCR0_) (0x0174) /*TimerACapture/Compare1*/ ,TACCR1_) (0x0176) /*TimerACapture/Compare2*/ ,TACCR2_)
/*Alternateregisternames*/ #defineCCTL0 TACCTL0 #defineCCTL1 TACCTL1 #defineCCTL2 TACCTL2 #defineCCR0 TACCR0 #defineCCR1 TACCR1 #defineCCR2 TACCR2 #defineCCTL0_ TACCTL0_ #defineCCTL1_ TACCTL1_ #defineCCTL2_ TACCTL2_ #defineCCR0_ TACCR0_ #defineCCR1_ TACCR1_ #defineCCR2_ TACCR2_ #defineTASSEL2 USARTSSELx*/ #defineTASSEL1 #defineTASSEL0 #defineID1 #defineID0 #defineMC1 #defineMC0
/*TimerACapture/CompareControl0*/ /*TimerACapture/CompareControl1*/ /*TimerACapture/CompareControl2*/ /*TimerACapture/Compare0*/ /*TimerACapture/Compare1*/ /*TimerACapture/Compare2*/ /*TimerACapture/CompareControl0*/ /*TimerACapture/CompareControl1*/ /*TimerACapture/CompareControl2*/ /*TimerACapture/Compare0*/ /*TimerACapture/Compare1*/ /*TimerACapture/Compare2*/
(0x0400)
/*unused*/
(0x0200) (0x0100) (0x0080) (0x0040) (0x0020) (0x0010)
/*TimerAclocksourceselect0*/ /*TimerAclocksourceselect1*/ /*TimerAclockinputdevider1*/ /*TimerAclockinputdevider0*/ /*TimerAmodecontrol1*/ /*TimerAmodecontrol0*/ TEAM LRN
267
/*todistinguishfrom
AppendixB #defineTACLR #defineTAIE #defineTAIFG
(0x0004) (0x0002) (0x0001)
/*TimerAcounterclear*/ /*TimerAcounterinterruptenable*/ /*TimerAcounterinterruptflag*/
#defineMC_0 #defineMC_1 #defineMC_2 #defineMC_3 #defineID_0 #defineID_1 #defineID_2 #defineID_3 #defineTASSEL_0 #defineTASSEL_1 #defineTASSEL_2 #defineTASSEL_3
(0*0x10u) (1*0x10u) (2*0x10u) (3*0x10u) (0*0x40u) (1*0x40u) (2*0x40u) (3*0x40u) (0*0x100u) (1*0x100u) (2*0x100u) (3*0x100u)
/*TimerAmodecontrol:0-Stop*/ /*TimerAmodecontrol:1-UptoCCR0*/ /*TimerAmodecontrol:2-Continousup*/ /*TimerAmodecontrol:3-Up/Down*/ /*TimerAinputdivider:0-/1*/ /*TimerAinputdivider:1-/2*/ /*TimerAinputdivider:2-/4*/ /*TimerAinputdivider:3-/8*/ /*TimerAclocksourceselect:0-TACLK*/ /*TimerAclocksourceselect:1-ACLK*/ /*TimerAclocksourceselect:2-SMCLK*/ /*TimerAclocksourceselect:3-INCLK*/
#defineCM1 #defineCM0 #defineCCIS1 #defineCCIS0 #defineSCS #defineSCCI #defineCAP #defineOUTMOD2 #defineOUTMOD1 #defineOUTMOD0 #defineCCIE #defineCCI #defineOUT #defineCOV #defineCCIFG
(0x8000) (0x4000) (0x2000) (0x1000) (0x0800) (0x0400) (0x0100) (0x0080) (0x0040) (0x0020) (0x0010) (0x0008) (0x0004) (0x0002) (0x0001)
/*Capturemode1*/ /*Capturemode0*/ /*Captureinputselect1*/ /*Captureinputselect0*/ /*Capturesychronize*/ /*Latchedcapturesignal(read)*/ /*Capturemode:1/Comparemode:0*/ /*Outputmode2*/ /*Outputmode1*/ /*Outputmode0*/ /*Capture/compareinterruptenable*/ /*Captureinputsignal(read)*/ /*PWMOutputsignalifoutputmode0*/ /*Capture/compareoverflowflag*/ /*Capture/compareinterruptflag*/
#defineOUTMOD_0 #defineOUTMOD_1 #defineOUTMOD_2 #defineOUTMOD_3 #defineOUTMOD_4 #defineOUTMOD_5 #defineOUTMOD_6 #defineOUTMOD_7 #defineCCIS_0 #defineCCIS_1 #defineCCIS_2 #defineCCIS_3 #defineCM_0 #defineCM_1 #defineCM_2 #defineCM_3
(0*0x20u) /*PWMoutputmode:0-outputonly*/ (1*0x20u) /*PWMoutputmode:1-set*/ (2*0x20u) /*PWMoutputmode:2-PWMtoggle/reset*/ (3*0x20u /*PWMoutputmode:3-PWMset/reset*/ (4*0x20u) /*PWMoutputmode:4-toggle*/ (5*0x20u) /*PWMoutputmode:5-Reset*/ (6*0x20u) /*PWMoutputmode:6-PWMtoggle/set*/ (7*0x20u) /*PWMoutputmode:7-PWMreset/set*/ (0*0x1000u)/*Captureinputselect:0-CCIxA*/ (1*0x1000u)/*Captureinputselect:1-CCIxB*/ (2*0x1000u)/*Captureinputselect:2-GND*/ (3*0x1000u)/*Captureinputselect:3-Vcc*/ (0*0x4000u)/*Capturemode:0-disabled*/ (1*0x4000u)/*Capturemode:1-pos.edge*/ (2*0x4000u)/*Capturemode:1-neg.edge*/ (3*0x4000u)/*Capturemode:1-bothedges*/
TEAM LRN
268
StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers /************************************************************ *BasicClockModule ************************************************************/ #defineDCOCTL_ DEFC( DCOCTL #defineBCSCTL1_ DEFC( BCSCTL1 #defineBCSCTL2_ DEFC( BCSCTL2
(0x0056) /*DCOClockFrequencyControl*/ ,DCOCTL_) (0x0057) /*BasicClockSystemControl1*/ ,BCSCTL1_) (0x0058) /*BasicClockSystemControl2*/ ,BCSCTL2_)
#defineMOD0 #defineMOD1 #defineMOD2 #defineMOD3 #defineMOD4 #defineDCO0 #defineDCO1 #defineDCO2
(0x01) (0x02) (0x04) (0x08) (0x10) (0x20) (0x40) (0x80)
/*ModulationBit0*/ /*ModulationBit1*/ /*ModulationBit2*/ /*ModulationBit3*/ /*ModulationBit4*/ /*DCOSelectBit0*/ /*DCOSelectBit1*/ /*DCOSelectBit2*/
#defineRSEL0 #defineRSEL1 #defineRSEL2 #defineXT5V #defineDIVA0 #defineDIVA1 #defineXTS #defineXT2OFF
(0x01) (0x02) (0x04) (0x08) (0x10) (0x20) (0x40) (0x80)
/*ResistorSelectBit0*/ /*ResistorSelectBit1*/ /*ResistorSelectBit2*/ /*XT5Vshouldalwaysbereset*/ /*ACLKDivider0*/ /*ACLKDivider1*/ /*LFXTCLK0:LowFreq./1:HighFreq.*/ /*EnableXT2CLK*/
#defineDIVA_0 #defineDIVA_1 #defineDIVA_2 #defineDIVA_3
(0x00) (0x10) (0x20) (0x30)
/*ACLKDivider0:/1*/ /*ACLKDivider1:/2*/ /*ACLKDivider2:/4*/ /*ACLKDivider3:/8*/
#defineDCOR #defineDIVS0 #defineDIVS1 #defineSELS LFXTCLK*/ #defineDIVM0 #defineDIVM1 #defineSELM0 #defineSELM1
(0x01) (0x02) (0x04) (0x08)
/*EnableExternalResistor:1*/ /*SMCLKDivider0*/ /*SMCLKDivider1*/ /*SMCLKSourceSelect0:DCOCLK/1:XT2CLK/
(0x10) (0x20) (0x40) (0x80)
/*MCLKDivider0*/ /*MCLKDivider1*/ /*MCLKSourceSelect0*/ /*MCLKSourceSelect1*/
#defineDIVS_0(0x00) #defineDIVS_1(0x02) #defineDIVS_2(0x04) #defineDIVS_3(0x06)
/*SMCLKDivider0:/1*/ /*SMCLKDivider1:/2*/ /*SMCLKDivider2:/4*/ /*SMCLKDivider3:/8*/
#defineDIVM_0 #defineDIVM_1 #defineDIVM_2
/*MCLKDivider0:/1*/ /*MCLKDivider1:/2*/ /*MCLKDivider2:/4*/
(0x00) (0x10) (0x20)
TEAM LRN
269
AppendixB #defineDIVM_3
(0x30)
/*MCLKDivider3:/8*/
#defineSELM_0 #defineSELM_1 #defineSELM_2 #defineSELM_3
/*MCLKSourceSelect0:DCOCLK*/ /*MCLKSourceSelect1:DCOCLK*/ /*MCLKSourceSelect2:XT2CLK/LFXTCLK*/ /*MCLKSourceSelect3:LFXTCLK*/
(0x00) (0x40) (0x80) (0xC0)
/************************************************************* *FlashMemory *************************************************************/ #define DEFW( #define DEFW( #define DEFW(
FCTL1_ FCTL1 FCTL2_ FCTL2 FCTL3_ FCTL3
(0x0128) /*FLASHControl1*/ ,FCTL1_) (0x012A) /*FLASHControl2*/ ,FCTL2_) (0x012C) /*FLASHControl3*/ ,FCTL3_)
#define FRKEY #define FWKEY #define FXKEY
(0x9600) /*Flashkeyreturnedbyread*/ (0xA500) /*Flashkeyforwrite*/ (0x3300) /*forusewithXORinstruction*/
#define ERASE #define MERAS #define WRT #define BLKWRT #define SEGWRT segmentwrite*/
(0x0002) (0x0004) (0x0040) (0x0080) (0x0080)
/*EnablebitforFlashsegmenterase*/ /*EnablebitforFlashmasserase*/ /*EnablebitforFlashwrite*/ /*EnablebitforFlashsegmentwrite*/ /*olddefinition*//*EnablebitforFlash
#define FN0 (0x0001) toFN5accordingto:*/ #define FN1 (0x0002 +FN0+1*/ #ifndefFN2 #define FN2 (0x0004) #endif #ifndefFN3 #define FN3 (0x0008) #endif #ifndefFN4 #define FN4 (0x0010) #endif #define FN5 (0x0020) #define FSSEL0 (0x0040) distinguishfromUSARTSSELx*/ #define FSSEL1 (0x0080)
/*DevideFlashclockby1to64usingFN0
#define #define #define #define
/*Flashclockselect:0-ACLK*/ /*Flashclockselect:1-MCLK*/ /*Flashclockselect:2-SMCLK*/ /*Flashclockselect:3-SMCLK*/
FSSEL_0 FSSEL_1 FSSEL_2 FSSEL_3
(0x0000) (0x0040) (0x0080) (0x00C0)
/*32*FN5+16*FN4+8*FN3+4*FN2+2*FN1
/*Flashclockselect0*/
/*to
/*Flashclockselect1*/
TEAM LRN
270
StandardRegisterandBitDefinitionsfortheMSP430Microcontrollers #define BUSY #define KEYV #define ACCVIFG #define WAIT #define LOCK only)*/ #define EMEX
(0x0001) (0x0002) (0x0004) (0x0008) (0x0010)
/*Flashbusy:1*/ /*FlashKeyviolationflag*/ /*FlashAccessviolationflag*/ /*Waitflagforsegmentwrite*/ /*Lockbit:1-Flashislocked(read
(0x0020) /*FlashEmergencyExit*/
/************************************************************ *ComparatorA ************************************************************/ #defineCACTL1_ DEFC(CACTL1 #defineCACTL2_ DEFC( CACTL2 #defineCAPD_ DEFC( CAPD
(0x0059) /*ComparatorAControl1*/ ,CACTL1_) (0x005A) /*ComparatorAControl2*/ ,CACTL2_) (0x005B) /*ComparatorAPortDisable*/ ,CAPD_)
#defineCAIFG #defineCAIE #defineCAIES falling*/ #defineCAON #defineCAREF0 #defineCAREF1 #defineCARSEL #defineCAEX
(0x01) (0x02) (0x04)
/*Comp.AInterruptFlag*/ /*Comp.AInterruptEnable*/ /*Comp.AInt.EdgeSelect:0:rising/1:
(0x08) (0x10) (0x20) (0x40) (0x80)
/*Comp.Aenable*/ /*Comp.AInternalReferenceSelect0*/ /*Comp.AInternalReferenceSelect1*/ /*Comp.AInternalReferenceEnable*/ /*Comp.AExchangeInputs*/
#defineCAREF_0 #defineCAREF_1 #defineCAREF_2 #defineCAREF_3
(0x00) (0x10) (0x20) (0x30)
/*Comp.AInt.Ref.Select0:Off*/ /*Comp.AInt.Ref.Select1:0.25*Vcc*/ /*Comp.AInt.Ref.Select2:0.5*Vcc*/ /*Comp.AInt.Ref.Select3:Vt*/
#defineCAOUT (0x01) #defineCAF (0x02) #defineP2CA0 (0x04) 1*/ #defineP2CA1(0x08) 1*/ #defineCACTL24 (0x10) #defineCACTL25 (0x20) #defineCACTL26 (0x40) #defineCACTL27 (0x80)
/*Comp.AOutput*/ /*Comp.AEnableOutputFilter*/ /*Comp.AConnectExternalSignaltoCA0:
#defineCAPD0 Register.0*/ #defineCAPD1 Register.1*/ #defineCAPD2 Register.2*/ #defineCAPD3
(0x01)
/*Comp.ADisableInputBufferofPort
(0x02)
/*Comp.ADisableInputBufferofPort
(0x04)
/*Comp.ADisableInputBufferofPort
(0x08)
/*Comp.AConnectExternalSignaltoCA1:
/*Comp.ADisableInputBufferofPort TEAM LRN
271
AppendixB Register.3*/ #defineCAPD4 Register.4*/ #defineCAPD5 Register.5*/ #defineCAPD6 Register.6*/ #defineCAPD7 Register.7*/
(0x10)
/*Comp.ADisableInputBufferofPort
(0x20)
/*Comp.ADisableInputBufferofPort
(0x40)
/*Comp.ADisableInputBufferofPort
(0x80)
/*Comp.ADisableInputBufferofPort
/************************************************************ *InterruptVectors(offsetfrom0xFFE0) ************************************************************/ #definePORT1_VECTOR #definePORT2_VECTOR #defineUSART0TX_VECTOR #defineUSART0RX_VECTOR #defineTIMERA1_VECTOR #defineTIMERA0_VECTOR #defineWDT_VECTOR #defineCOMPARATORA_VECTOR #defineNMI_VECTOR #defineRESET_VECTOR
(2*2u) /*0xFFE4Port1*/ (3*2u) /*0xFFE6Port2*/ (6*2u)/*0xFFECUSART0Transmit*/ (7*2u) /*0xFFEEUSART0Receive*/ (8*2u) /*0xFFF0TimerACC1-2,TA*/ (9*2u) /*0xFFF2TimerACC0*/ (10*2u)/*0xFFF4WatchdogTimer*/ (11*2u)/*0xFFF6ComparatorA*/ (14*2u)/*0xFFFCNon-maskable*/ (15*2u)/*0xFFFEReset[HighestPriority]*/
#defineUART0TX_VECTOR #defineUART0RX_VECTOR
USART0TX_VECTOR USART0RX_VECTOR
/************************************************************ *EndofModules ************************************************************/ #pragmalanguage=default #endif/*#ifndef__msp430x12x*/
TEAM LRN
272
APPENDIX C
ApplicationProgram forUseinChapter10 ThefollowingisacopyoftheapplicationprogramwrittenintheClanguageforuseintheprojectofChapter10.ThelatestversionofthisprogramshouldbedownloadedfromTexasInstrumentsIncorporatedWeb siteathttp://www.ti.com.TheinstructionsfordoingthisarecontainedinChapter10. TheprogramwaswrittenbyNealFragerofTexasInstrumentsIncorporated,andisusedbypermissionand courtesyofTexasInstrumentsIncorporated. TimeDateTemp.c //***************************************************************************** ** // MSP-FET430P120-TempSensor+Clock // // N.Frager // TexasInstruments,Inc // February2003 // BuiltwithIAREmbeddedWorkbenchVersion:1.26A // VersionforMSP-FET430P120 //****************************************************************************** #include //DefinesegmentsonLEDdisplay #definea0x01 #defineb0x02 #definec0x04 #defined0x08 #definee0x10 #definef0x20 #defineg0x40 //DefinenumbersonLEDdisplay #definezero a+b+c+d+e+f #defineone b+c #definetwo a+b+d+e+g #definethree a+b+c+d+g #definefour b+c+f+g #definefive a+c+d+f+g #definesix a+c+d+e+f+g #defineseven a+b+c #defineeight a+b+c+d+e+f+g TEAM LRN
273
AppendixC #definenine #definecelcius #definefahrenheit #defineblank
a+b+c+f+g d+e+g a+e+f+g 0x00
//Definebuttonpressnumbers #defineNOPUSH0 #defineMODE1 #defineTOGGLE2 //Definestatevalues #defineSHOW_TIME 0 #defineSHOW_DATE 1 #defineSHOW_YEAR 2 #defineSHOW_TEMP 3 #defineSET_HOUR 4 #defineSET_MIN 5 #defineSET_MONTH 6 #defineSET_DAY 7 #defineSET_YEAR 8 #defineAUTO_TOGGLE 9 //DefineExtraAutoToggleStates #defineSHOW_TEMP_F3 #defineSHOW_TEMP_C4 //DefineClockandDatevalues #defineJAN1 #defineFEB2 #defineMAR3 #defineAPR4 #defineMAY5 #defineJUN6 #defineJUL7 #defineAUG8 #defineSEP9 #defineOCT10 #defineNOV11 #defineDEC12 #defineCLK_PER_TEMP512 #defineCLK_PER_SEC512 #defineSEC_PER_MIN60 #defineMIN_PER_HR60 #defineMIN_YEAR2000 #defineMAX_YEAR2100 TEAM LRN
274
ApplicationProgramforUseinChapter10
#defineTRUE1 #defineFALSE0 //SystemRoutines voidinitialize(void); voidclocktick(void); voiddisplay(void); voiddisplaydigit(int); voidfillbuffer(void);
//initializeportsandvariables //runthesystemclock //displaydriver //digitdisplayroutine //fill4-digitbuffer
//Globalvariables unsignedintdigcount,dig1,dig2,dig3,dig4;//digitbuffer unsignedintclock_count,sec,min,hour,ampm;//clockvalues unsignedintmonth,day,year;//datevalues unsignedintmainstate;//mainstatemachine unsignedintbuttonpress,buttonpush;//buttonpresssignal unsignedinttoggle_count;//allowforfasterclockupdate unsignedintblink,timer;//controlblinkingfunctionality unsignedintdata,temp,temp_type,temp_count,temp_done;//temperaturedisplay unsignedinttogglestate;//autotogglestatemachine unsignedinttoggletimer;//2secondautotoggletimer unsignedintawake;//sleepmode(FALSE=sleep,TRUE=awake) unsignedintsleepcount;//counts15secondsuntilsleep unsignedintautowakecount;//counts20minutesuntilautowakeup //temperaturetable unsignedinttemp_array[28][2]={ {0,320},{14,345},{28,370},{42,395}, {56,420},{69,445},{83,470},{97,495}, {111,520},{125,545},{139,570},{153,595}, {167,620},{181,645},{194,670},{208,695}, {222,720},{236,745},{250,770},{264,795}, {278,820},{292,845},{306,870},{319,895}, {333,920},{347,945},{361,970},{375,995}}; //MainFunction voidmain(void) { initialize();//initializeports,timerAandvariables for(;;)//mainstatemachine-runcontinuously { switch(mainstate){ caseSHOW_TIME://displaytime if(buttonpress&(buttonpush==TOGGLE)){ mainstate=SHOW_DATE; TEAM LRN
275
AppendixC
buttonpress=0; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SET_HOUR; buttonpress=0; } break; caseSHOW_DATE://displaydate if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SHOW_YEAR; buttonpress=0; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SET_MONTH; buttonpress=0; } break; caseSHOW_YEAR://displayyear if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SHOW_TEMP; buttonpress=0; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SET_YEAR; buttonpress=0; } break; caseSHOW_TEMP://displaytemperature if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SHOW_TIME; buttonpress=0; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SHOW_TEMP; buttonpress=0; temp_type^=0x01; } break; caseSET_HOUR://setthehour if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SET_HOUR; buttonpress=0; hour++; if(hour==12) ampm^=0x01; if(hour>12) hour=1; TEAM LRN
276
ApplicationProgramforUseinChapter10
} elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SET_MIN; buttonpress=0; } break; caseSET_MIN: //settheminute if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SET_MIN; buttonpress=0; min++; if(min==MIN_PER_HR) min=0; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SHOW_TIME; buttonpress=0; } break; caseSET_MONTH: //setthemonth if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SET_MONTH; buttonpress=0; month++; if(month>DEC) month=JAN; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SET_DAY; buttonpress=0; } break; caseSET_DAY://settheday if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SET_DAY; buttonpress=0; day++; //Februarycalculation if((year%4)==0){//leapyear if((month==FEB)&&(day>29)) day=1; } else{ if((month==FEB)&&(day>28)) day=1; } TEAM LRN
277
AppendixC //30daymonths if(((month==APR)||(month==JUN)||(month==SEP)||(month ==NOV))&&(day>30)) day=1; //31daymonths if(day>31) day=1; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SHOW_DATE; buttonpress=0; } break; caseSET_YEAR://settheyear if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=SET_YEAR; buttonpress=0; year++; if(year>=MAX_YEAR) year=MIN_YEAR; } elseif(buttonpress&&(buttonpush==MODE)){ mainstate=SHOW_YEAR; buttonpress=0; } break; caseAUTO_TOGGLE://autotogglestate if(buttonpress&&(buttonpush==TOGGLE)){ mainstate=togglestate; if(mainstate==SET_HOUR)//Celciusexceptioncase mainstate=SHOW_TEMP; buttonpress=0; } elseif(buttonpress&&(buttonpush==MODE)){ awake=0;//systemsleepswithMODEpush P1OUT=0x00;//turnoffanalogsystem P2OUT=0x00; P3OUT=blank; CCR0=32767;//slowto1Hzinterruptspeed buttonpress=0; } break; } if(awake)fillbuffer();//fillthe4-digitbuffer LPM3; TEAM LRN
278
ApplicationProgramforUseinChapter10 }
}
//PORT1PushButtoninterruptserviceroutine-runonbuttonpress
#if__VER__=1024){//2secondautotoggle togglestate++; togglestate%=5; TEAM LRN
280
ApplicationProgramforUseinChapter10
}
toggletimer=0; } if(togglestate==SHOW_TEMP_F) temp_type=1; if(togglestate==SHOW_TEMP_C) temp_type=0; } elsetoggletimer=0;
//SystemSleepController if(awake){ if((P1IN&0xC0)==0xC0){ sleepcount++; if(sleepcount>=15360){//512Hz*30seconds=15360cycles awake=FALSE;//systemsleepsafter15seconds autowakecount=0;//resetautowakeclock P1OUT=0x00;//turnoffanalogsystem P2OUT=0x00; P3OUT=blank; CCR0=32767;//slowto1Hzinterruptspeed } } elsesleepcount=0; }
//PushButtonDebounce-runat32Hz if(awake){ if((P1IN&0xC0)==0x40){//P1.7=TOGGLE sleepcount=0; if((mainstate==SET_HOUR)|(mainstate==SET_MIN)| (mainstate==SET_MONTH)|(mainstate==SET_DAY)| (mainstate==SET_YEAR)){ toggle_count++; if(toggle_count>=80){//updatebuttonheldfor80/512seconds toggle_count=0; buttonpress=1;//sendanotherbuttonpresssignal } } if((mainstate==SHOW_TIME)|(mainstate==SHOW_DATE)| (mainstate==SHOW_YEAR)|(mainstate==SHOW_TEMP)){ toggle_count++; if(toggle_count>=1024){//2secondhold toggle_count=0; togglestate=mainstate; mainstate=AUTO_TOGGLE; TEAM LRN
281
AppendixC
}
if(togglestate==SHOW_TEMP){ if(temp_type) togglestate=SHOW_TEMP_F; elsetogglestate=SHOW_TEMP_C; } } } } elseif((P1IN&0xC0)==0x80){//P1.6=MODE sleepcount=0; } elseP1IFG=0x00;//ButtonReleased
}
//Displayadigit-runat512Hz if(awake){//runsonlyifsystemisawake display(); LPM3_EXIT; } else{//clearLEDsandshutdownanalogsincesystemissleeping P1OUT=0x00; P2OUT=0x00; P3OUT=blank; }
//SystemClock-runsat1Hz voidclocktick(void) { sec++;
//updateminutes if(sec>=SEC_PER_MIN){ sec=0; min++; if((min==20)||(min==40)||(min==60)){ autowakecount=0; toggle_count=0; sleepcount=0; awake=TRUE;//systemwakesup-autowake P1OUT=0x18;//turnonanalogsystem CCR0=63;//returnto512Hzinterruptspeed } } //updatehours TEAM LRN
282
ApplicationProgramforUseinChapter10 if(min>=MIN_PER_HR){ min=0; hour++; if(hour==12){ ampm^=0x01; if(!ampm){ day++; } } } if(hour>12){ hour=1; } //updatedays //Februaryupdate if((year%4)==0){//leapyear if((month==FEB)&&(day>29)){ day=1; month++; } } else{//nonleapyear if((month==FEB)&&(day>28)){ day=1; month++; } } //30daymonthupdate if(((month==APR)||(month==JUN)||(month==SEP)||(month==NOV))&& (day>30)){ day=1; month++; } //31daymonthupdate if(day>31){ day=1; month++; } //updateyear if(month>DEC){ month=1; year++; } //resetyearwhenmaxisreached if(year>=MAX_YEAR){ year=MIN_YEAR; TEAM LRN
283
AppendixC }
}
//initializeports,TimerA0andvariables-runonceatstart voidinitialize(void) { WDTCTL=WDTPW+WDTHOLD; //Stopwatchdogtimer TACTL=TASSEL_1+TACLR; //ACLK,clearTAR CCTL0=CCIE; //CCR0interruptenabled CCR0=63; //TimerAinteruptsat512Hz
digcount=0;//resetdigitbuffer dig1=0; dig2=0; dig3=0; dig4=0;
clock_count=0;//resetclockvars sec=0; min=0; hour=12; ampm=0;
mainstate=SHOW_TIME;//resetstatemachines togglestate=SHOW_TIME; buttonpush=NOPUSH; buttonpress=0; toggle_count=0; toggletimer=0; awake=TRUE;//systemisawake sleepcount=0; autowakecount=0;
month=JAN;//resetdatevars day=1; year=MIN_YEAR;
timer=0;//initializeblinkingfunctionality blink=0; temp=0;//settempoutput data=0; temp_type=1; temp_count=0; temp_done=0; TEAM LRN
284
ApplicationProgramforUseinChapter10 P1DIR=0x3F;//SetI/Oports P2DIR=0xFF; P3DIR=0x7F; P1IES=0xC0; P1IFG=0x00; P1IE=0xC0; P1OUT=0x18;//TurnA/Doff TACTL|=ID_0; TACTL|=MC_1;//StartTimer_ainupmode _EINT();//Enableinterrupts }
//Fill4-digitbuffer-runscontinuously voidfillbuffer(void) { unsignedintcounter; //determineclockdigits if((mainstate==SHOW_TIME)||(mainstate==SET_HOUR)||(mainstate==SET_ MIN)|| ((mainstate==AUTO_TOGGLE)&&(togglestate==SHOW_TIME))){ dig1=hour/10; dig2=hour%10; dig3=min/10; dig4=min%10; if(ampm)//AM/PMlights P1OUT=0x1F; elseP1OUT=0x1B; } //determinedatedigits elseif((mainstate==SHOW_DATE)||(mainstate==SET_MONTH)||(mainstate ==SET_DAY)|| ((mainstate==AUTO_TOGGLE)&&(togglestate==SHOW_DATE))){ dig1=month/10; dig2=month%10; dig3=day/10; dig4=day%10; P1OUT=0x1A; } //determineyeardigits elseif((mainstate==SHOW_YEAR)||(mainstate==SET_YEAR)|| TEAM LRN
285
AppendixC ((mainstate==AUTO_TOGGLE)&&(togglestate==SHOW_YEAR))){ dig1=year/1000; dig2=(year/100)%10; dig3=(year/10)%10; dig4=year%10; P1OUT=0x18; } //determinetempdigits elseif((mainstate==SHOW_TEMP)||((mainstate==AUTO_TOGGLE)&&(togglestate>=SHOW_TEMP))){ if(!temp_done){//updatetemponcepersecond data=0; P1OUT&=0x17;//TurnA/Don for(counter=10;counter>0;) { data=data