2 CHAPTER to MicroProcessorIntroduction BasedControl OBJECTIVES After studying this chaptet you shouldbe able to: . Unalerstandwhat a microprocessoris. what it does, and how it works. . Understandthe conceprsof RAM and ROM computermemory and how via the addressanddatabuses memoryis accessed . Understandhow parallel and serial data intedaces work. . Perform relevant calculationspertaining to analog-to-digital converte$ and digital-to analog converters. . Understandthe principles of digilal controller software. . Recognizeand describethe characteristicsof the various types of available digital controllefi, that is, micrccontrollers,single-boardcomputers,programmablelogic conoollen, and pe$onal computers. INTRODUCTION The digital integratedcircuit (IC) called a microprccessor lFigure 2.1(a)l' hasushered in a whole new erafor control systemselectronics This revolution has occtmedbecausei bringsthe fleribilil) ol pfogramcon(rolandrhecomiutarional rhemicroprocessor po*er of i iirmputer to beai ciii any problem.iAutomatic co rol applications are pafofthis technology'andmicroprocessor-based ticularly well suitedto takeaalvantage confo] systemsarerapidlyreplacingmanyolder controlsystemsbasedon analogcircontlollen relays,One ofthe first microprocessor-bas€d cuits or electromechanical (PLC), pogrammable logic conrroller was the applications for control madespecifically itself by 12. A microprocessor in Chapter chapter and which is discussedlaterin this circuits are input/output as memory and is not a computer; additional componentssuch 1(b)], which is 2 rcquirealto make it opemtional.Howevet tbe microcontroller lFigure 26 CHAPTER2 Figure2.1 (a) Microprocassor Mlcfocontrollgr CPU (microprocessor) (b) Microcohtroller doeJcontainall the computerfunctionson a sina closerelativeof the microprocessor, lack someof $e po$er and speedof the ne\ er mjcroprocessle IC, MicroconLrollers Inosl'u calleJ io,t Urt 'f,.rr compcclrre*i' idedlfor mrn) controlJpp'icrtron\: suchas vendingmacbines,arereallyusingnicroLlevices, micioorocessor-conirolled designin control contrJlle6.Somespecificroasonsfor usinga digitalr'microprocessor systemsarethe following: . Low level siSnalsfrom sensors,oncoconvertedlo digital' canbe transmittedlong distancesvirtuallyerorjree. 'lralegie' . A microproce..or canec'il) h"ndlecomplerc"lculalion\andconlrol . tonrr.irnt..utyi.rvcilablelokeeplmclolpardmeterqin\lo$nroting'y'lem . irroininn o".onior srategy is easyby loading in a new program;no hardware changesare requfeo. . Micriprocessor baseticontrollersare more easily connectedto the computernetwork andreadcur_ within an organization This allows designeff to enterprogram changes rcnr\)slemslalusrromlheirJe'krermr'lrl' ro tvl!891899E9998!49E!!9!fB9! rNrRoDUCloN 27 In this chapter,we will presentthe basic conceptsof a microprccessor--and syslem-applicamicrocontrolle;basedsystemwith particularemphasison control the restof the text make to but enough tions.It is by no meansan in-depthtreatment, moremeaningful, hardware In the firs-tsectionsofthis chapterthe basicconceptsof microprocessor (theseconceptsalso apply to microcontrollers)l have and ooemtionare introduceal haveat inctudea*ris materiattecausethe studentof moderncontrol systemsshould leasta generalknowledgeofhow the nicroprocessorperformsitsjob 2.1INTRODUCTIONTO MICROPROCESSOR SYSTEMIIARDWARE unit(CPU)' units:theceniulprocessing is madeupof fourbasicfunctional A computer unit doestheactualcompuF (VOl Thecentratprocessing memoiv.input,andoLrtput logjcunilandcontrolsections thearithmetic innoniit iotoor.a oi l\ o subparls: andlogic, (ALU) performs $e aclurlnumerical ,iin*" Z.:l-fli. *itrlt.tic logi; unit ol reclion conrol on The and so AND. OR ia)iulationssuchasadditionsubEacdon. ptogramI nstructhe thedataflow' suchasreadingandexecuting theCPUmanages handsit overto theALU for protheconfol section calculations, re-quire tions.Ifdata is theCPU themjcroprocessor compulet, cessing.lna mi;roprocessor_based Figure2,2 cPU(mlcroProcessor) r------------------i Bus Address ALU Outptjt TO To indicatorc, Registers DataBus ConlrolBus 28 CHAPTER 2 Digital datais in the folm of bits, whereeachbit hasa value of either I or 0. Digital logic 1 and0 Vdc to represenr logic 0. Eightbits circuits suallyuse5 Vdc to represent handles togetheris called a byte. A microprocessor digital datain words, wherea word may be 8, 16, or 32 bits wide. For example,an 8-bit microprccessor hasa byte sized word, with a maxinum decimalvatueof 255. (Computersrepresentnumbersin the binary numbersJstem;forexample,11111111binary = 255 decimal.)The rightmost bit in a binarynumberhasthe leastvalue(usually1) andis calledtheleastsignificant the highestvalueandis calledthe most signiff" bit (LSB). The leftmostbit represents cant bit O4SB). The convenion betweenbinary and decimal can be performeddirectly with mostscientificcalculators or manuallyusingthe techniqueshownin Example2.1. To expressvalueslargerthan255,lwo or morewordsareput togetherIn this text, we areusedunlessotherwisestated, will assume8 bit microprocessors Find the decimalvalueof the 8-bit binarynumber SOLUTJON LSB MSB r28..64:. 32 1 6 ,0.rr I : 1 I lxl= I 2x1= 2 4x0= 0 8x0= 0 16x1= 16 32x1= 32 64x0= 0.. 1 2 8x 1 = 1 2 8 + 179 decimal The memory section of the computer is a place where digital data in binafy form (ls and 0s) are stored.Memory consistsof cellsorganizedin S-bitgroups.Eachbyte CONTROL TO MICROPROCESSOR.BASED INTRODUCTION 29 is given a unique numeric address, which reprcsentsits location just as a sreet adalrcss representsthe location of a house,Dala are written into memory and read out of memory, basedsolely on thoir address.In a particular memory circuit, the addressesmight start at 1OO0and run consecutivelyto 2000. Figure 2.3 diagramsa section of memory. Note that the fiIst byte of datahas a decimal value of 2 (00000010= 2 decinal) and an addressof 1000. memory.The first is landomCompute$usuallyhavetwo kinds of addressable acc€ssmemory (RAJI), which allows the computerto read and write dataat any of its addresses(it is also calledread/writememory or RWM). Alt datain this t ?e of memory are lost when the poweris tumed off andis calledvolatile memory (an exceptionis alesignswhere RAM is kept "alive" with a small battery). The secondtype of memory is read-only memory (ROM), which is similar to RAM exceptthat new datacannotbe written in; ali dala in ROM are loadedat the factory and cannotbe changedby the computer This memory does not lose its data when power is tumed off and is called nonvolatile m€mory, Most miooprccessol systemshave both RAM and ROM. RAM is used for temporary program stomge and as a tempomry scratch-padmemory for the CPU. ROM is usedto storeprogramsanddatathat needto be alwaysavailable Actually, many computelsusean EPROM (erasablepro$anrmableread-orilymemory) oi an EEPROM (electdcally erasableprograrnnableROM) insteadof a ROM for long{erm mem ory. EPROMScan be erasedwith a strongUV light and reproFammed. EEPROMScan be ensed andrepogrammed electrically.Disk ddvosalso storedigital databut in a form that must be processedbefore they arc accessibleto the microprocessor. The inpuuoutput (VO) sectionof the computei allows it to inteface with the ool side wor1d.The input section is the conduit tbrough which new programsand dataare rnleredinto the compuler.andLheoutpulsecuonallo\L"lhe compulerlo communicale its rcsults.An VO interfaceis called a port. An input polt is a circuit that connectsinput devices to the compuler; examplesof input devicesare keyboards,sensors,and switches.An oulput polt is a circuit that connectsthe computerto output devlces. Examples of output devicesare indicator lamps, actuators,and monilors. lnput/oulput is discussedin more detail in the next seciion Referring again to Figure 2.2, we seethat the blocks are connectedby thrce lines labeled adalressbus, databus, aIId control bus The addr€ss buljs a group of wiros that carries an address(in binary {orm) from the CPU to the memory and VO circuits. The Fig!re 2.3 Address 1000 1001 1002 1003 1004 Data 00000010 01100100 00000000 01011100 10011010 30 CHAPTER2 hasalreadybeendiscussed, but you may wonneedfor memoryto receiveaddresses It tums out that all I/O ports are assignedaddresses der why VO ports need adalrcsses. and are treated essentially like memory locatrons by the CPU. The CPU oufputs data to the outside world by sendilg them to a port address.When the circuitry of the designated output port detectsils assignedaddresson the addressbus, it opensand allows data to passfrom the databus to whateveris connectedto fhe poIt. There arc two ways is done.Somemicroprccessorsusewhat is calledmemory-mapped that yO adalressing itrpuvoutput, where an VO addressis teated just like anothermemory adalrcss.Other microprocesson treat VO addressescompletely sepante liom memory addresses, The dats buqis a group of eight wires that carries the actual numedcal data ftom place to place within the computer Figure 2.2 showshow the databus interconnectsall blocks. Data flow in both dircctionson t}le databus. For example,input dataenler tbrough the input port and proceedtbrough the databus to fte CPU. If the CPU needs to store thesedata, it will sendthem back through the data bus to memory. Data to be outputted are sent (by the CPU) through lhe databus to lhe output port. If the databus connectsto all blocks.how do the dataknow which block to go to? The answeris the addresssystem. For example, when t]rc CPU sendsdata to memory, it does it in two steps:First, it puts the destinationmemoryaddresson the addressbus; second,it puts the dala on the data bus.When the designatedmemory detectsits own address,it "wakesup" and takesthe datafrom the databus.The otherblocks connectedto the becausethey were not addressed. A good anaibuseswill igrore the wholesequence ogy hereis the phonesystem,wherethe phonenumberis analogousto the memory of phonesmay be connectedto the syslem,whenyou address. Eventhoughthousands dial a numbe! only the designatedphone iings. The beauty of the bus systemis that it is expandable.Memory or addressableyO units can be addedto the systemby simply connectingthemto the buses. The contml bus (seeFigue 2.2) consistsof timing and event-controlsignalsfrom the CPU. These signalsare usedto control the dataflow on the databus. For example, oneof the controlsignalsis the r€ad vrite (RJW)line. This signalinformsthe memory if the CPU wishesio read existing daia out of memoly or write new datainto memory. Non-memory-mappedmachineshave a menory-I/O control li e.Thls signal info.ms the systemif the cunent dataexchangeinvolves memory or an yO port. In genas arethe addressanddatabuses. eral,the controlbusis not as standardized 2.2 INTRODUCTIONTO MICROPROCESSOR OPERATION The microprccessor works by executing a program of instructions. Creating the prc gram is similar in concepl to programming in BASIC, C, or any other highlevel com puter language.Each type of microprocessorhas its own instruction set! which is the insFuc set ofcommandsthatit wasdesignedto rccognizeandobey.Microprocessor CONTROL TO NIICROPROCESSOR-BASED INTRODUCTION 3l tions are very elementaland specific, and it usually takesmore than one to accomplish what a single, high-level languageinshrction would. Many micmprocessorinstructions simply move datafrom one place to anotherwithin the computer;othen perform mathematical or iogic operations.Still anothergroup of instructions conllol program flow, such asjumping forward or backwad in the program Each instruction in the instruc tion set is assignedits own unique operstion cod€, (which is typically 8 bits long and refered to as the op,code). The CPU usesthis 8-bit number to identify the instluction. All microprccessorchave at leastone accumulator lFigure 2.4(a)], which is a dataholding registerin the CPU. The accumulatoractsas a "staging area"for data.It is common for datacoming to the CPU to go fiIst to the accumulatot where it can be operated on. Similarly,most dataleavingthe CPU exits ftom the accumulator.Mathematical operationsusually store the result in the accumulator.Ma[y of the instructions involve the accumulatorin one way or another. A machine languageprogramis a list of instructions(in op-codeform) for the microprocessorto follow. Before the program can be executed,it musl first be loaded sequenliallyinto memory.The op codefor lhe first instructionis loadedat the first adahesslocation, the op-codefor the secondinstruction is loadednext in line, and so on. Figure 2.4(b) showsa sectronof memory with a shofi Fogram loadedin. The progmm listing includesthe addrcss,op-code,mnemonic,and a brief explanation.(A mnemonic is an English abbreviation of an insffuction. A Fogram listing using only mnemonicsis called assemblylaDguage.)The plogram in Figure 2.4(b) dircctsthe CPU to get I byte of datafrom input port 01, add I to it, and sendthe result lo outputport 02. Beforc execution can stat, the addressof the first instruction must be loaded into the registerthatthe prcgramcounter,The program counter is a specialaddress-stomge program, much like a bookmark. Tbe proCPU usesto keep lrack of where il is in the gram counter always holds lhe addressof the next instruction to be executed.Oncethe Figure2.4 CPU lnstruction Adr The CPUuseso tN 01 Explanation I Get datafrominputport 01. INRA OUT02 Incrsmentaccumulaior. t Senddatato oulputport 02. Op Code 00 o1 02 03 04 05 DB 01 3C D3 02 76 HLT Hall. o6 (a) (b) Examplemicroprocessorprogram 2 CHAPTER microprocessoris activated,executior of ihe progmm is complelely automatic.The exe first cution processis a seriesof fetch-executecycles,wherebythe microprocessor specific it. The following are the and then executes fiom memory fetchesthe instruction stepsthe microprocessorwould go tkough to executelhe program of Figure 2 4(b): L The microprccessorf€tchesthe first i talction from memory lt knows whereto find the instruction becauseits addtessis in the program counter 2- Once in th€ CPU, the op-codeis decodedto seewhich instructionit is, then the proper hardwareis activatedto executethis instruction. In the exampleprogram of Figure 2.4(b), the 6I5t instruction(IN 0l) is 2 bt'tes long. The first byte of the instruction is the op-code,telling the CPU to inpul data from a Port. The secondbyte of the instruction rclls the CPU )v/ri./l po( to read from. Exection of tbis instruction causes dataftom input port 0l to travel along the databus to the accumulator'AIso, the programcounteradvances to 02 (theaddressof the next instruction)Executionof the first instructionis now complete. 3. The next fetch-executecycle stans,this time fetchilg lhe insruction flom address02. is so the accumulator The new instruction(INR A) is "incrementthe accumulator," (add l) andthe resultpu! backin lhe accumulasentto theALU to be incremented of the llextinstruction. to 03, which is the address tor The programcounteradvances from address this dme fetching the instruction cycle stans, 4. The nextfetch-execute 03. The instruction(OUT 02) is executed,causingthe accumulatordatato be sent to outputpoft 02. to 5. The final instructionis fetched.It is a "halt," which causesthe microprocessor ceaseoperadngandgo into a wait mode. 2.3 INTERFACINGTO A MICROPROCESSOR CONTROLLER An imporlant pan of any control systemis the link betweenthe controller and the real world. For a digital controller, dataenter and exit through a parallel inlerface or through a serial interface. Both data formats are discussednext. The ParallelInterface The parallel interface transfer data8 bits (or more) at the sametime, using eight separatewires. It is essentially an extensionof the data bus into th€ outside world. The parallelinterfaceis idealfor inputtingor outputtingdatafrom devicesthat areeither on or off. For example,a singlelimitswitch usesonly one inputbit, andan on-offsignal to a motor requrresonly one output bit. these l-bit signals are called logic variabl€s, and eight such signals can be provided from a single (8-bit) port This concept will be expandedon later in this section. CONIBQ! TO I\,IlCROPROCESSOR-BASED TNTRODUCTTON 33 Figure2.5 Digital inpul Yout(analogvollage) '-9.96V -ace to connectto an thecollrollermayusea paral]elinte In otberapplicalions, sucha case,the DC motor. ln driving a variable-speed analogdevice-for example, voltage beforeit into an analog mustfirstbeconverted binaryoutputofthe controller a digital-toby a specialcircuitcalled is pefformed cand vethemotor.Thisoperation analogconverter Digital-to-Andog Conveft iotl Thedigitol"to-analogconverter(DAC)is a circuit thatconvertsa digital wordinto an theinternalworkings Ii is notwithinthescopeof thistextto describe analogvoltage. pararneters is appropnate. ofihe operating understanding olthe DAC,bu!a general DAC. The inputis an8-bit Figure2.5showstheblockdiagramof a typical8-bit !o thebinaryinputvalueand digitalword.Theoutputis a currentthatis proportional voltage(yrtt must A stable reference an op_amp voltage with to a be converted must is, for analog voltage-that the maximum defines This voltage be suppliedto theDAC. y,"r. the is 00000000, If the inPut is essentially %,,r a digitalinputof 11111I11,%,,i ot theoutputvoltageis a linearpercentage will beOVdc.Forall valuesin between, is (for the8-bitDAC) for anydigitalinput theoutprrtvoltage V,"rSpecifically, inpul x Ytul 256 (2.1) = DAC outputanalogvoltage %,,, input = decimalvalueofthe binaryinput Yd = relerencevoltage to the DAC Findtheana10011011. 7 34 2 CHAPTER of digital to analogconversionis resolution.The resAn impoitantconsideration olution of a DAC is the wo$t caseerror that is introducedwhenconvertirgbetween digital andanalog.This effor occursbecausedigital wordsczmonly rcpresentdisdete diagramin Figure2.5.For example,the ma\imum values,asindicatedby the stair-step valueofan s-bit numberis 255 decimal,which meansthere:re 255 possible"steps" ofthe ouQut voltage.The differencebetweenstepsis the valueofthe leastsignjficant bit (LSB). Becausethe smalleslincrcmentis onestep,the rcsolution(for 8-bitdata)is but if morc for manyapplicalions, This tesolutionis adequate I part in 255,or 0.39Eo. is needed.two (ormore) 8 bit portscanbe usedtogether.Two portsprovide16 bils of data.The maximumdecimalvalueof 16bils is 65,535.Being ableto dividean analog numberinto 65,535paits meansthat eachpart wiil be much smallel,so we can more precisely representthat number. INTRODUCTION TO MICFOPROCESSOR-BASED CONTROL Figurc2.6showsa darasheetfor an8-bi!DAC(DAC08O8). Thisdevicecomesas a 16-pinDIP (dualin-linepackage) andusesanextemalop_anp(suchastheLF 351), tworcsistors, anda capacitor io complete thecircuit.It rcquires plusandminuspowe;_ supplyvoltages.Thetimeto completea conversion is a fast 150ns (nanosecondsl. (The circuitshownin Figure2.6hasa y,.rof l0Vdc.) Figure2.6 for the DAC0808. an 8-bitdigital-to(courtesyof coa) ZlaNahonal ItrSemlconcfuctor Digilal'toAnalogConvertels DAC'0808, DAO080Z DAC08(m &Bit D/AConvoders Ganerrl Degcriptlon Th. o^coafi ftier t! .r s.bhhcncrrhicdiirLro *iol 6nsft, toacl t.dur ne I rur xd. d&ur 130d wli ! cl0tnrtn'.nrv 33dw wirhrEV eprlq. it h|.r.".. N,;..r ti"..] oomiry ), nqui.d rorrqi 'pprcrror rm rr'jiJri er. ourN..uifqi L lyr4dry!t Lsgor 2a6rrEr/ 263, id.r|{ &udI of 5.k drrn rO,rO* ;;;. sbir monoroih(y.^drii{ ry *}ih &6 td.t ourllr .u'6r or hn rhr a r/A F4tdd &blrkro eur..e i0' IFEF> 2 nA thi po*ri rupptvtuihB ot +. DACCoI rn6 n. Ind.o.ndrnr ot btr .dr rid .rhrblr u{.ri.tly dnrii d.rr...h.tr.r.,hto o{, tb .nri.r ru.pryvolrrr. tri!., ?h. DAClgOg *tit risre d rc y *$ !eh, TTL oll or Cirosheicrrdr, Indn rdrcr Dtxmmi r& {,. Mc1!03/MC t.03.Fe htdrsrdDord onr .. DACoIOo dtr d.n ElockandConnqcllor Dlagrarns TypicalAppllcatlon l1 t..; Foeluros io.$r .fd h&imuh r Fulrrd.curbnrnndhril rs8 !Y' . 7 rid &bn &aruv rrit.bl. toACOtOr. DACOOO6| r F d r r t i r r l m . rl 5 o r r y D tnoult r.. TTL nd CMOS . H{0hrF.d nulirtytht i.p. js {r: g 6A/rn . Por rclpryeohrt u$: |a.svlo !l6v . L@ Fsd codu pl o.r !! iw e r5v 36 2 CHAPTER Analag-to-DisitalCom'ers'n AIl analog-to-digital cotrv€rter (ADC) is a circuit that convefis an analogvoltage into a digital wcird.A typical ADC consistsof a single IC with a few support components Analog{o-digital conversionis a morc complicatedprocess(thanfor the DAC), and the haralwarorequiressomeconversiontime, which is typically in the microsecond range.The conversiontime requjreddependson the type ofADC, the appliedclock ftequency,and the number of bits being converted.Figurc 2.7 showsa block diagram for yin is 0 an 8-bitADC. The input yi" canbe any voltagebetween0 V and yef When yd (255 decimal). the ouQut is 11111111 Vdc, the outputis 00000000;when Vinis For input voltagesbetvr'een0 and V,er the output increaseslinearly with Vin;therefore, we candeveloDa simDleratio for theADC: output_ 255 v; Vnt (for 8 bits) Solvingfor outputgivesthefollowingl Y" x 255 outp'rt=--- (:2.2) output = decimal output value of an 8-bit ADC 4" = analog input voltage to the ADC V*r = ADC referencevoltage pulseis sentto theADC. TheADC To startthe conversionptocess,a slat_conversion then samplestbe analoginput and convertsit to binary.When completed.the ADC activatesthe data-readyoutput. This signal can be usedto ale the computerto lead in the binary da!a. Figure2.7 Sla conve|sion Dala r€ady Clock Vn (analogvoltageinput) Digilal ouIpul CONTROL TO NIICBOPROCESSOB-BASED INTRODUCTION Figure 2.8 for lhe ADC0804, ZNational ZSemiconductor 37 Analog-tGDigltal Converters ADC0803, ADC08048-BitpP ADCo8fi,ADC0802, CompatibleArDConverlers Corp.) GengralDsscription Th. Aoc0301, ADmao?, aDco003, A9€$04.t ourps m.{ l?L voka$ lcsl shichU$'60d1''.d@lntiomd MrcBoBUstu nrid.d 30304 .onbl bu., ird TarsTAr dlb bB, Th6? A/0' rNE, rikr r wo*swrrh 2.sv i 1M336)voxan 4irro& . 0V b 5v . ros lnpurvonas.r ! 03" n.ndiid widrh?0.pii olP pi.r* rhe @mmon-dodr 4jcriod and o n'lhgvo]bg.rt..l se inplr ai b. ldjund 10all@ . anra vohrg.rpr. ro rh3rurr3bi! ol BrcLuuon, Fgalures KoySpecifications Sbitr !l/4 LsB.r1l? LsB3nd1r LsB r MTcROBUS{30404.omp*ible 5voc rop?ot!6liom&iJ|yo'wih or :ndrot.prn.diuft d !01116 r.c6rc. TypicalApplicatlons ConnectlonDiagrams 38 2 CHAPTER : .:,i,, l asa 20-pin Figure2.8 showsa alatasheetfof an 8-bitADC (ADC0804) Packaged an external requires power and supply DIP, this device can operateon a single 5_Vdc pulse is applied resi;tor and capacitorio completetie ADC circuit The start conversion i" ADc frompin5 (INT-R)Thispanicular fw:nj,'"'a tm a"" 'iady sisnalcomes ca;"Ji be connectedin a free-runningmode whereit perfoms one conversionafterthe setaI half otheras fast asit can.Nolice alsothatthe pin labeledV*rD(pin 9) mustbe rangeot voltage analog for an call olthe ac$al V."r For example,if the requirements rs a converslon complete 0-5 Vdc, then pin 9 would be setto 2 5 Vdc The time to the than approximately100 $s (micro seconds),making it almost700 times slower earlier DAC0808discussed ACo tol $sten UsingPara el Purts Figure 2.9 showsa positioncontrolsystemusing a microprocessorbasedconlroller ports (each wit"hpara el ports. This pafiicular systemhasone output poll andthreeinput rn a DAC dre convened oorri^ is o" n aaat "r the oulputpon i' panition(d:six bil' f|direcrion 'ignal.lhere\en!hbil \pecitre'molor io proriderte ;nalogmolor-dnve andthe eighthbitturns on an audioalarmif some clo'ckwise.O = counlerctockwise)' The firsr input port inputs the selpoint data' the sec emergencysituation is detected. -bit logical r,aflona iputs ttre ,nOC datafrom the sensol'and the third inputs various I as two limi! as well ables.ln this case,the systemhas three front-panelswitches INTRODUCTION TO I\,4ICROPROCESSOR-BASED CONTROL Figure2.9 Analog 'l Switches1oinput set pointin binary. / Gnd = logic0 \ "-1 t0 CHAPTER 2 switches.The limit switchesareusedasa "backup" to detectit if the loadhasgoneout of its designaled range. Operationofthe systenproceedsas follows:The controllerinputsthe datafrom port 03 !o determineif the start (or stop) button hasbeen pressed.If the stat button has beenpressed,thenthe setpoint is readin from port 0 1 andthe digitizedsensordatai s readin from porl 02. Basedon its controlstraregy,the controlleroulputsto port 00 a binary word representingthe motor control voltage.This digital data is convertedto an arulog voltage with the DAC. This entire sequenceis repeatedover and over until lhe stopbuttonis pushed. The Serial Intelface In a s€dal interface, the data are sent I bit after the other on a single wire. There are a numberof goodreasonsfor doingthis.First,the cablingis simplerbecause only two wiresareneeded(at a minimun), thosebeing"data" and"retum."Second.shieldinga small groupofwires, which is olten necessary in an electricallynoisyindustdalenvi ronment,is easie.Third, serialdatacanmakeuseofexisting single-channel datalines suchas tije telephonesystem(whichmay requireusinga modem).For thesereasons, serialdatatransferis usuallyrecommended for distancesgreaterthan 10-30ft. Becausedataalwaysexistin a parallelform insidethe computet it mustbe converted to serial databefbrc coming oul the sedal polt. This is accomplishedwith a spe cial parallel-to-serialconverter IC called a universal asynchronous r€ceiver transmitt€r (UART). On the otherend ofthe line, a receiyerrnustconvertthe serial databackinto paralleldala,which is donewilh anotherUART.Figure2.10showsthe basicserialdatacircuit. Serialdata.rreclassifiedasbeiDgeithersynchronous orasynchronous. S]rchftrrr&r datd require that the databytes be sent as a group in a "package." It is usedin sophistjcatedcommunication systemsthatmovea lot of dataandwill not be furtherdiscussed herc. Arytrchmtnus data tlanslbr is the more conmon (but slower) type of serial trans fer and a11ows for individualbytesto be sentwhenne€ded. Figure2.10 conlroller Serialdala Paralleldata Serial'loparallel (UART) INTRODUCTION TO IVICEOPROCESSOR,BASED CONTBOL 41 Figure 2.11 I 0 1 1 0 0 1(0w i t h "*{.!$n*..cuon"o"..";.f Time Figure 2. I 1 shows the standardformat for asyncbronous serial data. First, a stat bir rs .enl. rhenrhedatarLSB fint,. Lhenc paril)_enorchecUng bit, andfinall\ rhesroD Drusr. 5ome vaflalionis alio$ed lo !hi. format.bur bothEar.mitrer andreceirer mu,r use the samefomat. The other important Dara u*"iii",."i p.,,."."Jilliffi i:i':1fl'#ffi;1ifl ,,illiliJ:Ji: Tfl nrcarryIncorrec(rn mostaase,).Srrnddrdbir rars are J00 6ps , bit\ per secondl,1200 bps.%00 bp.. 14.400bps28.800bps.iJ.600 bps.andj7.000 bp".Se;iat 9l_\-2a00 h rlo\aerrh0nparalJel rransmi5(ion. At .]oObps,ir Lalesajmosl t,ms-lo tran(mil b] le of dara.compared ro lessrt anu mi.ro,econA fo, parutiit_ rnr(r\ lhousands of"ltifie( slowfr Slill.for manyapplications. pdnicularly proce.\con_ trol, the longerdata-transfer timesarcnot a problem, RS232 In orderto makethe serialinterfacepractical,a setof specifications calledtheRS,232 sandardv ase,!abtirhed. Officialty. fie RS-232 shnaara,pec;nes *e seriuiLra iru.r_raceDelqeendalalerminalequipmenltDTE) anddala communication equiDment (DCE).A commordpplicarion ot RS2J2 is rheinrerfrce Uerween ;ta;il; modem,in whichcasethecomputeris theDTE anathenrodemis Are DCe tseeFieu;e 2.I2(a)lA modemis a devicetharconveds digiralAntuintouuOto ro*, * tf,uiit?" beftansmitted overthetelephone lines.As shownin Figure2.12,theRS_232 intefaca consistsof sevensignals;theserialalatais senton dn Z ina receiv"Oonpin:; ifreotfrer signals,suchas"Requestto send',andClearto send,,,areusedto confiimthatthetwo un(sareread)rocommunica(e. TheRS232skndardspecifie\connector r\Des.sienal name...pin num,bers. aodvologes.In pracdce. lhenS_ZlUrtana"ra*" li'rpoL;.?rl any seial interfaceastongas oneunir acrsas a Dfe anatfreottrer asa OCil n iwo DTE units needto interfacewirh eachother-for e*"-pl", a pC ro pC_;s;;;i"j a cablecalleda rrullmod€mor crossover cableis use<]. RS 232is comm."t;;;;; thecontrolfield whentwo unitsneedto exchangedata_for example, to conieci a pi to a local controlunit for thepurposeof downloadingu n"* ot p.og.u., *_ittuJ tiatedin Figure2.12(b). "ont RS-232serialdatatransferis somewhatmorecomplicatedthanparallel datatrans fer, but it offersadvantages suchas two-wjrecommunications anda universallv accepted inferface.Thehardwareto handleserialdatais standardized, readityavaitab/. andreliable. a :HAPTER2 =8,;re2.12 RS-232 2 3 5 6 20 7 DCE 2 3 Oaiaset ready 5 6 20 7 Computer =_ Modem t' ].,. 4 .] (a) lnterfacebelweendatatermjnalequipment (DTE)anddatacommunjcalion equipmenl(DCE).Serialdalaaretransferred on pins2 and3;the othersignats conlrol COIVport(DTE) {DCE) (b)Usingan RS-232seriatcable10connecta pC ro a contrcer Probably*le most commonuseofsedal datais in networking. More andmore,net works are being usedto interconnectall the units and device;in the conrrolsy;tem. Network cabling differsdepenalingon the type of Iocal area network (LAi), but most usethe generalized bussysremdiagmmmedin Figure2.13.Typically,eachunit on the net has a uniqueaddressnumberand also aaa.essaetecti# ci."riit y' Wfr"n one unir wantsto talk to anolherunit, ir filst broadcaststhe address ofth; unit its wantsto talk to (serially,ofcourse,on the signalwire) andthen sends lhe data(seri_ CONTROL TO MICROPROCESSOR-BASED INTRODUCTION Figure2.'13 43 intefacemodule ally), which consistsof somenumberof bytes.All units on the net will receivethe addiess,but only the inteDdedreceiverwill activateand tben read in the data.The interface betweenthe network cable and the PC is done through a commercially availableinterfaceexpansioncardcalleda networkinteface card (NIC). Other devices on the net, such as control units, would require a special interface circuit. which may bebuilt in or availableas an extemalmodule.Control systemnetworksarediscussed fufther in Chapter12. 2.4 INTRODUCTIONTO CONTROLLER PROGRAMMING It is beyond th€ scopeof this text to presenta detailed discussionof how to program a micrcprocessor in machine language.Stiil, it is useful to investigatein a geneml way what the software must do. A digital con oller is a computer operating in real time. This meansthat tr€ pmSram is running all the time-repeatedLy taking in rhe ne\uest sensordata and the calculating a new outputfor the actuator. The basic structure of a controller program is a loop. [n a loop sftucture,the same sequenceofinstructionsis executedover and over again,and eachpassthroughthe loop is caliedan iteration, or scafl Figure 2.14 showsa generalizedcontro]lerprc$am, and an explanation of the program follows: L The program rcads in the set-poinl data (recall that the set point is the desiredposition of the controlled vadable).This data could be rcad in from an input port or ftom memory. CHAPTER2 Figure2.14 Read in set Point data Subtractto get eror , Sendoulpulvalue i nme delay(oflional) )l (from a sensor)the actualvalue of the con2. The program diEcts the computerto rcail rolled variable. po-tnllo gel lj)e efior l. The actual dala are subtractedfrom the set a new aclualorconuol slgnar' 4 Basedon the enor da!4 the compulercalculales 5. The new ouqnrt is sent to ihe actualor' agarn' 6. The pmgrams looPsback to step I and starts ovel passdrougb lhe loo! deretmine' The dme il Lakeslor tbecompuErro exwuteoDe mte) ll ous rnFrvat rs -nog.hterval betweeninput readbgs ftnowD as fie sampling lhe dme \ariable"is tay Dotgetan accumtepicnxeol whal tbecontrolled ;..otpr"t .o be loopcan E\ecudonoffie o* b"ot"r i I lo;a discussionolatiasingr' '"r,irl1* the progmm ln otheriruau-"lfi.*oiuy .p".iryine a laslercompuleror strearnlininS pause mighl be in\enedlo.'glve a exarnph anowalt.ru tioos.thecompulermuslpaLrse for a motorto splnoown' time lo aliow or un opa-tot,i-" ,o a^t a .ome adjustmeot is simpl} dme{elay loopsh rheprogramA time'deia} loop iift"o 0."" ur-f"..** ' up to some count to ;i*n*r loop wherethe computeris instmcted .i*toilitc, "pi*i"g ffirff#iili1Jtr!.: #:#5*x**t;:l*tli"ffir.*.ffi -rrtr| $e clcle dmefor lher)lainloop f*o t*.ft.*"|D tigure 2.l4).lhe efecl is !o slow lo someptedeerminedvalue rale o.* tiorce marchingof tle sample i*ri -eti. .Jr",-". midoprocessor pro_ efficienl one time, peopte thought that the best and most r,".; ;;; il;;;;; w-ould h fie prosrammer languase-lhar in assemulv Jirec"uv (calleo programs instructionsToday sophisticaled Lectly relecrthe mactrinelanguage BASEDCONTROL TO I\4ICROPROCESSOR NTRODUCTION .rmpiler.!) can conve( a programwdtten in a highlevel language,pdmarily C, into very efficient machinelanguage.Highlevel languagesuseEngiish-soundingwords and a set ofpoweful commandsto specil, simpleand complicatedprogrammingoperations witb a mjnimum of instruciions.Using a highlevel languageto write programs ibr a microprocessorollers big advantages.suchas more compactprogram Listing.ease documentation. Also. programswritof wdting equations,andmorecomprehensible to run on any model of microprocessor can be compiled ten in a high levellanguage CONTROLLERS 2,5 MICROPROCESSOR.BASED Single-ChipMicrocomputers(Microcontrollers) A miooprocessor by itself is not a computer To be functional, the microFocessormust be connectedto other integraledcircuits thal provide the memory and yO capabiiity.A microcontrolleris a computeron a singleIC, designedspecificallyfor controlapplicamemory(bothRAM andROM), VO pofts,and tions.It consistsofa microprocessor, possibly otherfeaturessuchas timers andADCS/DACS.Having the completecontroller on a single chip allows the hardwaredesign to be simple and very inexpensive. Microcontrollers are showing up iDcreasinglyin products as varied as industrial appli cations.home appliances,andtoys. In suchusesasthese,they al€ cailedembeddedcon' trollers becausethe controller is locatedphysically in ihe equipmentbeing controlled. The main dillerence betweenmicroprocessorsand microcontrollers is that microprocessorsare being designedfor usein microcomputerswheregreaterspeedand larger word size are the driving requirements,whercasmicrocontrollers are evolving toward reducedchip countby integratiDgmorehdrdwarefunctionson tbe chip. Most control applicationsdo not needthe 32-bit word sizeand500-MHz (megahertz)speedof the newermicroprocessors. Eight or 16bits and I MHz will workjusl fine in manyapplications,dndthe single-chipmicrocontrollercostsmuch less. andmicroconffollersconcernsthe Anothef differencebetweenmicroprocessors tendsto be rich in instructionsdealingwith movinstructionset.The microprocessor ing datainto and out of memory. The microcontroller has fewer memory-moveinstructions and more bit-handlinginstructions.The reasonfor the lack ofmemory-move instructionsis that the microcontrollertypically has only a small amountofRAM, which it usesonly as a "scratchpad."The additionalbit handlinginstructionswere they are so uselul;n controlsystemapplicalions.For example,in a includedbecause control system,eachseparatebit ofa parall€l outpul word might control a different device,suchas a motoror indicatorlight. The bit-handlinginstructionsallow the soft ware to tum one device easily on or off without affecting the others. The Motorola 68HC11is a popularS-bit microcontrollerthat has256 bytesof RAM, 8K ofROM, and512K bytesofEPROM (seeFigure2.15a).It alsohasfive 8 bit polts with built-in sedaldatatransferandADC capability.Anolhercommon8 bit / 15 CHAPTEB2 Figure2,15 Elock , P6iie.:,1 I--fPAOPA2 PA3-PA6 PA7 PBO PBT (s6raLport) (o thlADc nph) Also exlenalAddress and Dala bus (a) N4olorola68HC11 microconlroller block diag!am Also exlernalAddless afd Databus (b) lnrel8051 mcrocontroller bLockd agtam RAORAs (Canaiso be ADC inpuls) PIC 16C72mjcfo coilroller blockdiagram FBO-FB7 RCO-FC7 ( C a na l s ob e senarpon & iimer !nlerface) INTRODUCTION TO MICROPROCESSOR-BASED CONTROL 47 microcontrolleris the Intel 8051,which has 128b)'tesof RAM and4K bytesof ROM, four paralleldatapolts, anda sedalpolt (seeFigue 2.15b).For coffio1 applications, usuallyare adequate:ROM is usedto storethe control thesehardwarearrangemenrs program, and RAM is used as data registers and a "scrafch pad." The VO signal lines can usuallybe connecteddireclly to the microcontrollerwithout addilionalpo cir cuiny. Software is typically written in C+ or some other language (including assembly language)and then convertedinto machinelanguagewith a compiler or assembler prcgram.The machinelanguageprogramwould then be loadedinto the microcon trolier's ROM or EPROM. Another popular micloconfoller is the PIC from Microchip Technology.For example, the PICl6Cxx family of 8-bit microcontrollers is a low-cost, versitle product that hasfound wide acceptance[seeFigure 2.15(c)].Therc are a wide rangeof options, including ROM, EPROM, EEPROM, ADCS, Timers, and serial ports. The PIC usesa slightly differcnt architecturefrom the 68HC1i and 8051 in that the ROM (o. EPROM) that containsthe programconnectsto the CPU with its own l+bit bus, whereasthe iegular databus is 8 bits. Allowing I 4 bits for the program memory meansthat all instnrctions arejust one word long. The devicehasthreeI/O ports,but many ofthe I/O bits can be used in diflerent ways (such as for an orl/off switch or ADC input), depending on how they are programmed. Finally, anotherprcduct calledthe BASIC Stampftom Pamlla.\ Inc. is usually considered a microcontrollet allhough it is actually a very small circuit boad with a few ICs and pins. The whole circuit board plugs into an IC socket, as though il were an IC (seeFigure 2.16 ). Wlat makesthe BASIC Siamp somewhatuniqueis that it hasan onboard BASIC program interperater.A program can be written in BASIC on a PC and tl€n dirccdy downloadedinto the Stamp'sEEPROM through a RS 232 pot. No assembler or compiling operation is required. There are now oiher micrccon[ollers on the market that can be prograrnmedin BASIC. In summary, a wide vanety of microcontrollers are available. At the low end are the 4-bit models, which are morc than adequatefor appliancesand toys. Thesetend to be large-volume,low-cost applications.Eight-bit microcontrollers (suchas the 68HC11 and 8051 menlionedearlier)are very popularbecause8 bits turn out to be a convenient size for both numericandcharacterdata.At the high end, 16 and32-bit microcontrollers are availablefor control systemsrequiiing sophisticated,high-speed Figure2.16 BASIC Stamp nodule(BS2Ic). .$ 2 CHAPTER avionics,or calculatingpowerfor suchapplicationsascomplicatedservomechanisms. processng. image Single"BoardComputers computersbuilt on a Sitrg€'board computers are off-the-shelf microprocessor_based butin gensingleprinted-circui!card(Figure2.17).Theycomein manyconfigurations, suchastheZilog 280, the IntelxS6lamilt the eraltheyusea standadmicroprocessor Motorola68000,or a microconlrollerThey alsoincludememoryICs (bothRAM and RoM),l/O capability,andperhapsspecialinterfacecircuitssuchasADCSorDACS by major nicroprocessorproduceNsuchas Single-bodrdcompulersaremanufactured SomesingleboardcomIntel and Motorolaas well as manyolhersmallercompanies. of putersare desjgnedto plug into a PC as an expansioncard.The obviousadvantage andboard-testing boardis thatit eliminalesdesign_ usinga rcady mademicroprocessor time. This is paticularly important in small volume productior or one of kind systems. ProgrammableLogic Controllers A programmable logic controller (PLC) is a self containedmicroprocessor-based unit, designedspecifically to be a controller. The PLC includes an yO sectionthat can Fig|.lre2.17 .. il ! i!n m!.d I *dr1;r.ir! "r ,iarrra. t &91{d.., CONTROL TO NI]CROPROCESSOR-BASED INTRODUCTION 49 intedacedjrectly to suchsystemcomponentsas swiiches,relays,small motors,and lights. Developedin the late 1960sto replacerelay logic controllers,PLCShave PLCScomein motioncontrolapplications. evolvedto be ableto ha dle sophisticated varioussizesandcapabilities;Figure2.18 showsa selectionof PLCS.The big difi:er in this sectlonis thatthe PLC has encebetweenPLCSandthe otherdevicesdiscussed power built i o a packagethat hasbeenruggedi porls, and supply the microprocessor, is zedfof an industrialenvironment.Installation vefy easybecausein manycasesthe sensorsand actuatorscan be connecteddircctly to the PLC- Once installed, the micrc_ processorprogramis downloadedinto the PLC from somesourcesuchas apersonal computer.The PLC manufacturerusually supplies software to facilitate the program ming operation.This softwareallows the userto write a programwith line-byline instructions,or it can converta relay logic-wiring diagram(ladderdiagram)directly Figure2.18 (Allen-Bndley 50 CHAPTER2 into a PLC program. Multiple PLCSin a plant can be networked so the individual units can be monitored and programmedfrom a single station. This is a form of distdbuted computer control (DCC) discussedin Chaptor 1. PLCs are discussedin detail in Chapter12. Personal Computers Usedin Control Systems The availabilityofrelatively low-cost,off-the-shelfpersonal computers (PCs)has madethem an attractivealtemativefor small, one-of-kind confol applications.control system software packagesare commercially available for the PC that run under DOS and Windows. Theseprcgrams are adaptableand allow the user to tailor the software to fit the control application,essentiallytuming a PC into a PLC (aithoughnot as rugged).Most of thesepackagesuseinteractive graphicsto link animation with changing processvalues.Someprogramshaveprovisionsto mathematicallysimulatethe processbeingcontrolledto help optimizethe controllercoefficients. A standardPC comeswith €xpansion slofs, which are circuit-cald connecton emanaring frcm he motherbodrd(main board) of the computer.E4)ansion cards plug into ihese slots and foIm a bridge betweenthe compuier and the outside world. Many dif ferent types of interface cards are available, such as VO seial and parallel datapors, Figure2.19 Muiti-function lO boaJd. includesADC. DAC, and digital LO. (Coulresyof OmegaEngineering,Inc.) INTBODUCTION TO MICROPROCESSOR,BASED CONTROL 51 ADCS, DACS,and computer-controlledoutput relays, to name a few Figure 2.19 shows an example of a'l interface expansioncard. Histodcally, data-acquisitionand controi functions were kept separate.Controllers ran the process,and other insfuments measuledand recorded the iesu]t. The concept of havinga singlePC performbolhtasLs\eem\ logical:afler.rll.the pC cdnuseir. computingability first as the controllerandthen tabulatesystemperfomancedata. These data can be siorcd on disk and/or displayed on the moniioi. A potential problem may arisebecausethe contoller must operatein real time. If a computeris to control a processandmonitor it at the sametime, the alata-rcduction process must not take so long as to interferewith the control duties;a connol rcsponsecan't wait. One way to overcomethis problem is to divide the control and data-acquisitiontasks amongmultiple processors, Using the PC as the mastercomputer,a separatemicroprccessoron an expansionca.d canperfom datacolleclion uninterrupted.one type of yO controller cardhas slots for threesmallerboads. Thesesmallet boardshavevatious combilations of analogand digital yO ports and counter-timers.Someboardsare available with solid-staterelays, which can be usedto directly control AC andDC motors. A rc with tO expansioncardsoften costslessthan a stand-alonecomputedzedcon tloi system.The cardsdo not needa separuteenclosureand use the pc's power supply, keyboard for input, and monitor for display.Also, using a standardPC meansthat plogiams canbe developedon anothercompatiblecomputer,eliminating processdowntime. Numerous manufacturersare selling iugged PCs that can survivo in haish industrial environments.Thesecomputerstypically use a membmne,typekeyboard(the keyboard appearsas one continuoussheetofflexible plastic)and havesealedcasesand filte$ covering the air vents.Somemodels of thesecomputersare rack mountableand powerluppl. \ontainlheiro$ n balter)-backup SUMMARY A micrcprocessor is a digital integated circuit that peforms the basic operationsof a computer.Microprocessonareusede"xtensively asthe basisof a digikl controller Digital control systemsare advantageous becausedigital data can be tmnsferredand storedvirtually error-free,andthe contml stmtegycaDbe changedby simply reprogramming. A computerconsistsoffourbasic functionalunits:(1) the CPU (microprccessor), which executesthe programmedinsfuctions andperfoms the calculations;(2) the memory,which storesihe programand data;(3) input; and (4) output.Inpuvoutpu! interfaces the computer to ihe outside world. A microprocessor,basedcomputerinterconnectstheseunits with threegroupsof signalscalledbuses.The addressbuscarrjes the addressofthe datato be processed. The databus caries the data,andthe con[o] bus carriostiming and control signals.Computershandle data as groups of binaty bits. Many microprocessorbasedcontrollers handle data in 8-bit gloups called a byte. A microprccessorhas a set of instructionsthat it can execute(called ihe instruction set).Each instruction is identified by a digital code called the operationcode (oP.code). 52 2 CHAPTER A program consists of a list of ihese op-codesstored in memory Tbe micrqro6(f automatically fetcheslhe instructions ftom memory and executesthem. one bt oEA digital conrroller may havetwo kinds of data intefaces: paiallel and senal-Tbe parallel interf-ace is the most straightforwardsystem,where all 8 bits are sentat fte sametime on eight sepantewires. In the serial inteface, datais sent 1 bit after the otber on a single wire. Serial data transfer is better for longei distances Many control systemsusecomponentsthat require an analogsignalinterface; therefore, the signals to or from the digital conuoller must be convened with an ADC (analog-to-digital converter) or a DAC (digital to-analog converter) Both circuits are avaiiablein IC folm. The digital controllerprogramhasa siandardformat.First, it readsthe setpoint thesevaluesto determineihe systemenor Based andsensorvalues,Thenit subtracts the on lhe error value, it next calculates appropriateactuator responsesignal and sends it out.Thenit loopsbackto the beginningof the progmmandexecutesthe samesetof instructions over and over, Microprocessorbasedcontrollerscomein a numberof standardforms.A micro_ memory,and inpuvoutputall on a singlelC. A controllerincludesa microprocessor, computet assembled single-board computer is an off{he-shelf microprocessor_based programmable logic controller(PLC) is a selfonto a singleprinled circuit board.A containedunit specificallydesignedto be a controller.A personalcomputer(PC)is a generalpurpose,self-containedcomputer;however,with the addilion of interface expansioncards, a PC becomesa very adaptableand cosFeffectivecontroller. GLOSSARY usedin accumulator A tempomrydigital datastorageregisterin themictoprocessor operalion\. dnddatcmoving mrn) mrlh.rogic. converter. ADC Seeanalog-to-digital the locationof I byle of datain memoryor a spe_ address A numberthatrepresents port. cific input/oulput to memoryandyO addressbus A groupofsignalscomingfromthemicroprocessor ports,specifying theaddress. ALu Seearithmeticlogicunit. andlogi arithmeticlogic unit (ALU) Thepaltof theCPUthatperformsarithmetic cal opemlions. ananaanIC) thatcanconvert converter(ADC)A d€vice(usually analog-to-digital log voltageinto its digital binaryequivalent INTRODUCTIONTOVICROPBOCESSOB-BASEDCOI\TBOL 53 assembly language A computerprogmmwrittenin Drnemonics, whichareEnglishlike abbrevntions for machine-code instruclioft. baud Therateat whichthe signalstatesarechanging;liequentlyusedto mean"bits per second," bjt Thesmallest unitof digitaidata,whichhasa valueof 1 or 0. byte An 8-bitdigitalword. central processingunit (CPU)Thecentralpan ofa computettheCPUperforms all calculations andhandles thecontlolfunctions of thecomputer control bus A groupoftimiDgandcontrolsignalscomingfromthomicroprocessor to memoryandyo pots. crossovel cable Sr" null mod€m. CPU Seec€ntralprocessing unit. DAC Seedigital-to-analogconverter. data bus A groupof signalsgoingto andfrom themicroprccessor, memory,andVO ports.Thedatabuscaries theactualdatathat arebeingprocessed. data communicationequipment(DCE)Oneof twounitsspecified by theRS-232 (for standard serialdatatransfer);theDCEis usuallya modem. dataterminalequipment(DTE)Oneoftwo unitsspecified by theRS-232 srandard (for serialdatatransfer).TheDTE is rsually the computer DCE Seedala communication equipmenl digital-to-analogconverter(DAC)A circuitthattranslates digitaldataintoananalog voltage. prcgramor datainto a computei(ftom another download To transfera computer compu@r), DTE Seedata terminal equipment. embeddedconttollei A srnallmicroprocessor-based contlollerthatis permanendy installedwid n themachineit is controlling. expansioncard/slot An expansion cardis a printedcircuitcardthatplugsinto an (PC).Theexpansion expansion sloton themotherboard of a porsonal computer card usuallyinterfacesthePCto theoutsideworld. letch-execute cycle A computercyclewheretheCPUfetchesaninstructionandthen Inpuvoutput(UO)Dataftomtherealwoddmovingin andoutof a computer YO S€einput/output. 54 CHAPTER2 thata panicularmicroprccessor is instfuction set Thesetofprogramcommands designed to recognize andexecute. programb€ingexecuted iteration Onepassthfoughthecomputer by thedigitalconthe set+oint and sensor data and caiculates the outputto troller; eachiteration"reads" ihe actuator, LAN Seelocalarcanetwork. leastsignilicantbit (LSB) Therightrnost bit of a binarynumberCanalsomeanthe smallestincrcmentof change. Iogicalvariable A singledatabit in thosecaseswherea singlebit is usedto rcpresentanon-off switch.motoron-offconrol. andsoon. with Iocalareanetwork(LAN) A systenthatallowsmultipleunitsto communicate (dme inrerconnecrion wire. eachorherall sharing lhe LSB s€dleastsignificantbit. mach,nelanguageThesetof operation codesthata CPUcanexecute. storcsdigitaldata.Memorydatais storedas memory Thepartofthe computerthat bytes,whereeachbyteis givenanaddress. memory-mappedinput/outpLrtA systemwherevo portsaretreatedexacdylike memorylocations, memory, and microcontroller An integrated circuitthatincludesa microFocessot inpuroutput;in essence, a "computeron a chip." microprocessorA digitalintegmted circuitthatperformsthebasicoperations ofa computerbut rcquiressomesupportintegratedcircuitsto be functional. most significantbit (MSB)Theleftmostbit in a binarynumber. mnemonic An Englishlike abbreviationof anopemtioncode. modem A circuitthatconvertsserialdatafrom diqitalform into tonesthatcanbesent throughthe telephonesystem. MSB Seemostsigdficsntbit, nonvolatlle memory ComputermemorysuchasROMthatwill notloseits datawhen thepoweris turnedoff. witheachoiher(rre null modem A cablethatallowstwoDTEunitsto communicate RS-232). to idenoperationcode (op-code)A digitalcodewordusedbythemicioprocessor tify a particularinsffuction. parallel intertace A typeofdatainterfacewhere8 bits enterol leavea unitat the sametime on eisht wircs. TO ]\iIICROPROC@ INTRODUCTION PC Seepe$onal computer. genemlpurpose self_contained' personal computer (PC) A microprocessor-based, computer (usuauy refers to an IBM or compatible computer) PLC S?eprogrammable logic controller. port has an port The pan of a computerwhereI/O data lines are connected;each address. registerin a computerthat holds the program counter A specialaddress-holding ad&essof the nextinstructionto be executed programmable logic controller (PLC) A rugged,self containedmicroprocessorbasedcontrollerdesignedspecificallyto be usedin an industrialenvironmenl RAM Sedrandom-accessmemorY. a memory random'access memory (RAM) Sometimescalledread/write memory' RAM losesits ou| wheredatacanhe written in or read arrangemenlusingadalresses contentswhenthe poweris turnedoff. memory'but it read-onty memory (ROM) Sirnilarlo IiAM in rhat it is addressable its dalawhen comespr;programmedanalcannotbe wilten into; also' it doesnoi lose the power is turned ofi to memory read/write (R/W) line A conlrolsignalthatgoeslrom the microprocessor thal the dali reaf time Refersto a comp ter mat rs processinglata at the sametime by the syslem are generated the enor that occursbecausedigital resolution In digital-toanalogconversion, canonly havecefain discfetevaiues. data ROM Se€read-onlymemory. standardihat specifiesvoltagelevelsand RS-232standard A seial datatransmission device) signal protocol between a DTE (computer) and a DCE (modem or other BAV Sesr€ad/write line. data sampling rate The timespl3rseconda digiralcontrollerreadsthe sensor scan Se€iteration. serial inte{ace a singlewire. A type of intedace where data are transferred 1 bit ailer the other on onlo computerassembled single-board computer A premademicroprocessor-based a singleprinted-cifcuitcard. 56 CHAPTEB? wherethe computeris givena "do-noth_ time-delay loop A progatrming techDique to somelargenumtterfor thePurposeof delayingtime' ing" job suchas_cormtin! UART Seeuniversalasynchronousr€ceivertratrsmitter' purpose inte_ universalasynchronousreceivertransmitter (UART) A special versa' and vice format parallel to sedal gratetlcircuit that conve(salatafrom the volatile memory ComputermemorysuchasI{AM that wil lose its datawhen poweris tumedof4' word A unit of digilal datalhata particularcomputer uses:cornmon\ ord sizesaJe 8. 16.and32birs. E)(ERCISES Secaion2.1 and 1. Briefly descdbe the functions of the AIU' confiol unit, CPU momory' input/oLrtPut. (Specify 2. V/hat stepsdoes the microprocessortake to rcad data at address 1020? your answer') the actions of the adakessbus and data bus in bus' ^id control bus brs' data d/d/ess alefine 3. Briefly num4. Use the methoalshownin Example 2.1 to find the decimal value of the brnary ber01011101. the binary 5. Use the methoal shown in Example 2.1 to find the decimal value of number11011010. Section 2.2 6. wlat is a microFoce ssor instraction set, aldhow is it different from a high-level latrguage such as BASIC? 7. A certain nicroprocessor has a simple instruction set shown below' INSTRUCTIONSET ExDlaation Op-code l{a1t the mrcloprocessol 16 Add next byie to accunmlalorc6t SubEct lext byte frcm accunulator' D5* Itrcrement the accuulato! 3C Decrerent the accunulator3D Move lhe nert byte into the accumulator' 3E* 'These ins"flclions use tuo bli"eE' aftertheProgramshowllbelowwasrun? what numberwouldbein theaccumulator INTRODUCTION TO lllICROPROCESSOR-BASED CONTROL PROGRAIi4 Add"ess 001 002 003 004 005 006 0p-code 3E 05 D6 a2 :c 76 Section2.3 E. Temperaturevaluesfrom -20"F to 120"F arc input data for a micropmcessor com_ puter Are 8 bits sufEcient?Ifso, what is the resolution? Explainrhe luncrionol he fo|,owingtparutt?l ljam poft and,"riat dan pon. l.9. U . s - e n a t d aal rae\ r n r a r1 2 0 0 b p s u s i n g l h e l o r m a r o f F i g u r e 2 . l l . w i { h o n e s r o How long wouldit taketo send10OO bytesofdata? 11, An 8 bir DAC has a referencevoltage of 9 V The binary input is 00 00. Find the analogoutputvoltage. 12. The^b-inarydataftom the computerin a cetain application are expectedto go from 00000000ro or ) 00t | | I I L Thesedaraare|}leinpurof a DAC. The dnalo; oLbur rhouldgo 0.5 V find $e DAC reference!otlage nece,.aryLomakerhis iaoojn 13. An 8-birADChasa rererence !ottage of t2 v u"aun-rtoe t"pur j.i tiFi;d thebinaryoutput. "r 14. Thebinaryoulpurof anADC shouldhavethe mnge00000000_ 11 t 111cone_ spondingto aninput of 0-6V Find thenecessary rcfetencevoltage. Section 2,4 15-, U\thatls real-timear!p,'jrg, andis it necessary for controlsystems? 16. De.cribedrebdsic.leps in a conrolprogram \can(toopj. | /. Ar (omeporntjn lheprogram il js de\iredto harethecompuler wait5 ! lor an operalor re.pon\e.How\ ouldrhisdelaybeaccomplished in softwarel _^ t6. A program conrains 150jnsFucdonq. andl})eaterage e\ecuiion rimeperinstruc_ tionis 2 ps.Findthesample rateof thisprogam. Section 2,5 19. What]s a micmcontroller,ar,d\that arc somediffercncesbetween a micrccon_ troller anda microptocessot? 20. What is a programmable toeic controller? You \vant to use a personalcomputer to contlol a simple robot arm. The arm has two Joinls, an elbow and a wrist. Eachjoint has a DC motor and a posirion sensor that outpursa DC votrage.you atreaalyhavea ,'plain vani[a,,pC;make a lisr of what you would need to acquire to make this svstem work. 22. Compareand conrrasrfie following:a ,fli roprocesror.a nicmconrmller, a pro. grammable logic contfoller, anda personal computer.