Using 8096

108
APPLICATION NOTE AP-248 September 1987 Using The 8096 IRA HORDEN MCO APPLICATIONS ENGINEER Order Number: 270061-002

description

microprocessor and its controllers

Transcript of Using 8096

APPLICATIONNOTEAP-248Septembei 1987UsingThe8096IRAHORDENMCOAPPLICATIONSFNOINFFROrder Number 270061-002Information in this document is provided in connection with Intel products Intel assumes no liability whatsoev-erincludinginfringementofanypatentorcopyrightforsaleanduseofIntel productsexceptasprovidedinIntelsTermsandConditionsofSaleforsuchproductsIntel retainstheright tomakechangestothesespecificationsat anytime without notice MicrocomputerProductsmayhaveminorvariationstothisspecificationknownaserrataOtherbrandsandnamesarethepropertyoftheirrespectiveownersSincepublicationof documentsreferencedinthisdocument registrationof thePentium OverDriveandiCOMPtrademarkshasbeenissuedtoIntel CorporationContactyourlocal Intel salesofficeoryourdistributortoobtainthelatestspecificationsbeforeplacingyourproductorderCopiesof documentswhichhaveanorderingnumber andarereferencedinthisdocument or other IntelliteraturemaybeobtainedfromIntel CorporationPOBox7641MtProspectIL60056-7641orcall 1-800-879-4683COPYRIGHT INTEL CORPORATION 1996Using The 8096CONTENTS PAGE10 INTRODUCTION 120 8096OVERVIEW 121 General Description 1211 CPU Section 2212 IO Features 422 The Processor Section 4221 Operations and AddressingModes 4222 Assembly Language7223 Interrupts823 On-Chip IO Section10231 TimerCounters10232 HSI11233 HSO 12234 Serial Port13235 A to D Converter16236 PWM Register1730 BASICSOFTWAREEXAMPLES 1931 Using the 8096s ProcessingSection 19311 Table Interpolation 19312 PLM-96 2232 Using the IO Section 24321 Using the HSI Unit24322 Using the HSO Unit25323 Using the Serial Port inMode 1 29324 Using the A to D 3140 ADVANCEDSOFTWAREEXAMPLES3141 Simultaneous IO Routines underInterrupt Control3142 Software Serial Port Using theHSIO Unit3443 Interfacing an Optical Encoder tothe HSI Unit3950 HARDWAREEXAMPLE 5151 EPROM Only MinimumSystem 5152 Port Reconstruction 5360 CONCLUSION 5470 BIBLIOGRAPHY 54CONTENTS PAGEAPPENDICESAppendixABasicSoftwareExamplesA-1A1 Table Lookup 1 A-1A2 Table Lookup 2 A-3A3 PLM-96 Code with Expansion A-5A4 Pulse MeasurementA-11A5 Enchanced Pulse MeasurementA-13CONTENTS PAGEA6 PWM Using the HSOA-15A7 Serial PortA-19A8 A to D ConverterA-21AppendixBHSOandAtoDUnderInterruptControlB-1AppendixCSoftwareSerialPortC-1AppendixDMotorControlProgram D-1Figures2-1 8096 Block Diagram 12-2 Memory Map22-3 SFR Layout32-4 Major IO Functions42-5 Instruction Summary52-6 Instruction Format72-7 Interrupt Sources82-8 Interrupt Vectors and Priorities82-9 Interrupt Structure BlockDiagram 92-10 The PSW Register102-11 HSI Unit Block Diagram 112-12 HSI Mode Register112-13 HSO Command Register 122-14 HSO Block Diagram 122-15 Serial Port ControlStatusRegister132-16 Baud Rate Formulas 142-17 Baud Rate Values for 10 11 12MHz 152-18 Multiprocessor Communication162-19 A to D ResultCommandRegister172-20 PWM Output Waveforms 182-21 PWM to Analog ConversionCircuitry183-1 Using the HSIO to Monitor RotatingMachinery283-2 Serial Port Level Conversion304-1 10-Bit Asynchronous Frame 354-2 Optical Encoder and Waveforms394-3 Filtered Encoder Waveforms 404-4 Schematic of Optical Encoder to8096 Interface 414-5 Motor Driver Circuitry414-6 Mode State Diagram 444-7 Motor Control Modes495-1 Minimum System Configuration52Listings3-1 Include File DEMO96INC 193-2 ASM-96 Code for Table LookupRoutine 1 203-3 ASM-96 Code for Table LookupRoutine 1 213-4 PLM-96 Code for Table LookupRoutine 1 233-5 32-Bit Result Multiply Procedure forPLM-96 233-6 Measuring Pulses Using the HSIUnit243-7 Enhanced HSI Pulse MeasurementRoutine 253-8 Generating a PWM with the HSO 263-9 Changes to Declarations for HSORoutine 273-10 Driver Module for HSO PWMProgram 273-11 Using the Serial Port in Mode 1 293-12 Scanning the A to D Channels314-1 Using Multiple IO Devices 324-2 Software Serial PortDeclarations 354-3 Software Serial Port InterfaceRoutines364-4 Software Serial Port InitializationRoutine 364-5 Software Serial Port TransmitProcess374-6 Receive Process 374-7 Motor Control HSO0 TimerRoutine 424-8 Motor Control HSI Data AvailableRoutine 444-9 Motor Control Mode 1 Routines454-10 Motor Control Mode 0 Routines464-11 Motor Control Software Timer 1Routine 474-12 Motor Control Next PositionLookup 494-13 Motor Control Timer InterruptRoutine 504-14 Motor Control Software TimerInterrupt Handler504-15 Motor Control Software Timer 2Routine 51AP-24810INTRODUCTIONHigh speed digitaI signaIs aie fiequentIy encounteied inmodeincontioIappIications.Inaddition,theieisoftena iequiiement foi high speed 16-bit and 32-bit piecisionin caIcuIations. The MCS-96 pioduct Iine, geneiicaIIyiefeiiedtoasthe8096,isdesignedtobeusedinappIi-cationswhichiequiiehighspeedcaIcuIationsandfastI/Oopeiations.The 8096 is a 16-bit miciocontioIIei with dedicatedI/OsubsystemsandacompIetesetof16-bitaiithmeticinstiuctions incIudingmuItipIyanddivideopeiations.This Ap-note wiII biiefIy desciibe the 8096 in section 2,andthengiveshoitexampIesofhowtouseeachofitskeyfeatuiesinsection3. TheconcIudingsectionsfea-tuie afewexampIes whichmake use of seveiaI chipfeatuies simuItaneousIy and some haidwaie connectionsuggestions. Fuithei infoimationonthe8096anditsuseisavaiIabIefiomthesouicesIistedinthebibIiogia-phy.208096OVERVIEW21 General DescriptionUnIikemiciopiocessois,miciocontioIIeisaiegeneiaIIyoptimized foi specific appIications. InteIs 8048 was op-timizedfoi geneiaI contioI tasks whiIe the 8051wasoptimizedfoi8-bitmathandsingIebitbooIeanopeia-tions.The8096hasbeendesignedfoihighspeed/highpeifoimancecontioI appIications. Becauseit hasbeendesignedfoitheseappIicationsthe8096aichitectuieisdiffeientfiomthatofthe8048oi8051.Theie aie twomajoi sections of the 8096, the CPUsectionandtheI/Osection.Fachofthesesectionscanbe subdivided into functionaI bIocks as shown in Figuie2-1.2700611Figure 2-1 8096 Block Diagram1AP-248211 CPUSECTIONThe CPU of the 8096 uses a 16-bit ALU which opeiatesona256-byteiegistei fiIeinsteadof anaccumuIatoi.AnyoftheIocationsintheiegisteifiIecanbeusedfoisouices oi destinations foi most of the instiuctions.ThisiscaIIedaiegisteitoiegisteiaichitectuie. Manyof the instiuctions canaIsouse bytes oi woids fiomanywheie in the 64K byte addiess space as opeiands. AmemoiymapisshowninFiguie2-2.In the Iowei 24 bytes of the iegistei fiIe aie the iegistei-mapped I/O contioI Iocations, aIso caIIed SpeciaIFunction Registeis oi SFRs. These iegisteis aie used tocontioI the on-chipI/Ofeatuies. The iemaining232bytes aie geneiaI puipose RAM, the uppei 16 of whichcan be kept aIive using a Iowcuiient powei-downmode.2700612Figure 2-2 Memory Map2AP-248Figuie 2-3 shows the Iayout of the iegistei mappedI/O.Someoftheseiegisteisseivetwofunctions,oneifthey aie iead fiomand anothei if they aie wiittento.MoieinfoimationabouttheuseoftheseiegisteisisincIudedinthedesciiptionof thefeatuieswhichtheycontioI.2700613Figure 2-3 SFR Layout3AP-248212 IOFEATURESManyoftheI/Ofeatuiesonthe8096aiedesignedtoopeiate with IittIe CPU inteivention. A Iist of the majoiI/OfunctionsisshowninFiguie2-4. TheWatchdogTimeiisaninteinaI timeiwhichcanbeusedtoiesetthe system if the softwaie faiIs to opeiate piopeiIy. ThePuIse-Width-ModuIation (PWM) output can be used asaioughDtoA, amotoi diivei, oi foi manyotheipuiposes. TheAtoDconveitei (ADC) has 8muIti-pIexedinputsand10-bitiesoIution.TheseiiaIpoithasseveiaI modes andits ownbaudiate geneiatoi. TheHigh Speed I/O section incIudes a 16-bit timei, a 16-bitcountei,a4-inputpiogiammabIeedgedetectoi,4soft-waie timeis, and a 6-output piogiammabIe event genei-atoi. AII of thesefeatuieswiII bedesciibedinsection2.3.22 The Processor Section221 OPERATIONSANDADDRESSINGMODESThe8096has100instiuctions, someofwhichopeiateonbits, someonbytes, someonwoids andsomeonIongs(doubIewoids). AII of thestandaidIogicaI andaiithmetic functions aie avaiIabIe foi both byte andwoid opeiations. Bit opeiations and Iong opeiations aiepiovidedfoisomeinstiuctions.TheieaieaIsofIagma-nipuIation instiuctions as weII as jump and caII instiuc-tions. A fuII set of conditionaI jumps has been incIudedtospeeduptestingfoivaiiousconditions.BitopeiationsaiepiovidedbytheJumpBitandJumpNotBitinstiuctions, asweIIasbyimmediatemaskingofbytes.ThesebitopeiationscanbepeifoimedonanyofthebytesintheiegisteifiIeoionanyofthespeciaIfunction iegisteis. The fast bit manipuIation of theSFRscanpiovideiapidI/Oopeiations.Asymmetiicsetofbyteandwoidopeiationsmakeupthemajoiityofthe8096instiuctionset. TheassembIyIanguagefoithe8096(ASM-96)usesaBsuffixonamnemonic to indicate a byte opeiation, without thissuffixawoidopeiationisindicated.Manyoftheseop-eiations can have one, two oi thiee opeiands. An exam-pIeofaoneopeiandinstiuctionwouIdbe:NOT Value1Value1e1s complement (Value1)AtwoopeiandinstiuctionwouIdhavethefoim:ADD Value2Value1Value2eValue2 aValue1AthieeopeiandinstiuctionmightIookIike:MUL Value3Value2Value1Value3eValue2

