Unit I To Uiibeddud System: Objective
Unit I To Uiibeddud System: Objective
OBJECTIVE
Th" embeddedsystem is introducedin this unit with basic I processor, The processor and soltwarerequirements. hardware may be a generalizedprocessoror specific for a particular embedded system. The software feature also ranges from a particular machine dependentimplementationto the high level implementation. language
1.I DEFINITION
with An embeddedsystem is one that has computer-hardware in it as one of its most importantcomponent. softwareembedded system for an application or It is a dedicatedcomputer-based systemor a part of a product. It may be either an independent larger system its software usually embedsin ROM (Read Only memoryas in a computer. Memory) it doesnot needsecondary 1.1.1Introduction A systemis a way of working, organizingor doing one or many tasksaccordingto a fixed plan, program,or set of rules.A system in which all its units assemble and work is also an arrangement together accordingto the plan or program. Let us examine the following two examples. Considera watch. It is a time-display system. Its parts are its and batterywith the beautiful dial, chassisand hardware,needles strap.Thesepartsorganizeto showthe real time everysecondand continuouslyupdateihetime everysecond. updatesthe display using three needles The system-program It follows a setof rules. Someof theserules are after dachsecond. as follows:
1.2
Embedded
(i)
positionaftera minute' to same that it rturns that it A long needlerotateselerl minutd such (iii) afteranhour' position ' to same rturns such that it (iv) A short needlerotatesevery hour. hours' positionaftertwelve to same returns ttqT to the sameinclinations All three needles (v) daY' each aftertwelvehours an automatic clothesConsidera washingmachine'It i$ partsincludeits status ,siii-'ciq hardware The important ";;i;.tstem. anO-^.aiatsfor user-defined display panel, ,h" and a motor to rotateor spin' its power supply for programming, a iolenoid valve control unit, an rnnei *ut"'level sensor' drain out. in unJ*otter valve for letting water ffi;;;;; Thesepartsorganretowashclothesautomaticallyaccordingtoa bYa user' program Preset placedin a is to washthe dirty clothes The system-program andstages' steps oi,pinr in pre-programqted tank,whiohrotates rulesare as follows:(i) It follows a setof *fuJ' Sot" of ifrese strictlyin thefollowingsequence' Followthe steps to a programmed the motoraccording StepI: Washby spinning period , and outthedirty water II: Rinsein freshwaterafterdrainins Step waterin programmed tit;'ii th;-tytt tn is noi rinse a second mode. saving spin fast the completely' StepIII: After drainingout t-he.later, out drying by centrifuging motor for a progr;;?d periodfor waterfrom theclothos' by a blinkingdisplay'Sound status StepIV: Showthe wash-over washcycle is complete. the ararmro, u minulJ'i" ,rgn"r that ihe (iii) In of the system' stage thJ process (ii) At eachstep,Oisptay G remainingpart of the caseof * int.*rpt"i'oi, #tu,t only
(ii)
*"n
1.1.2Architecture
Lput DeviccsInterfacing / DeciceCircuits
DataMcmory
ts*'"I
--l
I I
|l"*qp,_l Cottrollers I I
I P."fl'tPo," I
Figure.L I Cornponents .,J'anewbecldecl System Summary The embeddedsystem is a sophisticatedsystem consisting of severalhardwareand software components, and its design may be several times morqrcomplex than ihat of PC and the progrims runningon a PC.
1.2 Classifrcation of EmbeddedSystem Wecan classifu embedded systems intothree types asfollows
l. SmallScale Embedded Systems' 2.MediumScale Embedded Systems 3.Sophisticated EmbededSystems I. Small ScaleEmbedded Systems
1.4 Embedded Systems 'o These systems are designed with a 8 bit or 16 bit microcontroller; they have little hardware and software complexities and involve board-leveldesign. They may even be battery operated. o When developingembedded softwarefor these,an editor, assembler and cross assdmbler, specific to the microcontroller or prccessor used, are the main programmingtools. o Usually, 'C' is used for developing these systems. 'C' program compilation is done into the assembly, and executable codes are then appropriately located in the system memory. The softwarc has to fit within the memoryavailable. 2. Medium Scale Embedded Systems o These systemsare usually designedwith a single or few 16- or 32-bit microcontrollers or DSPs or Reduced InstructionSetComputen(RISCs). o Thesehave both hardwareand softwarecomplexities.For complex software design, there are the following programming tools: RTOS,Sourcecodeengineering tool, Simulator, Debugger and Integrated Development Environment(IDE). o Softwaretools also provide the solutionsto the hardware complexities. An assembler is of little use as a programmingtool. These systemsmay also employ the readily available ASSPs and IPs for the various example, for the bus interfacing, functions-for encrypting, deciphering, discrete cosine transformation TCP/IP protocol stackingand and inversetransformation, functions. network connecting 3. Sophisticated Embedded Systems o Sophisticated haveenormous hardware embedded systems and software complexities and may need scalable
processors or configurableprocessors and programmable logic arrays o They are used for cutting edge apprications that need hardware and software "o-d"ri-gn and integration in the -are final system; they constriined by !owe19r, ' the processing speeds availabre in their hardwareunits. o Certain software functions such as encryption and decipheringalgorithms,discretecosinetransrormation --ftoio.or ano the hardwareto obtain additional speeds Uy .uuing tirr. Some of the functions of the hardware,"rour".r"in th, system arealsoimplemented by the,ot*ui". 1.2.1 skills required for an Embedded system Designer An embedded systemdesigner hasto deverop a productusingthe available toolswithin the givenspecificatrons, costandtime frame. I. Skillsfor Small Scale EmbeddedSystem Designer The following skiils are needed in the individuaror team that is developing a small-scale system. Full understahding of microcontroilers with a basic knowledgeof computer architecture digitarerectronic design, software^ engineering, data comlunication, "ontiot engineering, motorsand actuators, sensors and measurements, .analog electronic design andIC design andmanufacture Specific skills wiil be needed in specific situations.For example,contror engineeringknowredgewirt be neededfor knowledge will be needed when deiigning td interfaces. Skillsfor Medium Scale Embedded System Designer
il,g"
syrt;;
Embedded
'C'-programming and RTOS programming and programmodeling skills are required to designa medium-scale embidded- system. Knowledgeofthe following becomes critical.
Tasks andtheirscheduling by RTOS. Cooperative preemptive and scheduling. il iii Interprocessor communication functiois. iv Use of shareddat4 and progrumin the critical sections andre-entrant functions. v Useof semaphores, mailboxes, queues, andpipes. vi Handlingof intemrpt-latencies and meeting'task deadlines. vii Useof various RTOSfunctions. viii Useof physical andvirtualdevice drivers. A designer musthaveaccess to an RTos programming tool with ApplicationProgramming Interfaces (ApI;) for the spicific microcontroller to be used.sorutions to variousfunctionstike memoryallocation, timers,devicedriversand intemrpthanding mechanism arereadilyavailable astheApIs of theRTdS. 3. Sbills Embedded SystemDesigner for Sophisticated o A team is needed to co-design and solve the high level complexities of thehardware andsoftware design. o An embedded system hardware engineer shouldhavefull skills in hardware unitsandbasicknowldge of ,C', RTOS andotherprogpmming tools. o Software engineer shouldhavebasicknowledge in hardware and a thorough knowledgeof .C', RTOS and other programming tools. A final optimumdesignsolution is then obtainedby system integration. Sumnery Theembedded system mayb" classified into threemaintypesas o Smallscale embedded system designed with a g bit or 16 bit microconholler.
Sophisticated embedded systems needscalable processors. These three types have different software and hardware complexitiesand usedifferentprograrnming tools. According to the type of embeddedsystem the skills requiredby the designer differs.
1.3 PROCESSOR
A processor is the heart of the embedded system.For an embedded designer, system knowledge of microprocessors and microcontrollers ii a prerequisite. 1.3.1Processor in a System A processor hastwo essential units O (i, ProgramFIow ControtUnit (CU) Execution Unit (EIl).
ThecU includes a fetchunit for fetching instructions from the memory. The EU hascircuitsthatimprement the instructions pertaining to d{a transfer operations anddataconversion from oneform to another. TheEU includes theArithmetic andLogicalunit (er.u) and also the circuits that executeinstructionsfor u p.gru, control- task, say, halt, intemrpt,or jump to anothei Jt of instructions. It canalsoexecute instructions ior a call or branch to another program andfor a call to a function. A processorruns the cycres of fetch and execute.The instructionqdefinedin the processor instnrction st,arexecuted in the sequence that they are fetched frorn tlre- r"t"".l. a processor is Embedded Systems mostlyin theformof antc ctrip. An embeddcd system. processor chip or core can be one of the following.
1.8 Embedded l. GeneralPurpose Proces.sor (GPP) a. Microprocessor. b. Microcontroller. c. Embedded Processor. d. Digital SignalProcessor (DSP). e. Media Processor. 2. Application Specific System Processor (ASSP) as additionalprocessor. 3. Multiprocessor system using General Purpose processors (GPPs) and Application Specific (ASIPs) instructionPrd,cessors (s) 4. GPP core or ASIP core (s) integratcdinto eitheran Application Specific IntegratedCircuit (ASIC), or a Very Large ScaleIntegratedCircuit (VLSI) circuit or an FPGA core integratedwith processorunit(s) in a VLSI (ASIC) chip. For a systemdesigner, the following are importantconsiderations when selectinga processor l. 2. 3. 4. Instructionset. Maximum bits in an operand Clock frequency in MHz Processingspeed in Million Instructions per Second
1.9
The earlier generation microprocessor's fetch-and-execute cycle was guided by clock frequency of the order of MHz. Processors now operate at frequency of 2 GHz. One example of an older generationmicrocontroller is Intel processor), 8085(8-bit Intel 8086or 8088(16-bit processor). An example of the new generation 32- and 64-bit microprocessorthe classic Pentium series of processorsfrom Intel. These have superscalar architecture. They also possess powerful ALUs and FloatingPoint Processing Units (FLPUs).An example of the use of Pentium III operating at I GHz clo.ck frequencyin an embedded systemis the 'EncryptionEngine'. 1.3.3 Microcontroller A microcontrolleris the most essential component of a control or communication circuit.A microcontroller is a single-chipVLSI unit (also called 'microdomputer') which, though having limited computational capabilitiespossesses enhancedinputoutput capabilitiesand a number of on-chip functional units. Microcontrollers are particularly suited for use in embedded systems for real-timecontrol applicationswith on-chip programmemoryanddevices
(MrPS).
5. Processor ability to solve the complex algorithms used in meeting the deadlines for their processing. 1.3.2Microprocessor A microprocessor is a single VLSI chip that has a CPU and may also have some other units for examples,caches,floating point processing arithmeticunit, pipelining and super-scaling units) that are additionally,presentand that result in faster processingof instructions
microcontrollers, often cailed embedded. processors, are required. When a microcontroller or microprocessor is specially designedsuchthat it hasthe following capabilities, then tire term embeddedprocessoris preferred inslead'of microcontrotiei or microprocessor. l . Fast context switching and thus rower ratencies of the tasksin complexrealtime applications. 2. and thusno shared dataproblem. 1!9Ti" ALU operations a J. RISC coni for fast,morepreciseand intensivecarcurations by the embedded software. calculations for rear time image processing and for aerodynamics are two exampres where theie is u n"1a for fast, precise and intensive calculationsand fast context-switching. Important embedded processor chips for embeddeJ ,yJr* -Jbelongto the following threestream,bf furili.r, Stream l: ARM familyARM 7* andARM 9*. Stream2: Intel famity i960, Stream 3: AMD family 29050. 1.3.5 Digital Signal processor (DSp) A digital- signal. processor (DSp) is an essentiar unit of an embeddedsystem for a rarge number of appricationr n*oing -*ug" processing of signals. Exemplary applicati'ons ur. in processiqg,multimedia, audio, video, fiDTV, DSp modem and telecommunication processing systemi. A DSP provides fasq discrete-time, signal_processing . instructions. It hu: V:ry Large Instruction i/""i tVilWl
1.3.4Embedded proccssor for a Complex Syotem For fast,precise andintensive carcurations and for comprex real time appticarions,drC ,b;;;;il; and microprocesson inentioned abovedo^ryt suftice.en "Lmonics warfaresystem, for exampte,an W".i"J *o Control System ljlr** (AWACS),whicharso absociater *.iift r'dar, is anexampre of
Data(SIMD) instructions fast; it processes Discrete cosine Transformations DCT and inverseoir OpcD functionsfasi.
l.l2
Embedded
Inffoduction to EmbeddedS
6. Keypad interfaceand displayinterfacehandling. 7. ShortMessage Service(SMS) protocol-based messaging 'single For all these tasks, a processor does not suffice. Suitablysynchronized multiple processors are required Summary A general-purpose processoris used becauseprocessing by the known instructions availableat predefined Genera[ Purpose Instruction-Set results in fast svstem development A microprocessor is usedwhen large embedded software is to be locatedin the externalmemorychips. A microcontroller is used when the functional units like intemrpt-handler, port, timer are needed. An embedded processor is used when besides fast processing fast context-switching and atomic ALU operations are needed. o A DSP is usedwhen signal-processing functionsare to be processed fast. o An ASSP is used as an additionalprocessing unip'for running the application specific tasks in place of processing usingembedded software. Multiple processors are usedwhen a singreprocessor does not meet the needsof the different tasks that have to be performedconcurrently.
I.4 OTHER HARDWARE UNITS 1.4.1 Power Source and Managing the power Dissipation andConsumption
Most systemshave a power supply of own. The supply has a specific operationrangeor a rangeof voltages.various units in
l.l4
Embedded S
l.l5
a) 5.0V+ 0.25V b) 3.3V+ 0.3v c)2.0V+0.2V d) l.sv + 0.2v a l2y * o.2v suppry is needed for a.flashor __Additionally, EEPROM. systbmas J9-ltaseis applied^on the chips of an embedded followsThe flow of vortage andthe connections oepeno on tt, number of supply pinsprovided withintheprocessor prus thepins in the associated chips and circuits.The pins ur" in puirr, consisting of the suppryin andrhe groundrine.The foilowing points haveto betaken careof whireionnecting the suppry rairs .(lines): o A processor mayhavo morethantwo pinsof VppandV5s. This distributes the powerin all the iectionsandreduces interference between thesections. . power the (a) external llo llppty should separately driving ports (b) timersana1c; clock ani resetcircuits. clock and resetoircuitsneedto be specially designed to be free from any radio frequency interfer"n.r. in I/O devicemay dissipate morepowerthanthe otherinternal units of the processor. A timer may dissipate a constant powerevenin wait state. Hence, these threecircuitsare powered separately. o thereshourd be separate interconnections lrom the supply' for pairs of Vpp pins, Vss analog ground,analog .and reference and analoginput vortagerinJs,the ebc unit digital groundand otheranalogpartsin the system. An ADC needs stringent noise-free supplyinputs. certainsystems do not havea powersource of their own:they connect to an external powersupplyor arepowered by the useof chargepumps.(l) NetworkInterfaceCara 6NtC; unCCrupni.
charge pumpconsists of a diodein the seriesfoirowedby a chargingcapacitor.Thp diode gets forward bias input frorn un external signal.
Acceleiator are examples of embedded systemsthat do not have their own power suppv and connectto pi power-supplylines. 1Z; A
An ernbedded_ srysteq may needto be run continuously, withou! being switchedoffq the systemdesign,tt erefor, is constrained by the needto limit powerdissipitionwhile ii is ru1njng.Total power :on:yption by the systemin ,unning, waitingandidle states shourd aisobe timited.ihe current n .o"d uv instarlt in processor the of an embedded system i"p."a"-' on ?! thestate andmodeolF" processor. The foilowing*, th; Gra values in six states of theprocessor. - . 50 mA whenonly the processor is running:that is, the processor is executing instructions. . 75 mA whenthe processor plusthe extemalmemories and chipsar9 i1,runningstate:that is, fetching and execution arebothin progress.
when only the processor is in stop state:that is, 15 f.A fetching and executionhave both stoppedand the clock has been disabled from ail structu'ral units of the processor. 15 mA when the processor plus the extemalmemories and chips are in stop state: that is, fetching and exd'oution haveboth stopped andthe crock diiabled from all system units. 5 mA whenonly the processor is in waiting state:that is, fetching and executionhave both stoppedbut the clock has not bepn disabled from the struciurar units of the processor, suchas timers. l-0 rnA when the processor, the external memoriesand the.chips are in waiting state.Waiting statenow means that-fetchingand executionhave bott stopped;but the clock has not beendisabredfrom the structurarunits of
l.l6
Embedded
the processor and the external I/O units and dynamic RAMs refreshingalsohashd stopped. 1.4.2 Clock Oscillator Circuit andClocking Unit(s) needsa The Clock is an importantunit of a system.A processor clocking various the controls clock The clock oscillator circuit. requirements of the cPU, of the system tirners and the cPU machinecycles.The machinecyclesarefor . Fetchingthe codesand datafrom memory . . and at the processor, decodingand exebuting Transferringthe resultsto memory
t.t7
1.4.4 Reset Circuit, Power-up Reset and WatchdogTimer Reset . Resetmeansthat the processor startsthe processing of instructionsfrom a startingaddress. That address,is one that is setby default in the processor programcounteron power-up. a From that address in memory, the fetChing of program-instructions startsfollowing the resetof the processor. . The resetcircuitactivates for a fixed period(a few clock cycles)and then deactivates. The processor circuit keeps the reset pin active and then deactivatesto let the programproceedfrom a default beginningaddress. The resetpin or the internalresetsignal,ifconnectedto the other units in the system, is activated again by the proceisor; it be comesan outgoingpin to enforcereset statein other sister units of the system.On deactivation of the reset that succeeds the processoractivation, a . program executesfrom start-up address.Reset can be activated by oneofthe following: a. An extemal reset circuit that activates on the power-up,on switching-onreset of the systemor on detectionof a low volt6ge. b. By a Software instruction or Time-out by a programmed timer known as watchdogtimer or a clock monitor detectinga slowdown below certain thresholdfrequencies dueto a fault. The watchdogtimer is a timing device that resetsthe systemafter a predefined timeout.This time is usually configured and the watchdogtimer is activatedwithin the first few clock cycles after power-up. It has a number of applications. In many embedded systems reset by a watchdogtimer is very essentialbecauseit helps in rescuingthe systemif a fault developsand the program gets stuck. On restart,the systemcan function normally.
ThE clock controlsthe time for executingan instruction.The or a clock circuit useseither a crystal (externalto the processor) or an extemal with the processor) ceramic (internally associated processor. to-the oscillatorIC attached . The crystal resonator gives the highest stability in . frequencywith temp drift in the circuit. . The interqal ceramic resonator, if available in a the useof the externalcrystal and gives irocessor, saves thoughnot very highly stablefrequency' i reasonable . The externallC-basedclock oscillatorhasa significantly higher power dissipation compared to the internal However, it provides a- higher processor-resonator. briving capability, which might be needed when the various circuits of embedded system are concurrently driven.
l.l6
Embedded
the processor and the external I/O units and dynamic RAMs refreshingalsohashd stopped. 1.4.2 Clock Oscillator Circuit andClocking Unit(s) needsa The Clock is an importantunit of a system.A processor clocking various the controls clock The clock oscillator circuit. requirements of the cPU, of the system tirners and the cPU machinecycles.The machinecyclesarefor . Fetchingthe codesand datafrom memory . . and at the processor, decodingand exebuting Transferringthe resultsto memory
t.t7
1.4.4 Reset Circuit, Power-up Reset and WatchdogTimer Reset . Resetmeansthat the processor startsthe processing of instructionsfrom a startingaddress. That address,is one that is setby default in the processor programcounteron power-up. a From that address in memory, the fetChing of program-instructions startsfollowing the resetof the processor. . The resetcircuitactivates for a fixed period(a few clock cycles)and then deactivates. The processor circuit keeps the reset pin active and then deactivatesto let the programproceedfrom a default beginningaddress. The resetpin or the internalresetsignal,ifconnectedto the other units in the system, is activated again by the proceisor; it be comesan outgoingpin to enforcereset statein other sister units of the system.On deactivation of the reset that succeeds the processoractivation, a . program executesfrom start-up address.Reset can be activated by oneofthe following: a. An extemal reset circuit that activates on the power-up,on switching-onreset of the systemor on detectionof a low volt6ge. b. By a Software instruction or Time-out by a programmed timer known as watchdogtimer or a clock monitor detectinga slowdown below certain thresholdfrequencies dueto a fault. The watchdogtimer is a timing device that resetsthe systemafter a predefined timeout.This time is usually configured and the watchdogtimer is activatedwithin the first few clock cycles after power-up. It has a number of applications. In many embedded systems reset by a watchdogtimer is very essentialbecauseit helps in rescuingthe systemif a fault developsand the program gets stuck. On restart,the systemcan function normally.
ThE clock controlsthe time for executingan instruction.The or a clock circuit useseither a crystal (externalto the processor) or an extemal with the processor) ceramic (internally associated processor. to-the oscillatorIC attached . The crystal resonator gives the highest stability in . frequencywith temp drift in the circuit. . The interqal ceramic resonator, if available in a the useof the externalcrystal and gives irocessor, saves thoughnot very highly stablefrequency' i reasonable . The externallC-basedclock oscillatorhasa significantly higher power dissipation compared to the internal However, it provides a- higher processor-resonator. briving capability, which might be needed when the various circuits of embedded system are concurrently driven.
l.l8
l.4.5 Memories In a system, there are Vbrioustypes of memories. They are as follows: o Internal RAI\4 of 256 or 5lZ bytes in a microcontroller for registers,temporary data and stack o o o Internal ROM/PROMIEPROM for about 4 KB to 16 KB of program External RAM for the temporarydata and stack Internalcaches
o EEpROM or flash o Extemal ROM or pROM for embedding software o RAM Memory buffersatthe pons o Caches (in superscalar microprocessors) Functions Assigned to the Memories in a System
1,4i.6 Input, Output and UO Ports, UO Buses and UO Interfaces o The systemgets inputs from physical devices(such as, for example,the key-buttons,sensorsand transducer circuits) throughthe input port. A controller circuit in a system gets the inputs from the sensorand transducer circuits. A receiverof signalsor a network card getsthe input from a communication system The system has output ports through which it sends output bytes to the real world. An output may be to an LED (Light Emitting diode) or LCD (Liquid Crystal Display) panel. For example,a calculator or mobile phone system sends the output-numbersor an SMS message to the LCD display.A systemmay sendoutput to a printer. An output may be to a communication systemor network. A control systemsendsthe outputs to alarms,actuators, furnacesor boilers. A robot is sent output for its various motors. Each output port is identified by its memory-bufferaddress (es) (called port address). The system sends the output by a write operation to the port address. There are also general-purpose ports for both the input and output (I/O) operations.For example, a mobile phonesystem sends outputas well as gets inputthrough a wireless communication channel. EachI/O port is also identified by an addressto which the read and write operationsboth take place. There are two types of I/O ports: Parallel and Serial. From a serial port, a system gets a serial streamofbits at an input or sendsa stream at an output. A systemport may get inputsfrom multiple channelsor may have to send output to multiple channels.A de-
ROM or EPROM
Storingeppticationprograms frorn wheretheprocessor fetches the instruction codes. Storingcodesfor system booting,initializing,Initial input dataandstrings. Codesfor RTOS. Pointers (addresses) of variousservice routines.
1.20
Embedded Systems
t.2l
multiplexer takes the inputs from various channelsand transfersthe input from a selectchannelto the system. A multiplexertakesthe output from the systemand sends it to anothersystem. A systemmight have to be connectedto a number of other devicesand systems. For networking the systems, there are different types of buses: for example, I2C CAN, USB, ISA, EISA andPCI. 1.4.7 Interrupts Handler A system may possessa number of devices and the system processorhas to control and handle the requirementsof each device by running an appropriate InterruptServiceRoutine (lSR) for each.'An intemrpts-handling mechanism must exist in each systemto handleintenuptsfrom variousprocesses in the system. Important points regardingthe intenuptsand their handlingby programmingare as follows: There can be a number of intem.rptsourcesand groups of intemrpt sourcsin a processor. An intemrpt rnay be a hardware signal that indicatesthe occurrenceof an event. A softwareintemrpt may arise in an exceptional condition that may have developedwhile running a program. The systemmay prioritue the sourcesand servicethem accordingly Certain sources are not maskable and cannot be disabled.Someare definedto the highestpriority during processing. The processor's current program has to divert to a service routine to completethat task on the occurrence ofthe intemrpt. The application program or scheduler is expeited to schedule and control the running of routines for the intemrptsin a particularapplication.
1.4.8 DAC (Using a PWM) and ADC PWM Supposea systemneedsto give an analog output of a control circuit f-or automation.The analog output may be to a power system for a d.c. motor or fumace. A Pulse Width Mod0lator (PWM) unit in the microcontroller operatesas follows: Pulse width is made proportionalto the analog-outputneeded.PWM for an 8-bit DAC inputs are from 00000000tq IlllIIII operation.The PWM unit outputs to an external integrator.and then providesthe desiredanalogoutput. ADC The ADC in the system microcontroller can be used in many applications such as Data Acquisition System (DAS), analog control system and voice digitizing system. Supposea system circuit. needsto read an analoginput from a sensoror transducer If convertedto bits by the ADC unit in the system,then thesebits, can also give an output.This providesa control after processing, for automationby a combineduseof ADC and DAC features. The convertedbits can be given to the port meant for digital a serial display.The bits may be transferred to a memory address, port or a parallelport. A processormay processthe convertedbits and generatea Pulse Code Modulated (PCM) output. PCM signals are used digitizing the voice in the digital format. Importantpoints aboutthe ADC are asfollows: . Either a singleor dual analogreference voltagesourceis requiredin the ADC. . An ADC may be of eight, ten, twelve or sixteen bits depending upon the resolutionneededfor conversion. . The start of the conversionsignal (STC) signal or input initiates the conversion to 8 bits. In system, an instruction or a timer signals the STC.
Embedded
Thereis an endofconversion (EOC)signal.I;-,yrt rn, a flag in a registeris setto indicatethe end of conversion and generate an intemrpt.
Introduction to EmbeddedSystems
r.23
well asthe softwarefor the systemto receiveinput from a setofkeys or from a keyboardor keypad. o . { Keypadhasup to a maximumof 32 keys.A keyboard may have 104 or more keys. The keypad or key board may interface serially or as parallel to the proqessor directly through a parallel or serial port or through a controller.
' .
There is a conversion timerimitin whichtheconversion is definite. A Sample and_Hold (S/H)unit is usedto sample the inputfor a fixedtimeandhordtiil conversion is ovei.
1.4.9LCD and LED Disptays r { system requires an interfacing circuitandsoftware to displaythe status or message fcira rine,for murti-rine displays, or flashing displays-. . An LCD screel ma-yshowup a multi_linedisplayof ch4racters or arsoshowa smail graphor icon'lcartea pictogram). An LCD needs little power.It is powered by a supplyor.battery (a solarpanelin thecalcuiator). LCD is a diode thatabsorbs or emitsrighton apprication of 3 V to 4 V and50 or 60 Hz voltag-i_pulses with currents less than 50 pA. An LSI (Lowir Scale Integrated circuit) dispray-controlrer is often usedin the cise of matrixdisplays. ' For indicating oN status of the system theremaybe an LED, whichglowswhenit is OIri.A flashing tdO may indicatethat a specifrc task is undercompietion or is running. It mayindicate a wait status for a message. The LED is a diodethatemitsyelow, green, red(or i-nfrared light in a remote controfier), on apprication oiu forward voltageof 1.6to 2 V. An LED nieds currentup to 12 mA above 5 mA. 1.4.10Keypad /I(eyboard . The.keypador keyboardis an importantdevice for getting user inputs. The system must provide the necessary interfacingand key-debouncing circuit as
1.4.11 Pulse Dialer, Modem and Transceiver . For user connectivity through the telephone line, interfacing wireless,or a systemprovidesthe necessary circuit. o It also providesthe softwarefor pulse dialing through for fax, the telephoneline, for modem interconnection for Internet packets routing, and for transmitting and connectinga WAG (Wireless Gateway) or cellular system. I transceiveris a circuit that can transmit as well as receivebyte streams.
1.4.13 Linking and Interfacing Buses and Units of the Embedded System Hardware . The busesand units in the embeddedsystemhardware are needed to be linked and interfaced. . a glue logic circuit. One way to do this is to incorporate
Embedded S
t.25
A glue circuit is a circuit that is placed(glued) for all the bus logic actionsbetweencircuits and Gtrveen all chi lps and main chips(processors and memories). The glue logic circuit of an embedded systemmay be a circuit for interconnectingthe processor to external memories so that the appropriate chip-select signals, according to the system memory, map each o? the memorychips. The glue logic circuit also includes a circuit to interconnect the parallel and serial ports to the peripherals.The glue circuit simplifies the overall embedded system circuit greatly. Programming and configuring one of the followings givesa gluecircuit. . PAL (Programmable Array Logic).
Summary o An internalpower source or a chargepump is essential in every system. An embeddedsystemhas to perform tasks continuously from power-up to power-off and may even be kept on continuously. For scheduling the various tasks and for real-time programming, a systemclock is needed. o o The systemclock also drivesthe timers for varioustiming and countingneedsin a system. A programthat is resetand runs on a power-upcan be a system program that executesfrom.the beginning, a systemboot-upprogram,a systeminitialization program.
o GAL (GenericArray Logic). o PLD (Programmable Logic Device). o CPID (Combined PLD). o FPGA (Field Programmable GateAnay) These devices are configurableand programmableby a systemcalled deviceprogrammer. l. .l4Hardware Units Required in Exemplary Cases
o The watchdog timer reset is a very useful feature in control applications. . o A system connects to external physical devices and systems parallelor serialports. through A systemmust havean intemrpthandlingmechanism for executingthe ISRs in caseof the intemrpts from physical devices,systems and softwareexceptions.
The hardwareunits that must be presentin the embedded systems are Processor, Processor Internal Bus, GISC or RISC processor Architecture, Cachesor MMU, PROM or ROM, EEpROM or FLASH; RAM Intemrpt Handler, I/O ports, Transceiver,GPIB Interface,Real time detectionof an event or signal, pulse Width Modulation for DAC, Analog to Digital Conversion,Modulation and Demodulation,Digital Signal FrocessingInstructionsand Non-LinearcontrollerInstructions.
1.28
Embedded Systems 2. In the next step,calledlinking, a linker links thesecodes with the other requiredassembled codes.The,linked file in binary for run on a computeris commonly known as executable file or simply '.exe' file. After linking, there has to be re-allocationof the sequences of placing the codesbeforeplacement of the codesin the memory. 3. In the next step,the loader program perforrnsthe task of reallocatingthe codesafter finding the physical RAM addresses available at a given instant. The loader is a part of the operatingsystemand placescodes into the memoryafter readingthe '.exe' file. 4. The final step of the systemdesign processis locating the codes as a ROM image and permanentlyplacing them at the actually availableaddresses in the ROM. In embedded programto keep systems, there is no separate track of the availableaddresses at different times during the running,as in a computer 5. Lastly, either (i) a laboratory system, called device programmer,takes as input the ROM image file and finally burnsthe imageiito the PROM or EP or (ii) at a foundry, a mask is created for the ROM of the embeddedsystemfrom the image file. [The processof placing the codes in PROM or EPROM is also called burningl.
1.29
. i
To write the prograrnin a high level languageis very simple compared to writing it in the assemblylanguage. 'C' programs have a feature that adds the assembly instructions when using certain processor-specific featuresand codingfor the specificsection,for example, port devicedriver. Commands PreDrocessor Main Function Intemrpt serviceroutine
Tasks 1...N
Kernel and Scheduler StandardLibrary FunctionsIncludingnetwork protocolfunction for sendinsstackand receivingstack program layer,s in enilteddetl system.s I'ahle L2 Diffbre.nr , r Theselayersare as follows. i ii iii iv v vi Processor Commands. Main Function. Intemrpt ServiceRoutine. Multiple tasks,say, I to N. Kernel and Scheduler. Standardlibrary functions, protocol functions and stackallocationfunctions.
1.5.4 Software in High Level Language . Software is thereforp developed in a high-level 'C'or'C+'or'Java'. Most of the times,'C' language, is the preferred language. o For coding, there is little need to understand assembly languageinstruction and the programmerdoes not have to know the machinecode for any instruction at all. The programmer needs to understand only the hardware organization.
r.30
C program functions
Code optimiret
In innovative concept is use of virtual devices during programming.A virtual device example is a file (for reading and writing the streamof bytes or words) or a pipe (for bufferinga streamof bytes). A device for the purposeof control, handling, reading and writing actionscan be taken as consistingof three . components. i Control Registeror Word It storesthe bits that, on settingor resettingby a device driver, controlthe deviceactions. ii StatusRegisteror Word It providesthe flags (bits) to showthe devicestatus. that controlsthe deviceactions. iii DeviceMechanism There may be input databuffers and output data buffers at a device.Device action may be to get input into or sendoutput from the buffer. A devicedriver is softwarefor controlling,receivingand sendinga byte or a streamofbytes from or to a device. In caseof physical devices,a driver usesthe hardware statusflags and control registerbits that are in set and resetstates. In case of virtual devices- a driver usesthe statusand , control words and the bits that exist in set and reset states. Driver controlsthreefunctions. i ii Initializing that is activatedby placing appropriate bits at the control registeror word. Calling an ISR on interruptor on settinga status flag in the statusregisterand run (drive) the TSR (alsocalledIntemrpt HandlerRoutine). Resetting the statusflag after interruptservice.
h igure 1.4 C pr<tgtzrm inl<tthr./ilt,./brR()II itnaga o { compiler generates the object codes. The compiler assembles the codes according to the processor instructionsetand other specifications. The 'C' compiler for embedded systems must, as a final step of compilation, use a code-optimizer. It optimizes the codesbeforelinking. After compilation,the linker links the object codeswith other neededcodes.Codes for device management and driver (devicecontrol codes)also link at this stage.After linking, the other steps fur creating a file for ROM imagearethe sameas shownearlier in figure
1.5.5 Software for the Device Drivers and Device Management . In an embedded system,there are a number of physical devices. Exemplary physical devices are keyboard, display,dislq parallelport and network-card.
iii
t.32
EmbeddedSystems
Using OperatingSystem(OS) functions,a device driver coding danbe madesuchthat the underlyinghardwareis hidden as much as possible.An API then defines the This makesthe driver usablewhen hardwareseparately. in a system changes the devicehardware Device Managementsoftware modules provide codes of devices,for initializing for detectingthe presence that are present. theseand for testingthe devices The underlying principle is that at an instant,only one physical device should get accessto or from one task only. The OS also provides and managesthe virtual like pipesandsockets. devices 1.5.6 Software Design for Scheduling Muttiple Tasks and Devices Using an RTOS systemis designedto perform Most often, an embedded scheduling of multiple functions while controlling multipledevices. as a systemprogramis thereforedesigned An embedded multitaskingsystemprogram. In a multitaskingOS, each process(task) has a distinct memory allocationof its own and a task hasone or more for a specificjob functionsor procedures A task may sharethe memory(data)with other tasks.A processor may process multiple tasks separately or concurrently-. The OS software includes schedulingfeaturesfor the (tasks, ISRs and Device Drivers). An OS or processes RTOShasa kemel. The kernel's important function is to schedule the transitionof a task from a readystateto a running state. the transitionof a task from a blocked It also schedules stateto the runningstate.
Syge!ql---L!lto Embedded Introduction The kernel may block a task to let a higher priority task be in runningstate[It is calledpreemptivescheduling]. the use of the'processorfor the The kernel coordinates multiple tasksthat are in readystateat any instant,such that only one task amongmany is in the runningstate. there is only one processor'inthe This is so because a task to a and dispatches system.The kernel schedules different statethan the Present. The kernel controls the inter process(task) messaging queues and pipes' and sharingof variables, . RTOS functions can thus be highly complex. In an RTOS hasto be scalable. system, embedded
1.5.7 Software Tools in Designing of an Embedded System The software Modulesand Tools far the DetailedDesigningof an EmbeddedSystemis as follows: Editor It is used for writing C codesor assemblymnemonicsusing the keyboard of the PC for enteringthe program. It allows the entry, addition, deletion, insert, appending previously written It linei or files, mergingrecordand files at the specificpositions. a sourcefile that storesthe editedfile. creates Interpreter It is used for expression-by-expression(line-by-line) codes. executable translationto the machine Compiler It usesthe completesetsof the codes.It may also include the codes, functiilns and expressionsfrom the library routines. It a file calledobject file. creates
t.34 Embedded Assembler _. For translatingthe assemblymnemonicsinto binary opcodes (instructions),i.e., into an e:rmutablefile called a binary file. tt also creates a list file that can be printed.The list file hasaddress, source code (assembly languagemnemonic) and hexadecimal object codes.The file has addresses that adjust during the actual run of the assembly language program. CrossAssembler For converting object codes or executable codes for a processor to other codesfor anotherprocessor and vice versa.The cross-assmbler assembles the assembly codesof target processor as the assemblycodes of the processorof the pCuseo in the system development.Later, it provides the object codes for the target processor. Thesecodeswill be the onesactually neededin the finally developed system. Simulator It is used to simulate all functions of an embeddedsystem circuit including additional memory and peripherals. It is independentof a particular target system.tt atso simulatesthe processesthat will execute when the codes execute on the targetedparticularprocessor. , Source-codeEngineering Soffware It is used for source code comprehension,navigation and browsing,editing, debugging, configuring(disablingand enabting the C+r features) and compiling. Real Time Operating System RTOS is neededin most embedded systems, as a may have to schedulemultiple tasks, drive a number of physiiar and virtual devicesand handlemany ISRs.
Introduction to EmbeddedSystems
1.35
Stethoscope It is usedfor dynamicallytracking the changeslin any program variable. It tracks the changesin any parameter.It demonstrates the sequencesof multiple processes(tasks, threads, service It also recordsthe entiretime history routines)that execute. Trace Scope To help in tracing the changesin the modulesand tasks with time on the X-axis. A list of actions also producesthe desired time scalesand the expected times for different tasks. Integrated DevelopmentEnvironment Softwareand hardwareenvironment that consistsof simulators with editbrs, compilers, assemblers, RTOS, debuggers, stethoscope, tracer, emulators, logic analyzers, EPROM EEPROM application codes' burners for the integrated development of a system. Prototyper For simulating,sourcecode engineering includingcompiling, debuggingand, on a Browser,summarizing the completestatusof phase. the final target systemduring the development Locator Usescross-assembler output and a memoryallocationmap and provides the locator program output. It is the final step of softwaredesignprocess br.the embedded system. 1.5.8 Models for Software Designing In complex or multiprocessorsystems,there are different models that aneemployed during flre design processesof the embeddod software and its RTOS. The modelsarc as following. . Finite StateMachirrc(FSM) . Petri Net model
1.36 . o
r.37
Cards, Missiles and Satellites, Computer Networking, Digital Consumer Electronics, and Automotive. Telecom Smart Cards Banking Telephone Security Missiles and Satellites
Activity diagramsbasedUML Modet. For multr"'processor systems,the fotowing additionar modersare needed. . ' . Synchronous Data Flow (SDF) Graph Timed pehi Nets and Extended predicate/Transition Net Multi Thread Graph (MTG) System
SUMMARY o The final machineimplement-able softwarefor product -' * a p.-. dmbedsin the ROM ai an image in tt " f.;;. . For configuring s.ope specific physicar device rike transceiver, the machine.oda,areused. t assemblylanguagefile is created rhree crpnc,,.. 1l in thrre stepsusing '.Assembleri 'I,inker, and .Locatoled o 'C'program hasseveral layers. 'C' o A compilergenerates an objectfile. a Using linker and locator the file for ROM image is createdfor the targethardware. Two typesof devices are considered: physicar and virtuar. PhysicaldevicesincludeLrvpuAr,piinirir. A virtual devicecould.be a file. For scheduling multiple tasks,RTOS kernelwith function,,i, "r.0.
Automotive
DVDs
Settop boxes High definition TVs Digital cameras
Motor Control System CruiseControl Engine/Body Safety Robotics in Assembly Line Car Entertainment Car Multimedia Mobile andE-Com Access
1.6EXEMPLARYEMBEDDEDSYSTEMS
]xe_mqlaV^ Applications of Each Type of Embedded System Embedded systems have very divenified applications. A few select application areas of emuraa.JryrtrmsareTerecom, Sme 1.6.1
A ty examples of smailscare embedded system apprications are asfollows: . Automatic Chocolate Vending Machine
Stepper motor controllersfor a roboticssystem
1.38
Embedded SySterqs
1.39
. . .
Washingor cookingsystem MultitaskingToys Microcontroller-basedsingle or multi-display digital panel meter for volage, cunent, resistance anil frequency Keyboard controller Serialport cards ComputerMouse CD drive or Hard Disk drive controller The peripheralcontrollersof a computer,for example,a CRT display controller,a keyboardcontroller, a DRAM c.ontroller, a DMA controller,a printer-controller, a laser printer-controller, a LAN controller, a disk drive controller Fax or photocopyor printer or scanner machine Digital diary Remote(controller)of TV Telephonewith memory,displayand other sophisticated feafures Motor controls Systems - for example, an accurate control of speedand position of d.c. motor, robot, and CNC machine;automotiveapplicationssuch as a close loop enginecontrol,a dynamicride control, and an antilock braking systemmonitor Electronic data acquisition and supervisory control system Electronic instruments,such as an industrial process controller Electronic smartweight display systemand an industrial moisfure recordercum controller
a a
Digital storagesystemf<ira signalwave form or Electric or Water Meter Readings Spectrum analyzer Biomedical systems suchas an ECG LCD display-cumrecorder, a blood-cell recorder cum analyzer, and a patientmonitor system Someexamples of medium scaleembedded systems are as follows: Computernetworking systems,for example,a router, a front-endprocessor in a servero a switch, a bridge,a hub' and a gateway For Internet appliances, there are numerousapplication systems An intelligent operation, administration and maintenancerouter (IOAMR) in a distributed network Mail Client card to store e-mail and personal addresses and to smartlv connect to a modem or server
. . . . .
. . . . o
Entertainment systems-such as a video game and a musicsystem Banking systemsfor example, Bank ATM and Credit card transactions Signal Tracking Systems for example, an automatic signal tracker and a target tracker Communication systems such as a mobilecommunicationSIM card; a numeric pager, a cellular phone,a cableTV terminal,and a FAX transceiverwith or without a graphic accelerator Image Filtering, Image hocessing, PatternRecognizer, Speech Processing and Video Processing A system that connectsa pocket PC or PDA @ersonal to the automobiledriver mobile phone Digital Assistant)
. . .
Embedded
and a wireless receiver.The systemthen connectsto a remote server for lntemet or e-mail or to a remote provider).This computer at an ASP (application Service system forms the backboneof m-commerce(mobile ecommerce)and mobile computing. Summary Based on the functions different types of embeddedsystems are usedfor variousapplications
L4l
the configurable processors(called FPGA cum ASIp processors)and non-configurableprocessors(DSp or Microprocessor or Microcontrollers) might be needed on a chip. . o . One example of a killer application using multiple ASIPs is high-definitiontelevisionsignalsprocessing.. ^ I cell-phoneis anotherkiller application. Recently, embedded SoCs have been designed for functioning as DNA chips. Consider an FpGA with a large number of gate arrays. Now, using VLSI design techniques, we can configure thesearraysto process the specifictaSks on an SoC.This gives a SoCas a DNA chip. Each set of arrays has a specific and distinct DNA complex structure. These structures as well as the processor embedon the DNA chip.
l.7.l Exemplary SoC for Cell-Phone . ' Figure showsan SoC that integrates two internalASICs, two internal processors (ASIPs), sharedmemoriesand peripheralinterfaces on a commonbus.
1.42
Embedded Systems
8tr5E5
OTIGR &16TAL
(EDA) tool. [For designof ASIC digital Automation 'High circuits,a Level Designlanguage(HDL)' is usedl. 1.7.2 ASIP
A systemspecificprocessor (ASIP) is the one that does not use the GPP (standard available CISC or RIS microprocessor or microcontroller or signalprocessor). The processoron chip incorporatesa section of ine CISC or RISC instructionset. This specific processor may have especially configurable instruction-set for an application. An ASIP canalsobe configurable. Using appropriate tools, an ASIP can be designed and configuredfor the instructions neededin the following exemplaryfunctions:DSP functions,controllersignals processing function, adaptive filtering functions and eommunication protocol-implementing functions. On a VLSI chip, an embedded ASIP in a specialsystem be a unit withinan ASIC or SoC.
Figu.e L5 Sv-stern on chip . Besides a processorand memoriesand digital circuits with embedded softwarefor spccific application(s), the SoCmay possess analogqircuitsaswell. An exemplary applicationof such an ASIC embedded SoC is the cell-phone.One ASIP in it is configuredto processencodingand decipheringand anotherdoesthe - voice compression. One ASIC dials, modulates, demodulates, interfaces the keyboardand multiple line LCD matrix displays,stores data input and recallsdatafrom memory. ASICs are designedusing the VLSI design tools with processorGPP or ASIP and analog.circuitsembedded into the design.
1.7.3IPCore
On a VLSI chip, theremay be high-levelcomponents. These are components that possess gate-level sophistication in circuits above that of the counter, register, multiplier, floating point operation unit and ALU. A standardsource solution for synthesizinga higherlevel component by configuringFPGA core or a core of. VLSI chip may be availableas an Intellectual Property, called(lP). The copyright for the synthesized design of a higherlevel componentfor gate-levelimplementationof an IP is held by the designer or designing company.One has
t.44
Embedded Systems
Introductionto Embedded
to pay royalty for every chip shipped. An embedded an IP(s) systemmay incorporate ' An IP may provide hardwired implement-able designof a transformor of an encryptionalgorithm or a deciphering algorithm An IP may provide a designfor adaptivefiltering of a signal. An IP may providefull designfor implementing Hyper Text TransferProtocol(HTTP) or File TransferProtocol (FTP) to transmit a web pageor a file on the Internet.
Using ARM7, a large number of embeddedsystems have recentlybecomeavailable. One recentapplication is in integratingthe operatingsystemLinux Kernel2.2 andthe devicedriversinto an ASIC.
1.7.4Embedding a GPP r (GPP) can be embedded Processor { GeneralPurpose GPP calledARM exemplary on a VSLI chip. Recently, 7 and ARM 9, which embedonto a VLSI chip, have by been developedby ARM and their enhancements TexasInstruments . either is available An A[M-processorVlSl-architecture it into VLSI or SoC. as a CPU chip or for integrating with RISC provides functionality CISC ARM architectureat the core. An applicationof ARM embed circuit is ICE. ICE is used for debugging an embedded system. Exemplary ARM 9 applicationsare setup boxes,cable devices suchas mobilehandsets. andwireless modems, ARM9 has a single cycle 16x32 multiply accumulate at 200 MHz. It yses 0.15 pm GS3O unit. It operates pipeline. CMOSs.It hasa five-stage It incorporatesRISC. It integrateswith a DSP when designing an ASIC solution having multiprocessors' architecture. GS2OCMOSs. 0.18pm based It uses
1.7.5 FPGA [Field Programmable"Gate Arraysl Core with a Single or Multiple Processors o { new innovationis Field Programmable Gate Arrays (FPGA)corewith a singleor multipleprocessor unitson chiP. . One exampleis Xilinx Virtex-Il Pro FPGA XC?VP lZ5. Other exampleis 90 nm Spartan-3 FPGA releasedon April 14,2003by Xilinx. . Thereis a setof.gates in eachFPGA cell, called.macro cell'. Each cell has severalinputsand outputsand they are interconnected like an anay (matrix). o Consider the algorithms for the following: an SIMD instruction, Fourier transform and its inverse, DFT or Laplace transform and its inverse, compressionor decompression, encryptingor deciphering,a patternrecognition 1.7.6 Components in an Exemplary SoC-Smart Card Its components areas follows:
a a a
ASIP (Application SpecificInstruction Processor) RAM for temporaryvariablesand stack ROM for application codes and RTOS codes for scheduling thetasks EEPROM for storing' user data, user address,user identificationcodes,cardnumberand expiry date
a a
Timer and Intem"rpt controller -16 MHz a circuit and Amplitude A carrier frequency ShiftedKey (ASK) Modulator
1.46
EmbeddedSystems
idantificrtions datafl ow
nrpply Systenpower
luu'dv'ure .compont:nts irt a l;igure I.6 .Embedded.sy-stem curd conlact less.smart . ASK modulatorgives l0% excessamplitudeof carrier pulses for bit 'I' and l0% less for bit '0'. A load modulation sub-carrier has one-sixteenth of this the ls and Os by Binary Phase frequencyand modulates ShiftedKeying (BPSK). . ' . Interfacingcircuit for the I/Os Charge pump for delivering power to the antenna(of -5mm range)for transmission and for systemcircuits.
Summary o A VLSI chip can embed[Ps for the specific applications, besides the ASIP or a GPPcore. o A system-on--chip is the concept,for example,a mobile phone. o A contact-less smartcard is one suchapplication.