Value1Thethieeopeiandinstiuctionscombinedwiththeieg-istei to iegistei aichitectuie aImost eIiminate the neces-sity of using tempoiaiy iegisteis. This iesuIts in a fasteipiocessingtimethanmachinesthathaveequivaIentin-stiuctionexecutiontimes, butuseastandaidaichitec-tuie.Long(32-bit)opeiationsincIudeshifts, noimaIize, andmuItipIyanddivide.Thewoiddivideisa32-bitby16-bitopeiationwitha16-bitquotientand16-bitiemain-dei. The woidmuItipIyis a woidbywoidmuItipIywith a Iong iesuIt. Both of these opeiations can be doneineitheithesignedoiunsignedmode. Thediiectun-signedmodesoftheseinstiuctionstakeonIy6.5micio-seconds. AnoimaIize instiuction andsticky bit fIaghave beenincIudedinthe instiuctionset to piovidehaidwaiesuppoitfoithesoftwaiefIoatingpointpack-age(FPAL-96).Major IO FunctionsHigh Speed Input Unit Provides Automatic Recording of EventsHigh Speed Output Unit Provides Automatic Triggering of Events and Real-Time InterruptsPulse Width Modulation Output to Drive Motors or Analog CircuitsA to D Converter Provides Analog InputWatchdog Timer Resets 8096 if a Malfunction OccursSerial Port Provides Synchronous or Asynchronous LinkStandard IO Lines Provide Interface to the External World when other Special Featuresare not neededFigure 2-4 Major IO Functions4AP-248MnemonicOper-Operation (Note 1)FlagsNotesands Z N C V VT STADDADDB 2 D wD a A u ADDADDB 3 D wB a A u ADDCADDCB 2 D wD a A aC vu SUBSUBB 2 D wD bA u SUBSUBB 3 D wB bA u SUBCSUBCB 2 D wD bA a C b1 vu CMPCMPB 2 D bA u MULMULU 2 D D a 2 wD A 2MULMULU 3 D D a 2 wB A 2MULBMULUB 2 D D a 1 wD A 3MULBMULUB 3 D D a 1 wB A 3DIVU 2 D w(D D a 2)A D a 2 wremainder u2DIVUB 2 D w(D D a 1)A D a 1 wremainder u3DIV 2 D w(D D a 2)A D a 2 wremainder u2DIVB 2 D w(D D a 1)A D a 1 wremainder u3ANDANDB 2 D wD and A 0 0ANDANDB 3 D wB and A 0 0ORORB 2 D wD or A 0 0XORXORB 2 D wD (excl or) A 0 0LDLDB 2 D wASTSTB 2 A wDLDBSE 2 D wA D a 1 wSIGN(A) 3 4LDBZE 2 D wA D a 1 w0 3 4PUSH 1 SP wSP b2 (SP) wAPOP 1 A w(SP) SP wSP a 2PUSHF 0 SP wSP b2 (SP) wPSW 0 0 0 0 0 0PSW w0000H I w0POPF 0 PSW w(SP) SP wSP a 2 I wSJMP 1 PC wPC a 11-bit offset 5LJMP 1 PC wPC a 16-bit offset 5BR (indirect) 1 PC w(A)SCALL 1 SP wSP b2 (SP) wPC 5PC wPC a 11-bit offsetLCALL 1 SP wSP b2 (SP) wPC 5PC wPC a 16-bit offsetRET 0 PC w(SP) SP wSP a 2J (conditional) 1 PC wPC a 8-bit offset (if taken) 5JC 1 Jump if C e 1 5JNC 1 Jump if C e 0 5JE 1 Jump if Z e 1 5Figure 2-5 Instruction SummaryNOTES1 IfthemnemonicendsinB abyteoperationisperformed otherwiseawordoperationisdone OperandsD B andAmust conformtothealignment rulesfor therequiredoperandtype DandBarelocationsintheregister file Acanbelocatedanywhereinmemory2DDa2areconsecutiveWORDSinmemoryDisDOUBLE-WORDaligned3DDa1areconsecutiveBYTESinmemoryDisWORDaligned4Changesabytetoaword5Offsetisa2scomplementnumber5AP-248MnemonicOper-Operation (Note 1)FlagsNotesands Z N C V VT STJNE 1 Jump if Z e 0 5JGE 1 Jump if N e 0 5JLT 1 Jump if N e 1 5JGT 1 Jump if N e 0 and Z e 0 5JLE 1 Jump if N e 1 or Z e 1 5JH 1 Jump if C e 1 and Z e 0 5JNH 1 Jump if C e 0 or Z e 1 5JV 1 Jump if V e 1 5JNV 1 Jump if V e 0 5JVT 1 Jump if VT e 1 Clear VT 05JNVT 1 Jump if VT e 0 Clear VT 05JST 1 Jump if ST e 1 5JNST 1 Jump if ST e 0 5JBS 3 Jump if Specified Bit e 1 5 6JBC 3 Jump if Specified Bit e 0 5 6DJNZ 1 D wD b1 if Di0 thenPC wPC a 8-bit offset 5DECDECB 1 D wD b1 u NEGNEGB 1 D w0 bD u INCINCB 1 D wD a 1 u EXT 1 D wD D a 2 wSign (D) 0 0 2EXTB 1 D wD D a 1 wSign (D) 0 0 3NOTNOTB 1 D wLogical Not (D) 0 0CLRCLRB 1 D w0 1 0 0 0SHLSHLBSHLL 2 C wmsbIsb w0 u7SHRSHRBSHRL 2 0 xmsbIsb xC0 7SHRASHRABSHRAL 2 msb xmsbIsb xC0 7SETC 0 C w1 1 CLRC 0 C w0 0 CLRVT 0 VT w0 0 RST 0 PC w2080H 0 0 0 0 0 0 8DI 0 Disable All Interrupts (I w0)EI 0 Enable All Interrupts (I w1)NOP 0 PC wPC a 1SKIP 0 PC wPC a 2NORML 2 Left Shift Till msb e 1 D wshift count 07TRAP 0 SP wSP b2 (SP) wPCPC w(2010H) 9Figure 2-5 Instruction Summary (Continued)NOTES1 IfthemnemonicendsinB abyteoperationisperformed otherwiseawordoperationisdone OperandsD B andAmust conformtothealignment rulesfor therequiredoperandtype DandBarelocationsintheregister file Acanbelocatedanywhereinmemory5Offsetisa2scomplementnumber6Specifiedbitisoneofthe2048bitsintheregisterfile7TheL(Long)suffixindicatesdouble-wordoperation8 InitiatesaReset by pullingRESETlow Softwareshouldre-initializeall thenecessary registerswithcodestartingat2080H9Theassemblerwill notacceptthismnemonic6AP-248Oneopeiandof most of theinstiuctions canbeusedwithany one of six addiessing modes. These modesincieasethefIexibiIityandoveiaII executionspeedofthe 8096. The addiessing modes aie: iegistei-diiect, im-mediate, indiiect, indiiect with auto-inciement, andIongandshoitindexed.Thefastestinstiuctionexecutionisgainedbyusingei-theiiegisteidiiectoiimmediateaddiessing. Registei-diiect addiessing is simiIai to noimaI diiect addiessing,exceptthatonIyaddiessesintheiegisteifiIeoiSFRscanbeaddiessed.TheindexedmodeisusedtodiiectIyaddiess the iemaindei of the 64K addiess space. Imme-diateaddiessingopeiatesaswouIdbeexpected, usingthedatafoIIowingtheopcodeastheopeiand.Both of the indiiect addiessing modes use the vaIue in awoid iegistei as the addiess of the opeiand. If the indi-iect auto-inciement mode is used then the woid iegisteiis inciemented by one aftei a byte access oi by two afteiawoidaccess. ThismodeispaiticuIaiIyusefuIfoiac-cessingIookuptabIes.Access to any of the Iocations in the 64K addiess spacecanbeobtainedbyusingtheIongindexedaddiessingmode. Inthis modea16-bit 2s compIement vaIueisaddedtothecontents of awoidiegistei tofoimtheaddiess of the opeiand. By using the zeio iegistei as theindex, ASM96(theassembIei)canacceptdiiect ad-diessingtoanyIocation.ThezeioiegisteiisIocatedat0000H and aIways has a vaIue of zeio. A shoit indexedmode is aIso avaiIabIe to save some time and code. Thismode uses an 8-bit 2s compIement numbei as the offsetinsteadofa16-bitnumbei.222 ASSEMBLYLANGUAGEThe muItipIe addiessing modes of the 8096 make it easyto piogiam in assembIy Ianguage and piovide an exceI-IentinteifacetohighIeveI Ianguages. Theinstiuctionsacceptedbythe assembIei consist of mnemonics foI-Iowedbyeitheiaddiessesoidata. AIist of themne-monics andtheii functions aie showninFiguie 2-5.The addiesses oi data aie givenindiffeient foimatsdependingontheaddiessingmode. ThesemodesandfoimatsaieshowninFiguie2-6.AdditionaI infoimationon8096assembIyIanguageisavaiIabIe in the MCS-96 Macio AssembIei UseisOuide,IistedinthebibIiogiaphy.270061B3Figure 2-6 Instruction Format7AP-2482700614Figure 2-7 Interrupt Sources223 INTERRUPTSThefIexibiIityoftheinstiuctionsetiscaiiiedthioughintotheinteiiuptsystem. Theieaie20diffeientintei-iupt souices that can be used on the 8096. The 20souices vectoi thiough 8 Iocations oi inteiiupt vectois.ThevectoinamesandtheiisouicesaieshowninFig-uie2-7, withtheiiIocationsIistedinFiguie2-8. Con-tioI oftheinteiiuptsishandIedthioughtheInteiiuptPending Registei (INT-PFNDINO), the InteiiuptMask Registei (INT-MASK), andthe I bit inthePSW (PSW.9). Figuie 2-9 shows a bIock diagiam of theinteiiupt stiuctuie. The INT-PFNDINO iegisteicontainsbitswhichgetsetbyhaidwaiewhenanintei-iuptoccuis. If theinteiiuptmaskiegisteibitfoithatsouiceisa1andPSW.9e1,avectoiwiIIbetakentotheaddiessIistedintheinteiiuptvectoitabIefoithatVectorSourceLocationPriority(High (LowByte) Byte)Software 2011H 2010H Not ApplicableExtint 200FH 200EH 7 (Highest)Serial Port 200DH 200CH 6Software Timers 200BH 200AH 5HSI0 2009H 2008H 4High Speed 2007H 2006H 3OutputsHSI Data 2005H 2004H 2AvailableAD Conversion 2003H 2002H 1CompleteTimer Overflow 2001H 2000H 0 (Lowest)Figure 2-8 Interrupt Vectors and Priorities8AP-248souice. When the vectoi is taken the INT-PFNDINObitiscIeaied.IfmoiethanonebitissetintheINT-PFNDINOiegistei withthecoiiespondingbit set inthe INT-MASK iegistei, the Inteiiupt with the high-estpiioiityshowninFiguie2-8wiIIbeexecuted.The softwaie can make the haidwaie inteiiupts woik inaImostanyfashiondesiiedbyhavingeachioutineiunwithitsownsetupintheINT-MASKiegistei. ThiswiIIbecIeaiIyseenintheexampIesinsection4whichchange the piioiity of the vectois in softwaie. The2700615Figure 2-9 Interrupt Structure Block Diagram9AP-24815 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00Z N V VT CI ST INT

MASKWHEREZisthezeroflagItissetwhentheresultofanoperationiszeroNisthenegativeflagItissettothealgebraicallycorrectsignoftheresultregardlessofoverflowsVistheoverflowflagItissetifanoverflowoccursVTistheoverflowtrapflagItissetwhentheVTflagissetandclearedbyJVTJNVTorCLRVTCisthecarryflagItissetifacarrywasgeneratedbytheprioroperationIistheglobal interruptenablebitSTisthestickybitItissetduringarightshiftifaonewasshiftedintoandthenoutofthecarryflagINT

MASKistheinterruptmaskregisterandcontainsbitswhichindividuallyenablethe8interruptvectorsFigure 2-10 The PSW RegisterPSW(showninFiguie2-10), stoiestheINT-MASKiegisteiinitsIoweibytesothatthemaskiegisteicanbepushedandpoppedaIongwiththemachinestatuswhen moving in and out of ioutines. The action ofpushingfIags cIeais thePSWwhichincIudes PSW.9,theinteiiuptenabIebit. Theiefoie, afteiaPUSHFin-stiuction inteiiupts aie disabIed. In most cases an intei-iupt seivice ioutine wiII have the basic stiuctuie shownbeIow.INT VECTORPUSHFLDB INT MASK xxxxxxxxBEI-- Insert service routine here-POPFRETThePUSHFinstiuctionsavesthePSWincIudingtheoIdINT-MASKiegistei.ThePSW,incIudingthein-teiiupt enabIe bit aie Ieft cIeaied. If some inteiiuptsneedtobeenabIedwhiIetheseiviceioutineiuns, theINT-MASKis Ioadedwitha newvaIue andintei-iupts aie gIobaIIy enabIedbefoie the seivice ioutinecontinues. At the end of the seivice ioutine a POPF in-stiuctionisexecutedtoiestoietheoIdPSW.TheRFTinstiuctionisexecutedandthecodeietuinstothede-siiedIocation.AIthoughthePOPFinstiuctioncanen-abIe the inteiiupts the next instiuction wiII aIways exe-cute. This pievents unnecessaiy buiIding of the stack byensuiingthattheRFTaIwaysexecutesbefoieanotheiinteiiuptvectoiistaken.23 On-Chip IO SectionAIIoftheon-chipI/Ofeatuiesofthe8096canbeac-cessedthioughthespeciaIfunctioniegisteis,asshowninFiguie2-3. Theadvantageofusingiegistei-mappedI/O is that these iegisteis can be used as the souices oidestinationsofCPUopeiations.TheieaiesevenmajoiI/Ofunctions. Fachone of these wiII be consideiedwithasectionofcodetoexempIifyitsusage. ThefiistsectioncoveiedwiII betheHighSpeedI/O, (HSIO),subsystem.ThissectionincIudestheHighSpeedInput(HSI) unit, HighSpeedOutput (HSO) unit, andtheTimei/Counteisection.231 TIMERCOUNTERSThe8096has twotimebases, Timei 1andTimei 2.Timei1isa16-bit fieeiunningtimeiwhichisincie-mentedeveiy8statetimes.(Astatetimeis3osciIIatoipeiiods,oi0.25miciosecondswitha12MHzciystaI.)10AP-2482700616Pulsemeasurementwith20msecresolutionInputtransitionstriggertherecordingofthereferenceTimer(16-bit)andtriggeredinput(s)(4-bit)Figure 2-11 HSI Unit Block DiagramItsvaIuecanbeieadatanytimeandusedasaiefei-ence foi boththe HSI sectionandthe HSOsection.Timei1cancauseaninteiiuptwhenitoveifIows,andcannot be modifiedoi stoppedwithout iesetting theentiiechip. Timei2isieaIIyaneventcounteisinceituses an exteinaI cIock souice. Like Timei 1, it is 16-bitswide, canbeieadat anytime, canbeusedwiththeHSOsection, andcangeneiate aninteiiupt whenitoveifIows. ContioI ofTimei2isIimitedtoinciement-ing it and iesetting it. Specific vaIues can not be wiittentoit.AIthough the 8096 has onIy two timeis, the timei fIexi-biIityisequaItoaunitwithmanytimeisthankstotheHSIOunit. TheHSIenabIesonetomeasuietimesofexteinaI eventsonuptofouiIinesusingTimei1asatimei base. The HSOunit canscheduIe andexecuteinteinaI eventsanduptosixexteinaI eventsbasedonthevaIuesineitheiTimei1oiTimei2.The8096aIsoincIudes sepaiate, dedicatedtimeis foi the baudiategeneiatoiandwatchdogtimei.232 HSIThe HSI unit canbe thought of as a message takeiwhich iecoids the Iine which had an event and the timeatwhichtheeventoccuiied. FouitypesofeventscantiiggeitheHSIunit, as shownintheHSIbIockdia-giaminFiguie2-11. TheHSIunitcanmeasuiepuIsewidths and iecoid times of events with a 22700617Whereeach2-bitmodecontrol fielddefinesoneof4possiblemodes00 8positivetransitions01 Eachpositivetransition10 Eachnegativetransition11 Everytransition(positiveandnegative)Figure 2-12 HSI Mode Register11AP-248miciosecond iesoIution. It can Iook foi one of fouieventsoneachof fouiIinessimuItaneousIy, basedonthe infoimationinthe HSI Mode iegistei, showninFiguie2-12. TheinfoimationisthenstoiedinasevenIeveI FIFO foi Iatei ietiievaI. Whenevei the FIFO con-tains infoimation, the eaiIiest entiy is pIacedinthehoIdingiegistei.WhenthehoIdingiegisteiisiead,thenextvaIidpieceofinfoimationisIoadedintoit. Intei-iuptscanbegeneiatedbytheHSIunitatthetimethehoIdingiegisteiisIoadedoiwhentheFIFOhassixoimoieentiies.233 HSOJustastheHSIcanbethoughtofasamessagetakei,the HSOcanbe thought of as amessage sendei. Attimesdeteiminedbythesoftwaie,theHSOsendsmes-2700618Figure 2-13 HSO Command Register2700619Figure 2-14 HSO Block Diagram12AP-248sages to vaiious devices to have them tuin on, tuin off,staitpiocessing, oiieset. Sincethepiogiammedtimescanbe iefeiencedtoeithei Timei 1oi Timei 2, theHSOmakesthetwotimeisIookIikemany.Foiexam-pIe, if seveiaI events have to occui at specific times, theHSOunit canscheduIe aII of the events basedonasingIetimei.Theeventsthatcan be scheduIed to occuiandthe foimat of the commandwiittentothe HSOCommandiegisteiaieshowninFiguie2-13.ThesoftwaietimeisIistedinthefiguieaieactuaIIy4softwaiefIagsinI/OStatusRegistei1(IOS1). ThesefIagscanbeset, andoptionaIIycauseaninteiiupt, atanytimebasedonTimei1oiTimei2. Inmostcasesthese timeis aie used to tiiggei inteiiupt ioutines whichmust occui at ieguIai inteivaIs. AmuItitaskpiocesscaneasiIybesetupusingthesoftwaietimeis.ACAM(Content AddiessabIe Memoiy) fiIe is themaincomponent of the HSO. This fiIe stoies uptoeight events whichaiependingtooccui. Fveiystatetime one Iocationof the CAMis compaiedwiththetwo timeis. Aftei 8 state times, (two micioseconds witha12MHzcIock), theentiieCAMhasbeenseaichedfoitimematches.IfamatchoccuisthespecifiedeventwiIIbetiiggeiedandthatIocationoftheCAMwiIIbemade avaiIabIe foi anothei pending event. A bIock dia-giamoftheHSOunitisshowninFiguie2-14.234 Serial PortContioIIingadevicefiomaiemoteIocationisasimpIetaskthatfiequentIyiequiiesadditionaI haidwaiewithmany piocessois. The 8096 has an on-chip seiiaI poit toieduce the totaI numbei of chips iequiied in the system.27006110NOTETIandRIareclearedwhenSP

CONisreadFigure 2-15 Serial Port ControlStatus Register13AP-248TheseiiaIpoitissimiIaitothatontheMCS-51piod-uct Iine. It has onesynchionous andthieeasynchio-nousmodes. Intheasynchionousmodesbaudiatesofupto187.5Kbaudcanbeused, whiIeinthesynchio-nous modeiates upto1.5MbaudaieavaiIabIe. ThechiphasabaudiategeneiatoiwhichisindependentofTimei1andTimei2,sousingtheseiiaIpoitdoesnottakeawayanyoftheHSI, HSOoitimeifIexibiIityoifunctionaIity.ContioI of the seiiaI poit is piovided thiough theSPCON/SPSTAT (SeiiaI Poit CONtioI/SeiiaI PoitSTATus)iegistei. Thisiegistei, showninFiguie2-15,has some bits which aie iead onIy and otheis which aiewiite onIy. AIthoughthe functionaIityof the poit issimiIaitothat of the8051, thenamesof someof themodesandcontioIbitsaiediffeient.Thewayinwhichthe poit is used fioma softwaie standpoint is aIsosIightIy diffeient since RI and TI aie cIeaied aftei eachieadoftheiegistei.The foui modes of the seiiaI poit aie iefeiiedtoasmodes0,1,2and3.Mode0isthesynchionousmode,andiscommonIyusedtointeifacetoshiftiegisteisfoiI/Oexpansion. Inthismodethepoit outputsapuIsetiainontheTXDpinandeitheitiansmitsoiieceivesdataontheRXDpin. Mode1is thestandaidasyn-chionousmode,8bitspIusastopandstaitbitaiesentoi ieceived. Modes 2 and 3 handIe 9 bits pIus a stop andstait bit. The diffeience betweenthe two is, that inMode2theseiiaI poit inteiiupt wiII not beactivatedunIesstheninthdatabitisaone,inMode3theintei-iupt is activated whenevei a byte is ieceived. These twomodes aie commonIy used foi inteipiocessoi communi-cation.UsingXTAL1Mode0BaudRateeXTAL1frequency4(Ba1)Bi0OthersBaudRateeXTAL1frequency64(Ba1)UsingT2CLKMode0BaudRateeT2CLKfrequencyB Bi0OthersBaudRateeT2CLKfrequency16B Bi0NotethatBcannotequal 0exceptwhenusingXTAL1inotherthanmode0Figure 2-16 Baud Rate FormulasBaudiatesfoiaIIofthemodesaiecontioIIedthioughthe BaudRate iegistei. This is a byte wide iegisteiwhichisIoadedsequentiaIIywithtwobytes,andintei-naIIystoiesthevaIueasawoid. TheIeast significantbyteisIoadedtotheiegisteifoIIowedbythemostsig-nificant.ThemostsignificantbitofthebaudvaIuede-teimines the cIock souice foi the baud iate geneiatoi. Ifthe bit is a one, the XTAL1 pin is used as the souice, ifit is a zeio, the T2CLKpinis used. The foimuIasshown in Figuie 2-16 can be used to caIcuIate the baudiates. ThevaiiabIeB is usedtoiepiesent theIeastsignificant 15 bits of the vaIue Ioaded into the baud iateiegistei.ThebaudiateiegisteivaIuesfoicommonbaudiatesaie showninFiguie 2-17. These vaIues canbe usedwhenXTAL1isseIectedasthecIocksouicefoiseiiaImodes othei thanMode 0. The peicentage deviationfiomtheoieticaIisIistedtoheIp assess the ieIiabiIity ofagivensetup. Inmost casesaseiiaI IinkwiII woikiftheieisIessthana2.5%diffeiencebetweenthebaudiatesofthetwosystems.Thisisbasedontheassump-tionthat10bitsaietiansmittedpeifiameandtheIastbitofthefiamemustbevaIidfoiatIeastsix-eightsofthe bit time. If the two systems deviate fiom theoieticaIby1.25%inopposite diiections the maximumtoIei-anceof2.5%wiIIbeieached.Theiefoie,cautionmustbe used when the baud iate deviation appioaches1.25%fiomtheoieticaI.NotethatanXTAL1fiequen-cyof 11.0592MHzcanbeusedwiththetabIevaIuesfoi 11 MHz to piovide baud iates that have 0.0 peicentdeviationfiomtheoieticaI. InmostappIications, how-evei, the accuiacyavaiIabIe whenusingan11MHzinputfiequencyissufficient.SeiiaI poit Mode 1 is the easiest mode to use as theie isIittIetowoiiyabout except initiaIizationandIoadingandunIoadingSBUF,theSeiiaIpoitBUFfei.IfpaiityisenabIed, (i.e., PFNe1), 7bitspIusevenpaiityaieusedinsteadof 8databits. The paiitycaIcuIationisdoneinhaidwaiefoievenpaiity. Modes2and3aiesimiIai to Mode 1, except that the ninth bit needs to becontioIIedandiead. It is aIsonot possibIe toenabIepaiity in Mode 2. When paiity is enabIed in Mode 3 theninth bit becomes the paiity bit. If paiity is not enabIed,(i.e., PFNe0), theTB8bitcontioIsthestateof theninth tiansmitted bit. This bit must be set piioi to eachtiansmission. Onieception, if PFNe0, theRB8bitindicatesthestateoftheninthieceivedbit.IfpaiityisenabIed, (i.e., PFNe1), thesamebit iscaIIedRPF(ReceivePaiityFiioi),andisusedtoindicateapaiityeiioi.14AP-248XTAL1 Frequencye120 MHzBaud Rate Baud Register Value Percent Error192K 8009Ha2409600 8013Ha2404800 8026Hb0162400 804DHb0161200 809BHb016300 8270H 000XTAL1 Frequencye110 MHz192K 8008Ha0549600 8011Ha0544800 8023Ha0542400 8047Ha0541200 808EHb016300 823CHa001XTAL1 Frequencye100 MHz192K 8007Hb1709600 800FHb1704800 8020Ha1382400 8040Hb0161200 8081Hb016300 8208Ha003Figure 2-17 Baud Rate Values for 10 11 12 MHzThesoftwaieusedtocommunicatebetweenpiocessoisis simpIified by making use of Modes 2 and 3. In a basicpiotocoI the ninth bit is caIIed the addiess bit. If it is sethighthentheinfoimationinthatbyteiseitheithead-diess of oneof thepiocessois ontheIink, oiacom-mand foi aII the piocessois. If the bit is a zeio, the bytecontains infoimationfoi the piocessoi oi piocessoispieviousIyaddiessed. InstandbymodeaII piocessoiswait inMode 2 foi a byte withthe addiess bit set.When they ieceive that byte, the softwaie deteimines ifthenextmessageisfoithem. Thepiocessoithatistoieceivethemessageswitches toMode3andieceivestheinfoimation.Sincethisinfoimationissentwiththeninth bit set to zeio, none of the piocessois set to Mode2wiIIbeinteiiupted. ByusingthisschemetheoveiaIICPUtimeiequiiedfoitheseiiaIpoitisminimized.AtypicaI connectiondiagiamfoi themuIti-piocessoimode is shown in Figuie 2-18. This type of communica-toncanbeusedtoconnect peiipheiaIs toadesktopcomputei, the axis of a muIti-axis machine, oi any oth-eigioupofmiciocontioIIeisjointIypeifoimingatask.15AP-24827006111Figure 2-18 Multiprocessor CommunicationMode0, thesynchionous mode, is typicaIIyusedfoiinteifacing to shift iegisteis foi I/Oexpansion. ThesoftwaietocontioI thismodeinvoIvestheRFN(Re-ceiveiFNabIe)bit,thecIeaiingoftheRIbit,andwiit-ing to SBUF. To tiansmit to a shift iegistei, RFN is settozeioandSBUFisIoadedwiththeinfoimation.Theinfoimation wiII be sent and then the TI fIag wiII be set.Theieaietwowaystocauseaieceptiontobegin.Thefiist isbycausingaiisingedgetooccuiontheRFNbit, thesecondis bycIeaiingRI withRFNe1. Ineithei case, RIis set againwhentheieceivedbyteisavaiIabIeinSBUF.235 AtoDCONVERTERAnaIoginputs aiefiequentIyiequiiedinamiciocon-tioIIeiappIication. The8097hasa10-bitAtoDcon-veitei that can use any one of eight input channeIs. Theconveisions aiedoneusingthesuccessiveappioxima-tionmethod,andiequiie168statetimes(42miciosec-ondswitha12MHzcIock.)TheiesuItsaieguaianteedmonotonicbydesignoftheconveitei. ThismeansthatiftheanaIoginputvoItagechanges,evensIightIy,thedigitaIvaIuewiIIeitheistaythesameoichangeinthesamediiectionastheanaIoginput. When doing piocess contioI aIgoiithms, it is fie-quentIy the changes in inputs that aie iequiied, not theabsoIuteaccuiacyofthevaIue.Foithisieason,eveniftheabsoIuteaccuiacyofa10-bitconveiteiisthesameas that of an 8-bit conveitei, the 10-bit monotonic con-veiteiismuchmoieusefuI.Since most of the anaIog inputs which aie monitoied byamiciocontioIIeichangeveiysIowIyieIativetothe42miciosecondconveisiontime, itisacceptabIetouseacapacitivefiIteioneachinputinsteadofasampIeandhoId. The8097doesnot haveaninteinaI sampIeandhoId, soitisnecessaiytoensuiethattheinputsignaIdoesnotchangeduiingtheconveisiontime.Theinputto the A/Dmust be betweenANONDandVRFF.ANONDmust bewithinafewmiIIivoItsof VSSandVRFFmustbewithinafewtenthsofavoItofVCC.UsingtheAtoDconveiteionthe8097canbeaveiyIow softwaie oveihead task because of the inteiiupt andHSOunitstiuctuie. TheAtoDcanbestaitedbytheHSO unit at a pieset time. When the conveision is com-pIeteit is possibIetogeneiateaninteiiupt. ByusingthesefeatuiestheAtoDcanbeiunundeicompIeteinteiiupt contioI. The Ato Dcan aIso be diiectIy16AP-248ADCommandRegister27006112ADResultRegister27006113Figure 2-19 A to D ResultCommand RegistercontioIIedbysoftwaiefIags whichaieIocatedintheAD-RFSULT/AD-COMMAND Registei, showninFiguie2-19.236 PWMREGISTERAnaIogoutputsaiejustasimpoitantasanaIoginputswhenconnectingtoapieceofequipment. TiuedigitaItoanaIogconveiteisaiedifficuIttomakeonamicio-piocessoi because of aII of the digitaI noise andthenecessityof piovidinganonchip, ieIativeIyhighcui-ient, iaiI to iaiI diivei. They aIso take up a faii amountof siIiconaieawhichcanbebetteiusedfoiotheifea-tuies. The A to D conveitei does use a D to A, but thecuiientsinvoIvedaieveiysmaII.FoimanyappIicationsananaIogoutputsignaI canbeiepIacedbyaPuIseWidthModuIated(PWM) signaI.This signaI canbe easiIygeneiatedinhaidwaie, andtakes up much Iess siIicon aiea than a tiue D to A. ThesignaI is avaiiabIedutycycIe, fixedfiequencywave-foimthat canbeintegiatedtopiovideanappioxima-tiontoananaIogoutput. Thefiequencyis fixedat apeiiodof 64miciosecondsfoia12MHzcIockspeed.ContioIIingthePWMsimpIyiequiieswiitingthede-siiedduty cycIe vaIue (an8-bit vaIue) to the PWMRegistei. SometypicaI output wavefoims that canbegeneiatedaieshowninFiguie2-20.ConveitingthePWMsignaItoananaIogsignaIvaiiesindifficuIty, dependingupontheiequiiements of thesystem. Some systems, such as motois oi switchingpowei suppIies actuaIIyiequiieaPWMsignaI, not atiueanaIogone. Foimanyotheicasesit isnecessaiyonIy to ampIify the signaI so that it switches iaiI-to-iaiI,andthenfiIteiit. SwitchingiaiI-to-iaiI meansthattheoutputoftheampIifieiwiII beaiefeiencevaIuewhenthe input is a IogicaI one, and the output wiII17AP-248bezeiowhentheinputisaIogicaIzeio.ThefiIteicanbeasimpIeRCnetwoikoianactivefiItei. If aIaigeamount of cuiient isneededabuffeiisaIsoiequiied.FoiIowoutputcuiients, (Iessthan100micioampsoiso),theciicuitshowninFiguie2-21canbeused.TheRCnetwoikdeteimineshowquiet theoutput is,but the quietei the output, the sIowei it canchange.ThedesignofhighaccuiacyvoItagefoIIoweisandac-tivefiIteisisbeyondthescopeof thispapei, howeveimanybooksonthesubjectaieavaiIabIe.27006114Figure 2-20 PWM Output Waveforms27006115This resistor limits Rise Time to reduce spikes and high frequency noiseFigure 2-21 PWM to Analog Conversion Circuitry18AP-24830BASICSOFTWAREEXAMPLESThe exampIes in this section show how to use each I/OfeatuieindividuaIIy. FxampIesofusingmoiethanonefeatuieatatimeaiedesciibedinsection4. AII oftheexampIesinthisap-noteaiesetuptobeusedasIisted.If iunthioughASM96theywiII IoadandiunonanSBF-96. In oidei to insuie that the piogiams woik, thestack pointei is initiaIized at the beginning of each pio-giam.IfthepiogiamsaiegoingtobeusedasmoduIesof othei piogiams, the stack pointei initiaIizationshouIdonIybeusedatthebeginningofthemainpio-giam.To avoid iepetitive decIaiations the incIude fiIe DF-MO96.INC, showninListing3-1, is used. ASM-96wiII inseit this fiIe into the code fiIe whenevei the diiec-tive INCLUDF DFMO96.INC is used. The fiIe con-tainsthedefinitionsfoitheSFRsandotheivaiiabIes.TheincIudestatementhasbeenpIacedinaIIoftheex-ampIes. It shouId be noted that some of the Iab-eIs in this fiIe aie diffeient fiomthose in the fiIe8096.INCthatispiovidedintheASM-96package.31 Using the 8096s ProcessingSection311 TABLEINTERPOLATIONAgoodwayof incieasingspeedfoi manypiocessingtasks is to use tabIe Iookup with inteipoIation. This caneIiminate Iengthy caIcuIations in many aIgoiithms. Fie-quentIyitisusedinpiogiamsthatgeneiatesinewave-foims, useexponents incaIcuIations, oi iequiiesomenon-Iineai function of a given input vaiiabIe. TabIeIookupcanaIsobeusedwithoutinteipoIationtodetei-mine the output state of I/O devices foi a given state ofaset of input devices. The pioceduie is aIsoagoodexampIeof 8096codeasitusesmanyof thesoftwaiefeatuies. Twoways of makingaIookuptabIeaiede-sciibed, one way uses moie caIcuIation time, the secondwayusesmoietabIespace.27006116Listing 3-1 Include File DEMO96INC19AP-248InbothmethodsthepioceduieissimiIai. VaIuesof afunction aie stoied in memoiy foi specific input vaIues.To compute the output function foi an input that is notIisted, a Iineai appioximation is made based on theneaiest inputs and neaiest outputs. As an exampIe, con-sideithetabIebeIow.If the input vaIue was one of those IistedthentheiewouIdbenopiobIem. UnfoitunateIytheieaI woiIdisneveisokind. TheinputnumbeiwiIIpiobabIybe259oi something simiIai. If this is the case Iineai inteipoIa-tionwouIdpiovideaieasonabIeiesuIt.ThefoimuIais:DeltaOuteUpperOutput-LowerOutputUpperInput-LowerInput(ActualInput-LowerInput)Actual OutputeLowerOutputaDeltaOutForthevalueof259thesolutionisDeltaOute900-400300-200(259-200)e50010059e5 59e295Actual Outpute400a295e695TomaketheaIgoiithmeasiei,(andtheiefoiefastei),itis appiopiiatetoIimit theiangeandaccuiacyof thefunction to onIy what is needed. It is aIso advantageousto make the input step (Uppei Input-Lowei Input)equaI toapoweiof 2. ThisaIIowsthesubstitutionofmuItipIeiightshiftsfoiadivideopeiation,thusspeed-ing up thioughput. The 8096 aIIows muItipIe aiithmeticiight shifts withasingIeinstiuctionpiovidingaveiyfastdivideifthedivisoiisapoweioftwo.Foi the puipose of an exampIe, a piogiam with a 12-bitoutput andan8-bit input hasbeenwiitten. Aninputstep of 16 (24) was seIected. To covei the input iange17woidsaieneeded,255/16a1woidtohandIevaI-uesintheIast15bytesofinputiange. AIthoughonIy12bitsaieiequiiedfoitheoutput,the16-bitaichitec-tuieoffeisnopenaItyfoiusing16insteadof12bits.Thepiogiamfoi this exampIe, showninListing3-2,usesthedefinitionsandequatesfiomListing3-1, onIytheadditionaIequatesanddefinitionsaieshowninthecode.Input Value Relative Table Address Table Value100 0001H 100200 0002H 400300 0003H 900400 0004H 160027006117Listing 3-2 ASM-96 Code for Table Lookup Routine 120AP-24827006118Listing 3-2 ASM-96 Code for Table Lookup Routine 1 (Continued)If the function is known at the time of wiiting the soft-waie it is aIso possibIe to caIcuIate in advance thechange in the output function foi a given change in theinput. Thismethodcansaveadivideandafewotheiinstiuctionsat theexpenseof doubIingthesizeof theIookuptabIe. TheieaiemanyappIicationswheietimeisciiticaI andcodespaceisoveiIyabundant. Inthesecases the code inListing 3-3wiII woiktothe samespecificationsasthepieviousexampIe.27006119Listing 3-3 ASM-96 Code For Table Lookup Routine 221AP-24827006120Listing 3-3 ASM-96 Code for Table Lookup Routine 2 (Continued)By making use of the second Iookup tabIe, one woid ofRAMwassavedand16statetimes.InmostcasesthistimesavingswouIdnotmakemuchofadiffeience,butwhenpushingthepiocessoitotheIimit,miciosecondscanmakeoibieakadesign.312 PLM-96InteI piovideshighIeveI Ianguagesuppoitfoimostofits micio piocessois and miciocontioIIeis in the foim ofPL/M. SpecificaIIy, PL/Miefeis toa famiIyof Ian-guages, eachsimiIaiinsyntax, but speciaIizedfoithedevice foi which it geneiates code. The PL/M syntax issimiIai toPL/1, andis easytoIeain. PLM-96is theveisionof PL/Musedfoi the 8096. It is veiy codeefficient asit waswiittenspecificaIIyfoitheMCS-96famiIy. PLM-96 most cIoseIy iesembIes PLM-86, aI-though it has bit and I/O functions simiIai to PLM-51.One Iine of PL/M-code cantake the pIace of manyIines of assembIy code. This is advantageous to the pio-giammei, since code canusuaIIybe wiittenat a setnumbeiofIinespeihoui,sotheIessIinesofcodethatneed to be wiitten, the fastei the task can be compIeted.If thefiist exampIeof inteipoIationisconsideied, thePLM-96 code wouId be wiitten as shown in Listing 3-4.Notethatveision1.0ofPLM-96doesnotsuppoit32-bit iesuIts of 16 by 16 muItipIies, so the ASM-96 pioce-duie DMPY is used. Pioceduie DMPY, showninListing 3-5, must be assembIed and Iinked with thecompiIedPLM-96piogiamusingRL-96,theieIocatoiandIinkei.ThecommandIinetobeusedis:RL96PLMFX1.OBJ,DMPY.OBJ,PLM96.LIB&toPLMOUT.OBJROM(2080H-3FFFH)22AP-24827006121Listing 3-4 PLM-96 Code For Table Lookup Routine 127006122Listing 3-5 32-Bit Result Multiply Procedure For PLM-9623AP-248UsingPLM, codeiequiiesIessIines, ismuchfasteitowiite, andeasiei to maintain, but may take sIightIyIongei to iun. Foi this exampIe, the assembIy code gen-eiatedbythePLM-96compiIeitakes56.75miciosec-ondstoiuninsteadof30.75micioseconds.IfPLM-96peifoimedthe 32-bit iesuIt muItipIyinsteadof usingthe ASM-96ioutine the PLMcode wouIdtake 41.5micioseconds to iun. The actuaI code Iistings aieshowninAppendixA.32 Using the IO Section321 USINGTHEHSI UNITOneofthemostfiequentusesoftheHSIistomeasuiethe time between events. This can be used foi fiequencydeteimination in Iab instiuments, oi speed/acceIeiationinfoimation when connected to puIse type encodeis.ThecodeinListing3-6canbeusedtodeteiminethehighandIowtimes of the signaIs ontwoIines. ThiscodecanbeeasiIyexpandedto4IinesandcanaIsobemodifiedtowoikasaninteiiuptioutine.FiequentIyitisaIsodesiiedtokeeptiackofthenum-bei of events which have occuiied, as weII as how oftentheyaie occuiiing. Byusingasoftwaie countei thisfeatuiecanbeaddedtotheabovecode. Thiscodede-pendsonthesoftwaieiespondingtothechangeinIinestate befoie the Iine changes again. If this cannot beguaianteedthenitmaybenecessaiytouse2HSIIinesfoi each incoming Iine. In this case one HSI Iine wouIdIookfoifaIIingedges whiIetheotheiIooks foiiisingedges. The code in Listing 3-7 incIudes both the counteifeatuieandtheedgedetectfeatuie.TheusesfoithistypeofioutineaieaImostendIess.IninstiumentationitcanbeusedtodeteiminefiequencyoninputIines,oipeihapsbaudiatefoiaseIfadjustingseiiaI poit. Section 4.2 contains an exampIe of making asoftwaieseiiaI poitusingtheHSIunit. Inteifacingtosome foim of mechanicaIIy geneiated position infoima-tionisaveiyfiequentuseoftheHSI.TheappIicationsin this categoiy incIude motoi contioI, piecise position-ing(piint heads, diskdiives, etc.), enginecontioI and27006123Listing 3-6 Measuring Pulses Using The HSI Unit24AP-248tiansmissioncontioI. TheHSIunitisusedextensiveIyintheexampIeinsection4.3.322 USINGTHEHSOUNITAIthoughtheHSOhasmanyuses,thebestexampIeisthatofamuItipIePWMoutput. Thispiogiam, shownin Listing 3-8, is simpIe enough to be easiIy undeistood,yetitshowshowtousetheHSOfoiataskwhichcanbecompIex. Inoideifoithispiogiamtoopeiate, an-othei piogiam needs to set up the on and off time vaii-abIes foi eachIine. ThepiogiamaIsoiequiies that aHSOIinenot changesoquickIythat it changestwicebetweenconsecutive ieads of I/OStatus Registei 0,(IOS0).A veiy eye catching exampIe can be made by having thepiogiamoutput wavefoims that vaiyovei time. Thediivei ioutine in Listing 3-10 can be Iinked to the abovepiogiamtopiovide this function. Linking is accom-pIished using RL96, the ieIocatabIe Iinkei foi the 8096.Infoimation foi using RL96 can be found in theMCS-96 UtiIities Useis Ouide, Iisted in the bibIiogia-phy.InoideifoithepiogiamtoIink,theiegisteidec-27006124Listing 3-7 Enhanced HSI Pulse Measurement Routine25AP-24827006125Listing 3-8 Generating a PWM with the HSO26AP-248Iaiationsection(i.e.,thesectionbetweenRSFOandCSFO) inListing3-8must be changedtothat inListing3-9.The diivei ioutine simpIy changes the duty cycIe of thewavefoimandsets the secondHSOoutput toa fie-quencytwicethatof thefiistone. AsIightIydiffeientdiiveiioutinecouIdeasiIybethebasisfoiaswitchingpoweisuppIyoiavaiiabIefiequency/vaiiabIevoItagemotoidiivei.TheIistingofthe diivei ioutine is showninListing3-10.27006126Listing 3-9 Changes to Declarations for HSO Routine27006127Listing 3-10 Driver Module for HSO PWM Program27AP-24827006128Listing 3-10 Driver Module for HSO PWM Program (Continued)Sincethe8096needstokeeptiackofeventswhichof-teniepeatatsetinteivaIsitisconvenienttobeabIetohaveTimei2actasapiogiammabIemoduIocountei.Theie aie seveiaI ways of doingthis. The fiist is topiogiamthe HSOto ieset Timei 2 when Timei 2equaIsasetvaIue. AsoftwaietimeisettointeiiuptatTimei2equaIszeiocouIdbeusedtoieIoadtheCAM.This softwaie methodtakes uptwo Iocations intheCAM and does not synchionize Timei 2 to the exteinaIwoiId.TosynchionizeTimei2exteinaIIytheT2RST(Timei2ReSeT)pincanbeused.InthiswayTimei2wiIIgetiesetoneachiisingedgeofT2RST. Ifitisdesiiedtohave aninteiiupt geneiatedandtime iecoidedwhenTimei2getsieset,thesignaIfoiitsiesetcanbetakenfiomHSI.0insteadof T2RST. TheHSI.0pinhasitsowninteiiuptvectoiwhichfunctionsindependentIyoftheHSIunit.Anothei optionavaiIabIe is to use the HSI.1 pintocIockTimei2. ByusingthisappioachitispossibIetouse the HSI tomeasuie the peiiodof events ontheinput to Timei 2. If bothof the HSI pins aie usedinsteadoftheT2RSTandT2CLKpinstheHSIOunitcankeeptiackof speedandpositionof the iotatingdevicewithveiyIittIesoftwaieoveihead. Thistypeofsetup is ideaI foi a system Iike the one shown in Figuie3-1,andsimiIaitotheoneusedinsection4.3.In this system a sequence of events is iequiied based onthepositionof thegeaiwhichiepiesentsanypieceofiotating machineiy. Timei 2 hoIds the count of thenumbei of tooth edges passed since the index maik. Byusing HSI.1 as the input to Timei 2, insteadof T2CLK, itispossibIetodeteiminetoothcountandtimeinfoimationthioughthe HSI. Fiomthis infoimationinstantaneous veIocity and acceIeiation can be caIcuIat-ed. Having the toothedge count inTimei 2 means27006129Figure 3-1 Using the HSIO to Monitor Rotating Machinery28AP-248that theHSOunit canbeusedtoinitiatethedesiiedtasks at the appiopiiate tooth count. The inteiiupt iou-tine initiated by HSI.0 can be used to peifoim any soft-waie task iequiied eveiy ievoIution. In this system, theoveiheadwhichwouIdnoimaIIyiequiieextensivesoft-waie has beendone withthe haidwaie onthe 8096,thusmakingmoiesoftwaietimeavaiIabIefoicontioIpiogiams.323 USINGTHESERIALPORTINMODE1Mode1oftheseiiaIpoitsuppoitsthebasicasynchio-nous 8-bit piotocoI andis usedtointeiface tomostCRTsandpiinteis.TheexampIeinListing3-11showsasimpIeioutinewhichieceives achaiactei andthentiansmits the same chaiactei. The code is set up so thatminoimodificationscouIdmakeitiunonaninteiiuptbasis. NotethatitisnecessaiytosetupsomefIagsasinitiaI conditions to get the ioutine to iun piopeiIy. If itwasdesiiedtosend7bitsofdatapIuspaiityinsteadof8bitsofdatathePFNbitwouIdbesettoaone.Intei-piocessoi communication, as desciibed in section 2.3.4,can be set up by simpIy adding code to change RB8 andthe poit mode to the Iisting beIow. The haidwaieshowninFiguie3-2canbeusedtoconveit theIogicIeveI output of the 8096tog12oi 15voIt IeveIs toconnecttoa CRT. This ciicuit has been found to woikwithmost RS-232devices, aIthoughit does not con-foimto stiict RS-232 specifications. If tiue RS-232confoimance is iequiied then any standaid RS-232diiveicanbeused.27006130Listing 3-11 Using the Serial Port in Mode 129AP-24827006131Listing 3-11 Using the Serial Port in Mode 1 (Continued)27006132Figure 3-2 Serial Port Level Conversion30AP-248324 USINGTHEATODThe code in Listing 3-12 makes use of the softwaie fIagsto impIement a non-inteiiupt diiven ioutine whichscansAtoDchanneIs0thiough3andstoiesthemaswoids in RAM. An inteiiupt diiven ioutine is shown insection4.1. WhenusingtheAtoDitisimpoitanttoaIwaysieadthevaIueusingthebyteieadcommands,andtogivetheconveitei8statetimestostaitconveit-ingbefoieieadingthestatusbit.SincetheieisnosampIeandhoIdontheAtoDcon-veiteiitmaybedesiiabIetouseanRCfiIteioneachinput. A 100X iesistoi in seiies with a 0.22 uf capacitoitogioundhas beenusedsuccessfuIIyintheIab. Thisciicuit gives a time constant of aiound 22 miciosecondswhichshouIdbeIongenoughtogetiidofmostnoise,withoutoveiIysIowingtheAtoDiesponsetime.40 ADVANCEDSOFTWAREEXAMPLESUsingthe8096foiappIicationswhichconsist onIyofthe biief exampIes in the pievious section does notieaIIymake use of its fuII capabiIities. The foIIowingexampIes use some of the code bIocks fiom the pievioussectiontoshowhowseveiaI I/Ofeatuiescanbeusedtogethei to accompIish a piacticaI task. Thiee exampIeswiII be shown. The fiist is simpIy a combination of sev-eiaI of thesection3exampIesiunundeianinteiiuptsystem. Next, a softwaie seiiaI poit usingthe HSIOunitisdesciibed.TheconcIudingexampIeisoneofin-teifacing the HSI unit to an opticaI encodei to contioI amotoi.41 Simultaneous IO Routines underInterrupt ControlA foui channeI anaIog to PWM conveitei can easiIy bemadeusingthe8096.IntheexampIeinListing4ana-IogchanneIsaieieadand3PWMwavefoimsaiegen-eiatedonthe HSOIines andone onthe PWMpin.FachanaIogchanneIisusedtosetthedutycycIeofitsassociatedoutput pin. Theinteiiupt systemkeepsthewhoIepiogiamhumming, piovidingtimefoi aback-gioundtaskwhichissimpIya32bitsoftwaiecountei.Toshowwhichioutines aie executingandinwhich27006133Listing 3-12 Scanning the A to D Channels31AP-248oidei, Poit1outputpinsaieusedtoindicatethecui-ient statusof eachtask. TheactuaI codeIistingisin-cIudedinAppendixB.TheinitiaIizationsection,showninListing4-1a,cIeaisa few vaiiabIes and then Ioads the fiist set of on and offtimes totheHSOunit. Notethat 8statetimes mustbe waited between consecutive Ioads of the HSO. If thisis not done it is possibIe to oveiwiite the contents of theCAMhoIdingiegistei. AnA/Dinteiiuptisfoicedbysettingthebit intheInteiiupt Pendingiegistei. Thiscauses thefiist A/Dinteiiupt tooccui just aftei theInteiiupt Maskiegistei is set andinteiiupts aie en-abIed.Listing 4-1 Using Multiple IO Devices27006134Listing 4-1a Initializing the A to D to PWM Program32AP-24827006135Listing 4-1a Initializing the A to D to PWM program (Continued)27006136Listing 4-1b Interrupt Driven HSO Routine33AP-24827006137Listing 4-1c Interrupt Driven A to D RoutineTheHSOioutineshowninListing4-1bissIightIydif-feientthantheoneinsection3. AII of theHSOIinestuinonatthesametime,onIythetuin-off-timeisvai-ied between Iines. This action is what is most common-Iyiequiiedfoi muItipIePWMoutputs andsimpIifiesthesoftwaie. Acompaiisonis madebetweenTimei1andthenextHSOtuinontimeatthebeginningoftheioutine. If thenext tuinontimehaspassed, thentheon-times aieIoadedintotheCAM, otheiwisetheofftimesaieIoaded.Themaximumnumbei of events intheCAMat anygiventimeis7. ThisoccuiswhenthefiistIinetotuinoffdoesso, causingtheoff-timesfoiaIIoftheIinestobe Ioaded. Foi two of the Iines theie wiII be an offtime,an on-time, and the just Ioaded off-time. The othei Iine(the one that just tuined off) wiII have onIy the on-timeandthejustIoadedoff-time.A/DconveisionsaiepeifoimedbythecodeinListing4-1cabout eveiy60micioseconds, 42foitheconvei-sion, the iest foi oveihead. The A/D ioutine sets up theHSOand PWMon and off times. Since the A/Dhas a tenbit output, the most significant 8 bits aieioundedupoidownbasedontheIeastsignificanttwobits.42 Software Serial Port Using theHSIO UnitTheieaiemanysystemswhichiequiiemoiethanoneseiiaI poit, an exampIe is a system which must commu-nicate withothei computeis andhave anadditionaIpoit foi a IocaI consoIe. If the on-boaid UART is beingusedasanintei-piocessoiIink, theHSIOunit canbeusedtointeifacethe8096toanadditionaI asynchio-nousIine.Figuie4-1showsthefoimatofastandaid10-bitasyn-chionous fiame. The stait bit is used to synchionize theieceiveitothetiansmittei, at theIeadingedgeof theSTARTbittheieceiveimustsetupitstimingIogictosampIetheincomingIineinthecenteiofeachbit.FoI-Iowingthestait bit aietheeight databits whichaietiansmittedIeast significant bit fiist. TheSTOPbit isset tothe opposite state of the STARTbit toguai-34AP-24827006138Figure 4-1 10-bit Asynchronous Frameantee that the Ieading edge of the START bit wiII causea tiansition on the Iine, it aIso piovides foi a dead timeontheIinesothat theieceivei canmaintainits syn-chionization.TheiemaindeiofthissectionwiIIshowhowafuII-du-pIexasynchionous poit canbe buiIt fiomthe HSIOunit.Theieaiefouisectionstothiscode:1.Inteifaceioutines. Theseioutines piovideapioce-duiaI inteifacebetweentheinteiiuptdiivencoieofthesoftwaieseiiaIpoitandtheiemaindeioftheap-pIicationsoftwaie.2.InitiaIizationioutine. This ioutine is caIIedduiingthe initiaIization of the oveiaII system and sets up thevaiiousvaiiabIesusedbythesoftwaiepoit.3.Tiansmit ISR. This ioutine iuns as an ISR (inteiiuptseiviceioutine)iniesponsetoanHSOinteiiuptin-teiiupt.ItsfunctionistoseiiaIizethedatapassedtoitbytheinteifaceioutines.4.Receive ISRs. Theie aie twoISRs invoIvedintheieceivepiocess. OneofthemiunsiniesponsetoanHSIinteiiuptandisusedtosynchionizetheieceivepiocessattheIeadingedgeofthestaitbit. Thesec-ond ieceive ISR iuns in iesponse to an HSO geneiat-ed softwaie timei inteiiupt, this ioutine is scheduIedtoiunatthecenteiofeachbitandisusedtodeseii-aIizetheincomingdata.The ioutines shaie the set of vaiiabIes that aie shown inListing4-2.ThesevaiiabIesshouIdbeaccessedonIybythe ioutines whichmake upthe softwaie seiiaI poit.27006139Listing 4-2 Software Serial Port Declarations35AP-248The tabIe aIso shows the decIaiations foi the com-mands issued to the HSO unit. In this exampIe HSI.2 isusedfoiieceivedataandHSO.5is usedfoitiansmitdata, aIthoughothei HSI andHSOIines couIdhavebeenused.The inteiface ioutines aie shown in Listing 4-3. Data ispassedtothepoit bypushingtheeight-bit chaiacteiintothestackandcaIIingchar

out, whichwaits foianyin-piocesstiansmissiontocompIeteandstoiesthechaiacteiintothevaiiabIeserial

out. Asthedataisstoied the START and STOP bits aie added to the databits. TheioutinechariniscaIIedwhentheappIica-tionsoftwaieiequiiesachaiacteifiomthepoit. Thedatais ietuinedintheaxiegistei inconfoimancetoPLM96caIIingconventions. Theioutinecsts canbecaIIed to deteimine if a chaiactei is avaiIabIe at the poitbefoie caIIing char

in. (If no chaiactei is avaiIabIechar

inwiIIwaitindefiniteIy).TheinitiaIizationioutineisshowninListing4-4. Thisioutine is caIIed withthe iequiied baud iate in the27006140Listing 4-3 Software Serial Port Interface Routines27006141Listing 4-4 Software Serial Port Initialization Routine36AP-248stack,itcaIcuIatesthebittimefiomthebaudiateandstoiesitinthevaiiabIebaud

count inunitsof TIM-FR1 ticks. An HSO command is issued which wiII initi-atethetiansmitpiocessandthentheiemaindeiofthevaiiabIes owned by the poit aie initiaIized. The ioutineinit

receiveiscaIIedtosetuptheHSIunittoIookfoitheIeadingedgeoftheSTARTbit.The tiansmit piocess is shown in Listing 4-5. The HSOunit is usedto geneiate anoutput commandto thetiansmitpinoncepeibittime.Iftheserial

outiegis-teiiszeioaMARK(idIecondition) isoutput. If theserial

out iegistei contains data then the Ieast sig-nificantbitisoutputandtheiegisteishiftediightonepIace. The fiaming infoimation (STARTand STOPbits) aieappendedtotheactuaI databytheinteifaceioutines. Notethat thisioutinewiII beexecutedoncepei bit time whethei oi not data is being tiansmitted. ItwouIdbepossibIetousethisioutinefoiadditionaIIowiesoIutiontimingfunctionswithminimaIoveihead.TheieceivepiocessconsistsofaninitiaIizationioutineandtwointeiiupt seivice ioutines, hsi

isr andsoft-ware

timer

isr. The Iistings of these ioutines aieshowninListings4-6a,4-6b,and4-6ciespectiveIy.The27006142Listing 4-5 Software Serial Port Transmit ProcessListing 4-6 Receive Process27006143Listing 4-6a Software Serial Port Receive Initialization37AP-24827006144Listing 4-6b Software Serial Port Start Bit Detect27006145Listing 4-6c Software Serial Port Data Reception38AP-248staitisdetectedbythehsi

isrwhichscheduIesasoft-waie timei inteiiupt in one-haIf of a bit time. This fiistsampIeis usedtoveiifythat theSTARTbit has notendedpiematuieIy(apiotectionagainst anoisyIine).The softwaie timei seivice ioutine uses the vaiiabIercve

statetodeteiminewhetheiitshouIdcheckfoiavaIidSTARTbit,deseiiaIizedata,oicheckfoiavaIidSTOPbit. When a compIete chaiactei has been ie-ceived it is moved to the ieceive buffei and init

receiveiscaIIedtosetuptheieceivepiocessfoithenextchai-actei. This ioutineis aIsocaIIedwhenaneiioi (e.g.,invaIidSTARTbit)isdetected.AppendixCcontains thecompIeteIistingof theiou-tinesandthesimpIeIoopwhichwasusedtoinitiaIizethemandveiifytheiiopeiation. Thetest wasiunfoiseveiaIhouisat9600baudwithnoappaientmaIfunc-tionofthepoit.43 Interfacing an Optical Encoder tothe HSI UnitOpticaI encodeis aieamongoneof themoiepopuIaidevices usedtodeteimine positionof iotatingequip-ment. These devices output two puIse tiains with edgesthatoccuifiom2to4000timesaievoIution.FiequentIytheie is a thiidIine whichgeneiates onepuIsepeiievoIutionfoiindexingpuiposes. Figuie4-2shows a six Iine encodei and typicaI wavefoims. As canbe seen, the two wavefoims piovide the abiIity to detei-mine both position and diiection. Since a miciocontioI-IeicanpeifoimieaI timecaIcuIationsit ispossibIetodeteimineveIocityandacceIeiationfiomthepositionandtimeinfoimation.Inteifacingtotheencodeicanbeaninteiestingpiob-Iem, as it iequiies connectingmechanicaIIygeneiatedeIectiicaI signaIs totheHSIunit. ThepiobIems aiisebecauseitisdifficuIttoobtaintheexactnatuieofthesignaIsundeiaIIconditions.TheequipmentusedintheIabwasaPittman9400se-iies geaimotoi witha 600 Iine opticaI encodei fiomVeinitech.TheencodeihastobecaiefuIIyattachedtothe shaft tominimize anyiunout oi endpIay. Foitu-nateIy, Pitmann has staited maiketing theii motoiswith baII beaiings and opticaI encodeis aIieady in-staIIed. It is iecommended that the encodei be mountedto the motoi using the exact specifications of the encod-eimanufactuieiand/oiagoodmachineshop.27006146Inside track generates Phase A Outside track generates Phase BFigure 4-2 Optical Encoder and Waveforms39AP-248DigitaIfiIteiingexteinaItothe8096isusedontheen-codei signaIs. The ideaIizedsignaIs comingfiomtheencodeiandafteithedigitaIfiIteiaieshowninFiguie4-3. Theciicuitiyconnectingtheencodeitothe8096iequiies onIy two chips. Aone-shot constiucted ofXORgatesgeneiatespuIsesoneachedgeof eachsig-naI. The puIses geneiated by Phase A aie used to cIockthe signaI fiom Phase B and vice veisa. The haidwaie isshowninFiguie4-4. CMOSpaitsaieusedtoieduceIoadingontheencodeisothatbuffeisaienotneeded.Note that T2CLKis cIockedonbothedges of bothfiIteiedphases.Byusingthismethodiepetitiveedges on a singIe phasewithoutanedgeontheotheiphasewiIInotbepassedontothe8096. Repetitiveedgesonaphasecanoccuiwhenthemotoiisstoppedandvibiatesoiwhenit ischanging diiection. The digitaI fiIteiing technique caus-esaIittIemoiedeIayinthesignaIatsIowspeedsthanananaIogfiItei wouId, but thesimpIicitytiadeoff iswoithwhiIe. Thenet effect of digitaI fiIteiingisIosingtheabiIitytodeteiminethefiistedgeafteiadiiectionchange. This does not affect thecount sincethefiistedgeinbothdiiectionsisIost.Ifitisdesiiedtodeteiminewheneachedgeoccuisbe-foiefiIteiing, theencodeioutputscanbeattacheddi-iectIy to the 8096. As these wouId be input signaIs, Poit0isthemostIikeIychoicefoiconnection.ItwouIdnotbeiequiiedtoconnect theseIinestotheHSIunit, astheinfoimationonthemwouIdonIybeneededwhenthemotoiisgoingveiysIowIy.The motoi is diivenusingthe PWMoutput pinfoipowei contioI and a poit pin foi diiection contioI. The8096 diives a 7438 which diives 2 opto-isoIatois. Thesein tuin diive two VFFTs. A MOV (MetaI Oxide Vaiis-toi,atypeoftiansientabsoibei)isusedtopiotecttheVFFTs, and a capacitoi fiIteis the PWM to get the bestmotoi peifoimance. Figuie 4-5shows the diivei cii-cuitiy. To avoid noise getting into the 8096 system, theg15voItpoweisuppIyisisoIatedfiomthe8096IogicpoweisuppIy.ThisistheextentoftheexteinaIciicuitiyiequiiedfoithisexampIe. AII of thecountinganddiiectiondetec-tion aie done by the 8096. Theie aie two sections to theexampIe: diivingthemotoiandinteifacingtotheen-codei. The motoi diivei uses piopoitionaI contioI with27006147NOTESPhaseA isPhaseAclockedbyPhaseBPhaseB isPhaseBclockedbyPhaseAFigure 4-3 Filtered Encoder Waveforms40AP-248somemodificationsandabiakingaIgoiithm.SincethemainpointofthisexampIeisI/Ointeifacing, themo-toi diivei wiII bebiiefIydesciibedat theendof thissection.Inoideitointeifacetotheencodeiit isnecessaiytoknow the types of wavefoims that can be expected. ThemotoiwasacceIeiatedanddeceIeiatedmanytimesus-ingdiffeientmaximumvoItages. Itwasfoundthatthe27006148Figure 4-4 Schematic of Optical Encoder to 8096 Interface27006149Figure 4-5 Motor Driver Circuitry41AP-248motoi wouId deceIeiate smoothIy untiI the time be-tweenencodeiedgeswasaiound100micioseconds.Atthis point the motoi wouId eithei continue to deceIeiatesIowIy,oiwouIdsuddenIystopandieveise.TheIatteicaseistheonethatwasmostpiobIematic.Aftei a biief oveiview, each section of the piogiam wiIIbe desciibedsepaiateIy, withthe compIete Iistingin-cIuded in the Appendix D. In oidei to make debuggingeasiei, asweII astopiovideinsight intohowthepio-giamis woiking, I/Opoit 1is usedtoindicate thepiogiam status. This infoimation consists of which iou-tine the piogiam is in and undei which mode it is opei-ating.Themainpiogiamsectionsaie:MainIoop,HSIinteiiupt, Timei2check, andMotoidiive. TheieaieaIsominoi sections suchas initiaIization, timei ovei-fIowhandIing, andsoftwaietimeihandIing. Tyingev-eiything togethei is some oveihead and gIue. Wheie thegIue is not obvious it wiII be discussed, otheiwise it canbedeiivedfiomtheIistings.The piogiam is a main Ioop which does nothing exceptseive as a pIace foi the piogiam to go when none of theinteiiupt ioutines aie being iun. AII of the piocessing isdoneonaninteiiuptbasis.Theie aie thiee basic softwaie modes whichaie in-voked depending on the speed of the motoi. The modesiefeiied to as 0, 1 and 2, in oidei fiom sIowest to fastestopeiation.Whenthepiogiamisiunningtheopeiatingmode is indicated by the Iowei 2 bits of Poit 1, with thefoIIowingcoding:P10 P11 Mode Description0 0 0 HSI looks at every edge1 0 1 HSI looks at Phase A edges only0 1 2 Timer 2 used instead of HSI1 1 2 (alternate form of above)The exampIe is easiest to see if mode 2 is desciibed fiist,foIIowed by mode 1 then mode 0. In mode 2 Timei 2 isused to count edges on the incoming signaI. A softwaietimeiioutine,whichisactuaIIyiunusingHSO.0,usestheTimei2vaIuetoupdateaLONO(32-bit)softwaiecounteiIabeIedPOSITIONTheHSOioutineiunsev-eiy260micioseconds.TheHSO.0inteiiuptisusedin-steadofanactuaIsoftwaietimeibecauseoftheabiIitytoeasiIyunmaskitwhiIeotheisoftwaietimeiioutinesaieiunning.In the code in Listing 4-7, the mode is fiist deteimined.Foi the fiist pass ignoie the code staiting with the IabeIin

mode

1. Staiting with in

mode

2 the countei isinciementedoideciementedbasedonbit zeioof DI-RFCT. If DIRFCT.0e0the motoi is goingback-waid, ifitisa1themotoiisgoingfoiwaid. Nextthecount diffeience is checked to see if it is sIow enough togo into mode 1. If not the ioutine ietuins to the code itwasiunningwhentheinteiiuptoccuiied.27006150Listing 4-7 Motor Control HSO0 Timer Routine42AP-24827006151Listing 4-7 Motor Control HSO0 Timer Routine (Continued)If thepuIseiateissIowenoughtogotomode1, thetiansitionismadebyenabIingHSI.0andHSI.1. Bothof theseIinesaieconnectedtothesameencodeiIine,withHSI.0IookingfoiiisingedgesandHSI.1Iookingfoi faIIingedges. TheHSI

TIMEiegistei is ieadtospeed up cIeaiing the HSI FIFOand the LAST1

TIMEvaIueisset upsothemode1ioutinedoesnotimmediateIyput thepiogiamintoanotheimode. TheHSI FIFOis then cIeaied, the Timei 2 vaIue usedthioughout this ioutine is saved, andthe ioutine ie-tuins.This ioutine stiII iuns inmodes 0 and1, but inanabbieviatedfoim.ThesectionofcodestaitingwiththeIabeIin

mode1checkstoseeifthepuIsesaiecominginsosIowIythatbothHSIIinescanbechecked.Ifthisis the case thenaII of the HSIs aie enabIedandthepiogiamietuins.Thisioutineisthesecondaiymethodfoigoingfiommode1tomode0,thepiimaiymethodisbycheckingthetimebetweenedgesduiingtheHSIioutine,whichwiIIbedesciibedIatei.TheHSOioutinewiII enabIemode0fiommode1iftwo edges aie not ieceived eveiy 260 micioseconds. Thepiimaiy method, (undei the HSI ioutine), can onIyenabIe mode 0 aftei anedge is ieceived. This couIdcauseapiobIemiftheIast2edgesonPhaseAbefoietheencodeistopsweietoocIosetoenabIemode0. Ifthis happened, mode 0 wouId not be enabIed untiI afteitheencodeistaitedagain,iesuItinginmissededgesonPhase B. Using the HSO ioutine to switch fiom mode 1tomode0eIiminatesthispiobIem.Figuie 4-6 shows a state diagiamof howthe modeswitching is done. As can be seen, theie aie two souicesfoimostofthemodedecisions.ThisheIpsavoidpiob-Iemssuchastheonementionedabove.Wheneithei Mode 1oi Mode 0is enabIedthe HSIinteiiuptioutinepeifoimsthecountingofedges,whiIetheHSOioutineonIyensuiesthatthecoiiectmodeisiunning. The ioutines foi modes 0 and 1 shaie the sameinitiaIizationandcompIetionsections, withthe mainbodyofcodebeingdiffeient.TheinitiaIizationioutineissimiIaitomanyHSIiou-tines. The fIags aie checkedto ensuie that the HSIFIFOdataisvaIid, andthentheFIFOisiead. Next,the main body of code (foi eithei mode 0 oi mode 1) is43AP-24827006152NOTESMode0HSIExaminesedgesonPhaseAandBMode1HSIExaminesedgesonPhaseAonlyMode2TIMER2storesedgecountFigure 4-6 Mode State Diagram27006153Listing 4-8 Motor Control HSI Data Available Routine44AP-248iun. At the end time and count vaIues aie saved and thehoIding iegistei is checked foi anothei event. Listing 4-8containstheinitiaIizationandcompIetionsectionsoftheHSIioutine.Listing4-9is the mainbodyof the Mode 1ioutine.Befoie any caIcuIations aie done in Mode 1, the incom-ing puIse peiiod is measuied to see if it is too fast oi toosIowfoimode1.Thetimepeiiodbetweentwoedgesisusedsothat thedutycycIeof thewavefoimwiII notaffectmodeswitching.IfitisdeteiminedthatMode2shouIdbeset, Poit 1.1isset, aII of theHSIIinesaiedisabIed, and the HSI fifo is cIeaied. If Mode 0 is to beset aII of the HSI Iines aie enabIedandthe vaiiabIeLAST

STAT is cIeaied. LAST-STATe0 is used asa fIag to indicate the fiist HSI inteiiupt in Mode 0 afteiMode1.Afteithemodecheckingandsettingaiecom-pIete the inciementaI vaIue in Timei 2 is used to updatePOSITION. ThepiogiamthenietuinstothecompIe-tionsectionoftheioutine.TheieisaIotmoiecodeusedinMode0thaninMode1, most of which is due to the muItipIe jump statementsthat deteimine the cuiient andpievious state of theHSI pins. In oidei to save execution time seveiaI bIocksof code aie iepeated as can be seen in Listing 4-10. Thefiistdeteiminationisthatofwhichedgehadoccuiied.If a Phase A edge was detected the LAST1

TIME andLAST2

TIMEvaiiabIesaieupdatedsoaiefeiencetothe puIse fiequency wiII be avaiIabIe. These aie thesamevaiiabIesusedundeiMode1.AtestisaIsomadetoseeif theedgesaiecomingfast enoughtowaiiantbeinginMode1,iftheyaie,theswitchismade.IftheIast edgedetectedwasonPhaseB, theinfoimationisusedonIytodeteiminediiection.27006154Listing 4-9 Motor Control Mode 1 Routines45AP-24827006155Listing 4-10 Motor Control Mode 0 Routines46AP-248AfteimodecoiiectnessisconfiimedandtheLASTx

TIME vaIues aie updated the LAST

STAT (LastStatus)vaiiabIeisusedtodeteiminethecuiientdiiec-tion of tiaveI. The POSITION vaIue is then updated inthe diiectionspecifiedbythe Iast twoedges andthestatus is stoied. Note that the fiist time in Mode 0 afteibeing in Mode 1, the Mode 1 done

chk ioutine is usedtoupdatePOSITION, insteadof theioutinesgoing

fwdandgoing

revfiomtheMode0sectionof code.ThecompIetionsectionofcodeisthenexecuted.Pioviding the PWM vaIue to diive the motoi is done byaioutine iunningundei Softwaie Timei 1. The fiistsectionofcode,showninListing4-11a,hastodowithcaIcuIatingthepositionandtimeieiiois.Listing4-11bshowsthenextsectionof codewheiethepoweitobesuppIiedtothemotoiiscaIcuIated. Fiistthediiectionischeckedandif thediiectionisieveisetheabsoIutevaIueoftheeiioiistaken. Iftheeiioiisgieateithan64K counts, the PWM ioutine is Ioaded with the maxi-mum vaIue. The next check is made to see if the motoiis cIose enough to the desiied Iocation that the powei toitshouIdbeieveised,(i.e.,enteitheBiakingmode).IfthemotoiisveiycIosetothepositionoihassIowedtothepointthatisIikeIytotuinaiound,theHold

Posi-tionmodeisenteredThedeteiminationof whichmodesaieseIectedundeiwhat conditions was doneempiiicaIIy. AII of thepa-iameteis used to deteimine the mode aie kept in RAMsotheycanbeeasiIychangedonthefIyinsteadofbyie-assembIingthepiogiam.ThepaiameteisintheIist-ing have been seIected to make the motoi iun, but havenotbeenoptimizedfoispeedoistabiIity.AdiagiamofthemodesisshowninFiguie4-7.Inthe Hold

Positionmode powei is easedontothemotoi to Iock it into position. Since the motoi couId bestoppedinthismode, someintegiaI contioI isneeded,aspiopoitionaIcontioIaIonedoesnotwoikweIIwhentheeiioi is smaII andtheIoadis Iaige. TheBOOSTvaiiabIe piovides this integiaI contioI by incieasing theoutputafixedamounteveiytimepeiiodinwhichtheListing 4-11 Motor Control Software Timer 1 Routine27006156Listing 4-11a Motor Control Software Position Counter47AP-24827006157Listing 4-11b Motor Control Power Algorithm48AP-24827006158Figure 4-7 Motor Control Modeseiioi does not get smaIIei. Once the eiioi does getsmaIIei, usuaIIy because the motoi staits moving,BOOSTiscIeaied.A sanity check can be peifoimed at this point to doubIecheck that the 8096 has piopei contioI of the motoi. Inthe exampIe the woist that canhappenis the pioto-27006159Listing 4-12 Motor Control Next Position Lookup49AP-248typewiIIneedtobeieset, sothesanitycheckwasnotused. If one weie desiied, it couId be as simpIe ascheckingahaidwaiegeneiateddiiectionindicatoi, oiascompIexascheckingmotoiconditionandotheien-viionmentaIfactois.Aftei aII checks have beenmade, the powei vaIue isIoaded to the RPWR iegistei using a softwaie inveisiontocompensatefoithehaidwaieinveision.Diiectionisdeteimined next and the powei and diiection aiechangedinadjacent instiuctions withinteiiupts dis-abIedtopieventchangingpoweiwithoutdiiectionandviceveisa.Toexeicise the piogiamIogicthe desiiedpositionischangedbasedonthetimevaIueusingthecodeandIookuptabIeshowninListing4-12.The iemainingsections of the piogiamaie ieIativeIysimpIe, butwoithdiscussingbiiefIy. TheinitiaIizationioutineinitiaIizes theI/Ofeatuies andpIaces seveiaIvaiiabIes fiom ROM into RAM. Having these vaiiabIesinRAMmakesiteasieitotweaktheaIgoiithm.Timei1isexpandedintoa32-bittimeibytheinteiiuptiou-tineshowninListing4-13.Softwaie timei oveihead is handIed by the ioutineshown in Listing 4-14. In this ioutine the status of eachtimeibitischeckedinashadowiegistei.IfanyofthetimeishaveexpiiedtheappiopiiateioutineiscaIIed.27006160Listing 4-13 Motor Control Timer Interrupt Routine270061B2Listing 4-14 Motor Control Software Timer Interrupt Handler50AP-24827006161Listing 4-15 Motor Control Software Timer 2 RoutineThe Iast ioutine, shown in Listing 4-15, is the SoftwaieTimei 2 ioutine which outputs some vaiiabIes to extei-naI RAM. It aIsokeepsLAST1-Timewithin1800Hof Timei1topievent oveifIows fiomoccuiiingwhentheMode0andMode1softwaiecheckthisvaiiabIe.AcompIeteIistingof thepiogiamasitisusedinouiIabcanbefoundinAppendixD.Foiagivenmotoioiencodei it wiII piobabIy be necessaiy to change some ofthetimeconstantsonthefiistpageoftheIisting.Withthe motoi used in oui expeiimentation, puIses aiemissed fiomtime to time when diiection changesquickIy. If the motoi weie not as fast to tuin aiound oithe encodei weie mounted bettei these piobIems shouIddisappeai. The missing puIses occui whenswitchingfiomMode1toMode0,otheithanthatnoanomaIiesweiefoundintheIab.Piioitotheveisionof codejust discussed, seveiaI at-temptsweiemade, oneof whichcouIdbeusedundeiceitainconstiaints. It ispossibIetouseonIymodes2and0tomonitoi the encodei, piovidedthe encodeiaIways opeiates smoothIy and piovides at Ieast 200 mi-ciosecondsbetweentheIast seveiaI edgesof PhaseAbefoieieveising.ThisideawasoiiginaIIytiiedbecausethe motoi was not chaiacteiizedthoioughIyat fiist,and caused piobIems because of the motois tendency tostopsuddenIywhenitsspeedwasIow.If an encodei has a Iowei Iine count and theiefoie moietimebetweenoutputpuIsesthetwomodesoIutioncanbeused.ThesoftwaiefoithetwomodeveisioncanbeeasiIyextiactedfoimthethieemodeveision,soitwiIInotbepiesented.50HARDWAREEXAMPLE51 EPROM Only Minimum SystemThe diagiam in Figuie 5-1 iIIustiates how to connect an8096inaminimumconfiguiationsystem.Fithei2764soi 27128s canbe usedinthe system. Note that theIowei FPROM contains the even bytes whiIe the uppei51AP-24827006162Figure 5-1 (1 of 2)onecontainstheoddbytes, andtheaddiessingisnotfuIIy decoded. This means that the addiessing on a2764 wiII be such that the Iowei 4K of each FPROM ismapped at 0000H and 4000H whiIe the uppei4K is mapped at 2000H. If the piogiam being Ioaded is16KbytesIongthefiisthaIfisIoadedintothesecondhaIf of the 2764s andvice veisa. AsimiIai situationexistswhenusing27128s.52AP-24827006163Figure 5-1 (2 of 2)This ciicuit wiII aIIow most of the softwaie piesented inthisap-notetobeiun.Inasystemdesignedfoipioto-typingintheIabitmaybedesiiabIetobuffeitheI/Opoitstoieducetheiiskofbuiningoutthechipduiingexpeiimentation. One may aIsowant toenhance thesystembypiovidingRCfiIteisontheAtoDinputs,apiecisionVRFFpoweisuppIy,andadditionaIRAM.52 Port ReconstructionIfitisdesiiedtofuIIyemuIatea8396thenI/Opoits3and4mustbeieconstiucted. Itiseasiesttodothisifthe usage of the Iines canbe iestiictedtoinputs oioutputs on a poit by poit iathei than Iine by Iine basis.The poits aie ieconstiucted by using standaid memoiy-mapped I/Otechniques, (i.e., addiess decodeis andIatches), at the appiopiiate addiesses. If no exteinaIRAMisbeingusedinthesystemthentheaddiessde-codingcanbepaitiaI,iesuItinginIesscompIexIogic.TheieconstiuctedI/OpoitswiII woikwiththesamecodeastheonchippoits. TheonIydiffeiencewiII bethepiopagationdeIayintheexteinaIciicuitiy.53AP-24860CONCLUSIONAnoveiviewoftheMCS-96famiIyhasbeenpiesentedaIong withseveiaI simpIe exampIes anda fewmoiecompIex ones. The souice code foi aII of these pio-giams aieavaiIabIeintheInsiteUseis LibiaiyusingoideicodeAF-16.AdditionaIinfoimationonthe8096can be found in the MiciocontioIIei Handbook and it isiecommendedthatthisbookbeinyouipossessionbe-foieattemptinganywoikwiththeMCS-96famiIyofpioducts.YouiIocaIInteIsaIesofficecanassistyouingetting moie infoimation on the 8096 and its haidwaieandsoftwaiedeveIopmenttooIs.70BIBLOGRAPHY1.MSC-96MacioAssembIeiUseisOuide, InteI Coi-poiation,1983.Oideinumbei122048-001.2.MiciocontioIIei Handbook (1985), InteI Coipoia-tion,1984.Oideinumbei210918-002.3.MSC-96 UtiIities Useis Ouide, InteI Coipoiation,1983.Oideinumbei122049-001.4.PL/M-96UseisOuide,InteICoipoiation,1983.Oideinumbei122134-001.54AP-248APPENDIXABASICSOFTWAREEXAMPLESA1 Table Lookup 127006164A-1AP-248A1 Table Lookup 1 (Continued)27006165A-2AP-248A2 Table Lookup 227006166A-3AP-248A2 Table Lookup 2 (Continued)27006167A-4AP-248A3 PLM-96 Code with Expansion (Continued)2700616927006170A-6AP-248A3 PLM-96 Code with Expansion (Continued)27006171A-7AP-248A3 PLM-96 Code with Expansion (Continued)27006172A-8AP-248A3 PLM-96 Code with Expansion (Continued)27006173A-9AP-248A3 PLM-96 Code with Expansion (Continued)27006174A-10AP-248A4 Pulse Measurement27006175A-11AP-248A4 Pulse Measurement (Continued)27006176A-12AP-248A5 Enhanced Pulse Measurement27006177A-13AP-248A5 Enhanced Pulse Measurement (Continued)27006178A-14AP-248A6 PWM Using the HSO27006179A-15AP-248A6 PWM Using the HSO (Continued)27006180A-16AP-248A6 PWM Using the HSO (Continued)27006181A-17AP-248A6 PWM Using the HSO (Continued)27006182A-18AP-248A7 Serial Port27006183A-19AP-248A7 Serial Port (Continued)27006184A-20AP-248A8 A to D Converter27006185A-21AP-248A8 A to D Converter (Continued)27006186A-22AP-248APPENDIXBHSOANDATODUNDERINTERRUPTCONTROL27006187B-1AP-24827006188B-2AP-24827006189B-3AP-24827006190B-4AP-248APPENDIXCSOFTWARESERIALPORT27006191C-1AP-24827006192C-2AP-24827006193C-3AP-24827006194C-4AP-24827006195C-5AP-24827006196C-6AP-248APPENDIXDMOTORCONTROLPROGRAM27006197D-1AP-24827006198D-2AP-24827006199D-3AP-248270061A0D-4AP-248270061A1D-5AP-248270061A2D-6AP-248270061A3D-7AP-248270061A4D-8AP-248270061A5D-9AP-248270061A6D-10AP-248270061A7D-11AP-248270061A8D-12AP-248270061A9D-13AP-248270061B0D-14AP-248270061B1D-15INTEL CORPORATION 2200 Mission College Blvd Santa Clara CA 95052 Tel (408) 765-8080INTEL CORPORATION (UK) Ltd Swindon United Kingdom Tel (0793) 696 000INTEL JAPAN kk Ibaraki-ken Tel 029747-8511Printed in USAxxxx0296B10MRP SMMicrocontroller Operation