You are on page 1of 348
Embedded Systems Architecture, Pragramming and Design Second Edition Raj Kamal Acknowledgements um money grate my teaches: a the din Iu of Tesbneogy, Dei (1966-72) and the Univrsty of pps, Sweden (1978-79, 198), Tor eahing ne the impenance of searing and theese of Keep ‘rere techn. {would Fhe oth Pok MS Seb. FNA. for his support and blesings ioghoat my scaemic Ie ckoowedgr ny Inder coleaues -D: PC Sharma, Dr?K Chante, Dr Sajee Tolar, Mos Win Tek. Dr A “Snomt, De Maya ng. Dr Sanjay Tawar, Ms Prot Sakon, Ms Sada Masih Ms Apuma Dev, and Ms Vat G “Tearand eter nies seaman, Dr PS Grover Det). De Harvie Singh Sani (Hyderaba), De Radka SGutipauey Dr TV Gopl (Anna Uniersiy) and Dr KM Mea (Annu Univesity)—fr tc constant encourage oeiation of my efits. ar thal to heel ean t MeCeaw ill Edin nda Fortec eviews rd day tect, Lacon ne college Dr MK Sa, Hea. Conger Cre of the Universi. wh wi is ew etion she posed aay dig he as phase ofthe pregrain of his ook, Tool alo ike otha all those viewers who Took ou ie ogo tough the rit and give mete Fendbck, mame re itd belo Ramanaryan Rody sep of Computer Science ond Enginern. te Gandia of Technology He Delhi lita Folare findstan Clee of Sone end Tchelogs. Agra Akhil Kothart dep of Electonics and Conmatiation Engineering ahaa Sin Des Tait of Te: Gar priya Kear ins Isat of Engincerag and eral, imi Adina dep of Ceci oe) Commute and Ergineein ‘uta instina of Engivering we Monee Kola Pipankar Ghosh dep of Elec nd Commanicaton Engineering “Sal Ist of Teta. Roan ehashish De dep af Elecrnnics end Cominco Engineering eahnad Saha ning of Tecate: Kote Finally, F acknowledge my wife, Sisil Mtl and my Family merbecs—Shalin Mita, Necdbi Mital, De At ‘ondskar Dr hip! Konasar and Me Anh Kondaskar—for thee immense love, understanding and sopping Je wong ofthis eee eden P Kabisapathy Dep of Eleconics cn Inaramenaion Engineering, College of Enginering and Tecnology. Bhubaneswar KK Mohapatra Dept of Elecinnic. Neti nttatofTetnolos, Rowe JK Meadiratta Dept ef Electrics and Communication ond Engineering RY. Cale of Eninering.Bangaine la B Das ‘ep of Electronics Engineering National Insite of Tecan Calicut ‘Santa Kumari Dept Feces and Canvnonicaton Engineering “anv Universi, Vb V Mortidharen Dept Commuter Sconce ond Bnei. MS Rone hotioneof Toole, Banglore Josephine P Kumar Dept of Computer Science and Brine. MUI Coleg of Enginecring. Bangalore Stanley Johnson Invense Ina Pt. Lid. Cheoma ro with K Contents Prec tothe Second Edition Prac othe Fist Edition 1. Intraductin to Embedded Systems THE Embedded Systems 12 Presi Eade in 2 System 5 13 Embedded Hardware Units and Devices in Spc 10 14 Embed Soma in a Sytem 19 15 Examples of Emedod Sysem 27 16 Embed Steno chip (Se) and Use of VESI Cit Design Texhaology 29 17 Compler yes Desig al Process 12 [LF Design Process in Entel Spey 17 19 omalzaion of System Design 42 1.10 Design Proves nd Design Examples 43 LIF Clasifiton of Embeoled Systeme 52 12 Skis Reqbired orn bedded Systm Desisner 38 2. $051 and Advanced Proceso Architectures, Memory Organization and Real-world Intrtacing 2I BSI Accent 62 22 Real World nertaing 72 2.3 Inradcton to Adve Archean 214 Procesor and Memory Orpnizaian 25 racion-Level Plea 10 26 Perormance Mees 106, 2.7 Memory Types, Memory-Maps and Adress 105 2.8 Proceuor Slostion 12! 29 Memory Seen 118 5, Device and Communication Bases for Devices Network RI 1O Types and Bam 120 42 Sor Communion Devices 1 43 Parl Device Pons 14 1A SopbistsedItrtacng Fetus in Device ns 150 35. Wels Devies 15! 36 Timer nd Counting Devies 152 47 Welcog Tiree 157 38 Rel Time Cook 139 519 Networked Embed Syoms 139 310 Saial Bus Communion Protea 160 2LI Paral Bs Device role Parallel Communication Network Using ISA. PC, POLX a Advanced Buses (66 412 Inert Enabled Syren Network Prtacls 170 413. Wireless nd Motil Sytem Protocols 175 Device Drivers and Interrupts Service Mechanism ‘$1 Prgms 0 Busywcit Apeeach witout Inert Service Mechanism 189 a ro xiv 42 ISR Concene 192 5 ncrpt Sources 200 413 nrg Servicing (Huang) Mechanim 203 415. Moliple Incr 209 “6 Comex and the Periads for Cote! Switching, Inter Latency and Deane 211 449 Clasiticaton of Process lnterrupt Service Mechanism frm Content Saving Angle 27 444 Drea Memory Aeces 218 49 Device Driver Programming 220 Programming Concepts and Erabeded Programming in C, + and Java 5.1 Sofware Programing in Assembly Language (ALP) sad in High-Level Lingwage “C235 5.2 C Program Elements: Header and Source File and PeporesorDietves 237 53. Program Elements: Macros and Functions 259, 514 Program Element: Data Types, Duta Stucures, Motes Sttemens Lops and Poiners 247 55 Object.Orented Programming 262 56 Embedded Programming in Cr 265, 57 Embosded Progamming in fava 261 (Program Medelinn Concepts 6.1 Progr Models 274 62 DEG Moses 277 3. Ste Machine Programming Models for Event conralled Popa Flow 282 {64 Modeling of Multiprocessor Systems 258 65 UML Modeling 295 2. Interprocess Commnication and Synchronization of Processes, Threads and Tasks LL Muliple Preset an Appicaion 05 72. Maliple Teas in am Applicaton 306 73 Tasks 308 14 Tank Sates 08 15 Tank and Data 310 “16. Cleareut Distinction teoween Farsi, ISRS and Tanks y ther Characterisies 377 17 Concept of Semaphore 314 18 Shared Dats 325 118 Inerpacese Commusicaion 230 1140 Signal Fanction 332 TN Semaphoce Functions 324 LAD Message Queue Fares 35 7113. Mailbox Functions 337 ZLIA Pipe Functions. 339 LAS Sooke: Furctions 347 716, RPC Functions 45 8. Real-Time Operating Systems 8:1 OS Services 351 82 Process Management 355 83 Timer Functions 356 8 Event Funcions 258 85 Memory Management 258 Contents ms 380 contents ‘56 Devic. Fle and 10 Subyysems Management 67 17 loterspt Roane n RTOS Environment eu Handling of reap Sas Call 1 Keattime Oporating Spwens 70 9 Basie Design Using an RTOS 372 10 Rugs Tas Scheduling Modes, tterap Latency and Resp of the Tasks Perfomance Metics 385 LIL OS Seouiy Funes OP 9. Realtime Operating System Progeamming-1: MicrogOS.I and VaWorks 91 Basic Fusions and Types of RTOSES. 408 92 RTOS mcOs-t #10 93 RTOS VaWorks 453 10. Reals Operitng System Programming: Windows CE, OSEK and Rea time ux Functions 11 Windows CE 78 102 OSEK 494 103 Linws 26.cand RTLnox 496 1H. Design Examples and Case Studies of Program Modeling and Programming with RTOS 11.1 Case Study of Embed System Design ad Cocing fo an Amati 5/2 (Chole Verding Machine (ACVM) Using Mocs RTOS 1.2 Case Stay of Digial Camers Harbrre at Solvare Arciecre 531 113 Case Sua of Coin fr Seating Appicaion Layer Byte Sueur on 3 TTCHMP Nevwork Using RTOS Vawerks 57 12. Design Examples and Cae Stes of Program Modeling and P Rros2 12.1 Case Sudy of Conmuication Betwarn Ochoa Reiss 567 123 nba Syste ia Autre 374 12.3 Cave Stay of am Embedded Stem oe an Adie Case Cantol (ACC) Sytem in Cor 377 12.4 Cae Sty ofa Embed Sytem ora Stat Cand S48 25. Cine Sly oa Mable Phone Sta or Key Iga vgramming with 13, imbedded Softare Development Process und Tuo 1.1 Insoducsion Enid Sotware Develapent Press and Tals 620, 132 Most and Target Maines 62! 15.3 Linking and Locating Solware 626 138 Going Embedded Soware ino the Target System 630 18S sues im Hrdvane-Software Design and Co-deign 34 1H. Testing, Simulation and Debugging Teetiques and Tools 1 Testing oo Hest Mashine 649 142 Simolsters 650 143 Laboratory Toole 655 Anpends I Roadmap for VariltCoe Sates Agpex2: Selec Bibigriphy Indes e 406 ” ts oss 602 63 - Walkthrough TEAL ge aap veoh (| Simple way of point-wise presentation of the details by | | | ‘Summary, Keywords and thet Gelintions, review questions - and practice exercises in each chapter ‘Waiktheough ‘Walkthrough l xi) x Explains modeling of programs and sokwareenginesing practices fr system design by Comprehensive explanation with coding exams for Case studies of systems fr automatic choclate vending mactine, ita camera, TOP! learn he dey used ATOSeS. mCOS, Vator, IP stack creation, abot orcosta, automatic use contol, smart caréand mobile phone ts enlace emai manteai { opendis2: select Bil Detailed selected biography of books, journal references and important web tnks at end ofthe book ofacitate bling a startup Ivar for references and further studies in Embedded Systems Wiatktraugh Introduction to Embedded Syste a £ A R NN I N G HRRRANRS BO Sia wee OF TEeNN@LOGY UmRARY EANGALONE - S00 60, ACN, Ho. Section 1 Deftions of system and embedded system Section 1.2 The processing unit of an embeded system consists of 1. A processor 2 Canmonly used microprocessors 3. Applicationspecific intrction set processors (ASTPst ‘nicraconrllers, DSPs ard others Single purpose processors Section 1.3 The hardieare it of an embeded stem consists of 1 An embedded ‘sem poser source with esate peace ddssipaion 2 Aclack oscillator circuited clocking unit hat eta processor 3. Timers and areal me clock (RTC) or various timing needs ofthe stem 4. Rese circuit nd watchdog timer 5. System and external memories 6, System input ouput (10) ports, sera, parallel and wireless communication, serial Univeral Asynchronous Receiverand Transmiter (UART) and other port protcols ad buses 7, Devices such as Digital to Analog Converter (DAC) using Pulse With Modulation PWM), Analog to Digital Converter (ADC) Ligit Emiting Diode (LED) and Liquid Crystal Display (LCD) units, keypad and keyboard, touch screen, pulse dialer, madem and transeiver 8 Muliplexers, deruliplerers, decoder for interfacing of he devices and buses L £ A R N I 22 ° a mes & 9 trig conor (aer Seaton Ls 1 Languages tha are sed develop embeded software fora stem 2. Program modes 4, Matting using on operating sytem (08), tom device driver, device sunagemen and real tne operating stem (RTOS) 4 Sofmre tos for em design Seton 15 vaples of epplicion: of embedded sytem Seton U6 Designing on embedded stem ona VLSI chip 1 Embed SC (Sytem on Chip) and eampls of ts eplicatons 2. Uses of Application Specie Ison Set Pres (ASIP) ad Inelecual Property TP) coe 4. Fld Pregraoable Gate Array (FEGA coe wth single or maple pocesar ants onan ASIC chip section 17 The comes tem consis of 1. Embedded microprocessors or GPPs i complex ses 2 Ebeling ASIP mcrconrlers, DSPs. med an ner processors 1. Bnei appcatiom specie sem processor (ASSP 4 Enbedng ralipteprocesors in ytens section 18 The devon process has 1 Changes In embeded stem design 2 Design mers opiniation 43. Code of harvard sofware componens Section 19 The sate design forma defined Seton 110 The design of embeded harvard sofare in an awomatc chocolate vending machine smartcard dsacanera able phone. mobile compe ar ar five as examples Section Lt Classification of embeded sens ino thre res Section 112 Sls needed to dsgn an embedded sem Invoducton o Embedded Systems f J 1.1 “EMBEDDED SYSTEMS 1.4.1 System ‘Asystem is « way of working organizing or doing one or many tasks acconling oa fixed plan, program. or exof rales A system salsoan arrangement in which lls units ssemble and work together according tothe plan or program ‘Consider a watch. Iti atime-splay system. Is pars ate its hardware, needles and batery with the beautiful dial, chasis and sap. These pars organize Zo show the real ime every second and cominvously tpdate the ime every second, Te system program updates the display using three needles afer each second, follows ast of rales. Some ofthese rule area follows: () All needles move only clockwise. i A thin and Tong needle rotates every second such that it earns to same positon ater a minut. (i) A Tong needle rotates very minute such that it returns to same position after an hour, (i) A short nee ote every hour sch that ftretums to same position after twelve ours. (¥) All thee needles etum tothe same inctnation ater twelve hours each day ‘Consider a washing machine, It isan automatic clothes-vashing sytem, The important hardware parts include ils status display pane, the switches and dials for user-defined programming, 2 motor to rotate or ‘pin, its power supply and contol unit sn inner water-level sensor a solenoid valve for ling water in and nother valve fr keting water Uain out, These parts organize to wash clothes automatically according 10 & program preset by a uset. The system-program is activated to wash the diy clothes placed ina tank, which fotales oF spins in preprogrammed steps and stages. follows a set of rules. Some of these rules are as follows: ( Follow the steps strictly in the following sequence. Step I: Wash ay spinning the motor according to programmed peiod. Step I: Rinse in Fesh water after draining out the dity wate, and rinse @ second time ifthe system snot programmed in water-saving mde, Sep II: After daining out the water completely spin the motor fs fora progranimed period for ding by eentuging out water from the clothes. Sep TV: ‘Show the wash-over status bya blinking display. Sound the alam for 2 miwe to signal thatthe wash cycle is compete. (i) At each step, display the process stage ofthe system. i) In ease of an interuption, execute only the remaining part of the program, starting fom the postion when the process was interupted, There fan Beno repetition from Step Lunlss the wer resets the system by inserting anoer se of clothes ad resets the progra 4.1.2 Embedded System Definition One of the definitions of embeidd system is a follows “An embedded system isa system that has embedded sofware and conputerhardware, which wakes it «system dedicaied for an applications) or specie part of an application or product ora part ofa larger Embedded systems have been dened in books published recently in several ways. Given below isa eres of definitions fom others in the eld ‘Wayne Wolf author of Computers as Components ~ Principles of Embedded Computing System Design: “what is an embedded computing sytem? Loosely defined, iis any device that includes a programmable ‘computer bus not itself intended to be a general-purpose computer” nd “a fax machine or aclock bil rom mieroprocessor is an embedded computing system" i ex Embedded Systems. EAS: " BM author of Bnbeed Mirocontles “Embedded Sytem se eectonc sens ta aa microprocessor or microcontoller, tut we do aot think of them as computersthe compote hidden or embedded in the system.” David E. Simon author of Ar Embedded Safoware Primer: ‘any computer system hidden in ny ofthese products InP tear a an eodction tothe Design of Smal cole Embedded Stems with examples Freeney CRHCOS8 miroconroles: (I “An embedded system ks sytem whose rp function is not compu “People use the term embeded sytem to mean system, hidden from view, forming an integral pat of microconiroller-base, software driven, rela {teractve, operating on diverse physical vai and cost-conscious market" the greater whole". (2) “An embedded system is a real time control system, autonomous, or human- or network ls and in diverse environments, and sold into a competitive ‘computerisation conpnents 1" Amisepeesor 2 Auge memay eth loin to ks (Prima mean mond eis Rado Acs Mey (RAM, Rely Nee (ROM) and fast accessible caches) ae mane aes (© Sesinary meno innermost nhs, tes an cade pes ope Imeony in CD-ROMs or memory sks (in mobile compute] ising ohh dee Pans con eed ne mayen 3. vodissch sachsen meen tc 4 lp ois chase nce dias eae 5: Outpt ans sich aan LCD ses, es ra eee 6, Networking unis uch ners et, fr end aces ed set bs ive, ex 1 Av oping system (0S) th hs pene use wer sa pss a tay non ‘Anemone syst is sym ht as te min components nbd tit "Kendriya Snr aconpute Fg hw hoist eat fan embed {aiem Asta niente KOM orathmeme, teal one hadi oed CD menor as nts 2. Renbet min epteaon ts er proceso eae 3. Hembeds a realtime operating sytem (RTOS) that sp vare. The application software may concurrently perform a series of ervises the application software running on to the procties of tasks in the system, It Perea saomectanism tole the processor una process as sched and contextswich berocee he cet ae ee, Ti cone of process, tread and ask explained ner in Sections 71 te 3g Ste les rng te exestion ofthe appleaonotvae TA aac oi to ‘not embed the RTOS.) a ° Irroducton to Embedded Systoms reaones | verte Omer Crt Pons [outputs intertocinge | | | 1 _} L_Baergecse : 3 i : i Fig. 1.1 The components of embedded system hardware and evens have different rates and time istinet rates. For example, audio, vdeo, data, network steam and ie constrains (2) Complex algorithms. (3) Complex graphic user interfaces (GUIs) and other user inter (4) Dedicated functions. Constraints An embed system design ping in vw the costs: (1 arise system reno, ie peso sp) dt sitive re en Conia ee of wat Tor ven ra Op wake ad lp "he system dein or an embed ye has cnsins with ear fo perfomance power ie and (Gi) # include mah > (i) woid main (vty { (iv) in if, 2,13. a float ress (v) T= 127 (2 = 29513 = AD; a m iF + 2 + 18: ces = wort (a): (¥) pri (resul):) generates the object codes. It assembles the codes ictal || Fiat eluding ct seairg Sekar | | ecahng Sch C, Ce, Java, Visual C++ ar the languages used for software development. A C program has various layers: processor commands, main function, tsk and library funesions, nterrup service routines and kere (Gcheduler). The compiter generates an object fil. Using linker and locator, the file for the ROM image is created forthe targeted hardware, Initoducon to Embedded Systems 1 | acne A Cotesia A oc Fa z ‘Compiier | Obed Fae. | £ way | 2 i Mastin [Linker | Progam oses al |_Goses ‘Slaps an ¢ town in Fire 18 Embodied System] ROM Merry Fig. 1.8 The process of converting 2 C program into the file for ROM image 1.4.5. Program Models for Software Designing “The program desige ask i simplified if «program is modeled, “Thedfferent models tha ae employed during the design processes othe embed software areas follows 1. Sequetal Program Mode! 2 Object Oriented Program Model 3. Control and Data lw graph or Synchroncus Data Flow (SDF Grapor Muli Thread Graph (MTG) Moet 4. Finite State Machine for datapath 5. Multithreaded Model for concurrent processing of processes ar tread or asks UML. (Universal Modeling language) isa modeling language lor object oriented programming. “These models ae explained Chapter 6 1.4 Software for Concurrent Processing and Scheduling of Multiple ‘Tasks and ISRs Using an RTOS ‘An embuilded system program is most often designed using multiple processes or multitasks or 3 tmultitheads. [Refer to Sections 7.1 to 7.3 for definitions and understanding of the processes, threads and tasks | “The molipl tusks ae processed most often by the OS na sequentially bt concurently. Concurent processing tasks ean be interrupted for running the ISRs, snd higher priority tsk preempt the running of lower priority tasks. 'An OS provides for process, memory, devices, 10s and file system management. A filesystem specifies the ways in which a file is erated, called, named, used, copied, saved of deleted, opened and closed, File system i the software fr using to files ona disk, ash memory, memory card or memory tek. (0S software have scheduling functions forall the processes (asks, ISRS and device drivers) inthe system. Since the runing of the tasks and ISRs may have realtime consrsnis and deans or nishing the tasks, an RTOS is required in an embedded system. The RTOS provides the OS functiogs for coding the system, provides interpocess communication funetiqas anyacontols the passing of messages and signals to task [RTOS funetions ae highly complex. There ae a numberof popular and rea Chapters # to 12 desribes the RTOS functions and examples of applications available RTOSS, the embedded syste, [2] Embedded Systems eg RTOS is wed in most embedded systems and the system dees concurrent processing of multiple ‘when he tess have eal ime constrains and deaine 1.4.7 Software for Device Drivers and Device Management in an Operating System Am embse system is designed to perform muitpie functions snd has to control mutiple physical end ‘nul devices. nan embeddedsystem, here may be numer of phsicul devices, Exemplary physical devices ae timer, keyboarus, display, ash meme, parallel por nd wetwuek cards ‘A program is ako be developed using the concept of virtual devices. Examples of veal deviees areas Fallows 1. A ile (of revords opened, ead, written and closed, and saved as a siceam of bytes or words) 2. A pie for sending nd recevirg a seeam of bytes fom a sauce Wo destination) 3. A socket (for sending and receiving a stream of bytes belwoen the client and server software and between souce and destination computing systems) 4. A RAM sk for sing the RAM in a way simile t files the disk) A fileisa data structure (or vital device) which sends the econ characters or words) ta daa sink (Kor ‘example. prmgram neon and which tees the data From the data source fi example. program Function Alena computer may also be stoce in the hard disk ain Mash memory in embeded system, ‘Theterm vitual device fllows from the analogy tha usta keyboard zives an input to the processor for 4 read, a le aso gives an input to the processe. The peacessor gives an output 10 a printer for a write Similar, the procesr writes an output the ile A device fr the purpase of conto. handling. eating and writing three components) A contol registro word thal stores the bits that, on setting or resting by a device ‘diver, conta device ations. Gi A status register worl hat prvi the flags (its) to sy the device situs othe device diver (i) A deviee mechani that controls the deve ations. There my be input an ‘utp data bles ina device, which may be writen or read by device driver Deviee driver aeons are to J, input data balers, utp data buffers and status setions ean be taken as consisting of 25 inp oF send pas fom the conte er f the devin ‘A devie ever is sftware for opening, connecting or binding eaing, writing and cling or controlling sections ofthe device Is software writen in high level language. Ht contas functions for device open (configure), connet bin listen, read or write or else. The device driver executes ltr the program the con regiter (or we) of peripheral or viral device. The programming i called device initialisation (registration or attachment. The diver rads the status regis, ets the imps and writes the outputs. I ‘executes onan interrupt oor from te device. A driver controls tee functions. ()Intalining, which is sctivated by placing appropiate bts atthe control register or word. (i) Calling an ISR on interupt or on sting status fag in the status register a unig (riving) the I (nterupt Handler Routine). i) Reseting the stats ia aller an interrupt service. ‘diver may be designed for asyctwonous operations (multiple use by task one after smother) or synchronous ‘operations (concurrent use by the tsk). Using’heifltion ofthe OS, a device diver coding ear be made sch that the underyng hardware ix hidden as much as possible. An API then defines the hardware separately. This makes the driver usable when the device hardware changes in a system, eee fs A device driver aeceses a parallel or serial port, keyboard, mice, disk. nctwork display. ile, pipe and sweket at specific addrewes. An OS als provides device driver cok for ystem-port arses and for hardware acess mechanisms, ‘A device manager software provide codes fr deleting the presence of devices for niialring these and for testing the devices tha are present. The manager includes software For allocating and registering pet (in Fac it may be a register ar memory) addreses for te various devices at distin diferent adresses, neloing, tenes for detecting any collision between these i any. I ensures tha any device acesses to ome task oly it rn instant I takes into account that virtual devices may also ave akreses tht are alocated by the manager. ‘An OS alo provides and executes movil for managing devices that associate with an embedded system. ‘The underlying principe is tha at an instant, only one physical or viral device should get accesso oF from cone tsk only Sections $24 and 8.6.1 will describe device drivers and device management in detail. The OS alo provides and manages viwal device such as pipes and sockets. Sections 7.14 and 7.15 deveibe these in deuil For designing embedded-softwar, two types of devices are considered: physical and virwal. Physical eviews include Keypad, printer ce display unit. A vial device could bea leo pipe or socket oc RAM tisk, Device drivers and device manage software ae needed inthe system, The RTOS includes devic- drivers and a device manager to contol and facilitates the use ofthe number of physical and viral ] li | | PROGRAM | ! bata | (CONTROLLER L AND PORT i i | | Fig. 1.10 ASoC embeded system andits common bus withinternal ASPs, internal processors, IPs, shared memories and peripheral interfaces Introduction to Embedded Systems 31 1.6.1 Application Specific IC (ASIC) ‘ASICs designed using the VLSI design tots with he processor GPP or ASIP and analog circuits embedded jm the design, The designing is done using the Electronic Design Automation (EDA) too. [For design of an [ASIC, a High-level Design Language (HDL) i wed, 1.6.2 IP Core (On 2 VLSI chip, there may be integration of high-level components. These components possess sate-level sophistication in cteuits above that ofthe counter, register, multiplies, floating point operation unit tnd ALU. A standard souce solution for syathesizing a higher-level component by configuring an FPGA ‘ore or a core of VLSI circuit may be available as an Intellectual Propery. called (IP). The designer or the ‘esigning company hols the copyright forthe symthesized design ofa higher-level component fo gatelevel implementation of an IP. One might have to pay royalty fr every chip shipped. An embedded system may inconporate several IP. + Am IP may provide hardwired implementable design of a ansform, an encryption algorithm or 3 decinhering algorithm, + Am IP may provide a design For adprive filtering ofa signal + Am IP may provide a design foc implementing Hyper Test Transfer Protocol (HTTP) or File Transfer Protocol (FTP) or Bluetooth protocol to transmit a web page ora file on the Internet + Am IP may be designed fora USB or PCI bus controller. [Sections 3.103 and 3.12.2] 1.6.3 FPGA Core with Single or Multiple Processors ‘Suppose an embedded system is designed with @ view to enhancing functionalities in future. An FPGA ‘cores then used inthe circuits. Kt consists of large numberof programmable gates on a VLSI chip. There is ‘asetof gates ineach FPGA cel called mero cl. Esch cell as several inputs and outputs. All cells iteconnect, Tike an aray (matrix). Each interconnection is programmable through the associated RAM in an FPGA ‘programming tool. An FPGA core can be used with single or multiple proceso. Consider the algorithms for the following: Fourier transform (FT) and its inverse (IFT), DFT or Laplace ‘transform and itsinverse, compression or decompression, eneryptingo: deciphering specific pater recognition {or recognizing a signature o finger print or DNA sequence). We can configure a algorithm int the logic fates of FPGA. It gives hardwired implementation or a processing unit I is specific © the need ofthe embedded system. An algorithm ofthe embedded software can implement in one ofthe FPGA sections and another algorithm in its other section. FPGA cores witha single or muliple processor units n chip are used. One example of such core is Xiling Vinex-ll Pro FPGA XC2VPI25. XC2VPI25 from Xilinx has 125136 Topi cells in he FPGA core ‘with four IBM PowerPCS. Ic has been used as a data security solation with encryption engine and data rate (of 1.5 Gbps. Other examples of embedded systems integrated with logic FPGA. arays are DSP-enabled, realtime video processing systems and line echo eliminators for the Public Switched Teleeommnication [Networks (PSTN) and packet switched networks, [A packet is @ nit of a message or a flowing data such that t can follow a programmable route among the number of optional open routes available at an instance.) Embedded Systems 1.7 ~ COMPLEX SYSTEMS DESIGN AND PROCESSORS 1.7.1 Embedding a Microprocessor A General Purpose Processor microprocessor can be embedded on & streams of mieroprocessors embedded ina complex system design, I chip, Table 1. list different Table 1.4 Important microprocessors used in embedded systems ————— ‘Seam “Microprocessor Faris Somer (CISC oF RISC oF Bath fetus Seam | esHeux Motorola cise swan 2 x86 case Seeam 3 SPARC sun Sean ARM ARM 1.7.2. Embedding a Microcontroller Microcontolle: VLSI cores or chips for embeded systems are usually among the five steams of families siven in Table 1.5 Table 1.5 Major microcontrollers® used in the embedded systems Seam iron ; Sone GiCor AC ban Svea! 6SHCHxx, HCI2e, HCI6x Motors asc | siveam 28051. s051Bx niet, Philips cis | sem} IC IEA CH, I6FTG and ICIS Mistp owe RISC Cove with CISC funconaity | Steam 4" aticroconrolles Enhancements of CORTEX-M3 ARM, Texas. Philp. | ARMS/ARM? from Philips, Semsung and Samsung and St ST Microelectronics Microelecooes ete ® cx pop icrcons area allows (Hise and Super Tet. Gi) Misi 70,700, MgC a 1M92C amis. (i) National Semiconductor COPS and CRI6 15: iv) Teshita TLCS SS (Tent sven MSP 490 for low oagebatery beter) Seung SAM, (vi Zils 290 e280, 1.7.3 Embedding a DSP ‘A digital signal processor (DSP) isa processor core ot chip forthe applications that process digital signals [For example, filtering, noise cancelation, echo elminatia, compression and encryption applications Just as 8 microprocessor isthe most essential unit of a computing system, & DSP is essential unit of en embedded Intoducton » Embedded Systoms [33] _syslem ina luge numberof applications needing processing of signals. Exemplary applications ae in image processing, multimedia, io, video, HDT, DSP modem and teleommunicaion processing systems, DSPs fs il use in systems for ecognizing image pattern or DNA sequence [DSP as an ASIP isa single chip or core ina VLSI unit includes the computational capabilites of @ pencessor and Multiply and Accumulate (MAC) units. A typical MAC has a 16 32 MAC unit [DSP executes dseretestime, signal-processing insructions. I has Very Large Instruction Word (VLIW) processing capailitis: processes Single Insivction Multiple Dia (SIMD instructions it processes Discrete Cosine Transformations (DCT) and inverse DCT (IDCT) functions. The lauer re used in algorithms for signal analyzing, coding. tering. noise cancellation, ho elimination, comyyessing and dccompressng, ee Major DSPs for embedded systems are from the tree seams given in Table 16, Table 1.6 Important digital signal processor® used in the embedded systems Sesan ‘se Fans Source Seam 1 "Tws320Cxx, OMAP! Texas Sxeam 2 ‘Tigee SHARC Analog Devoe Siren 3 0a Moto Seam 4 PNK 1300, 1500? Philips ‘example, TMSS200G2XX a Fae pin 200 Miz DSP Section 235, 2h roe which ies ida DSP operas odes eon Se 1.7.4 Embedding an RISC A RISC microprocessor provides the speedy processing of instuctions. each ina single clock-eyte, This Facilitates pipelining and superscalar processing. Besides greaily enhanced capabilities mentioned above. thre is grel enhancement of speed by which a insrueton fron sets processed. Thunb” instruction set isa new industry standard thal also gives a reduced coe density in ARM RISC processor RISCs ar used when the system needs to perform intensive computation. or example. ina speech processing sytem, 1.7.5 Embedding an ASIP ASIP isa procesor with an instucton set designed for specific application areas on a VLSI chip or core {ASIPexainples ae microcontroller, DSP, 10, medi, network or ather domain-specific processor Using VLSI design tools. an ASIP with instructions ses required inthe specific aplication areas can be designed, The ASIP is programmed using the insrctions of te following fupetios: DSP, cont! signals processing. discrete cosine transformations. apie fiterng wel comniation pretaca-mplementing functions. 1.7.6 Embedding a Multiprocessor or Dual Core Using GPPs In an embedded system, several processors or dual core processors may be needed to execute an algorithm fast within a strict deadline, For example, in reabtime video processing, the number of MAC ‘operations needed per second may be moce than is possible from one DSP unit. An embedded system {then incorporatgs two oF more processors running in synchronization, An example of using moltple ASIP is high-definiion television signals processing. [High definition means thatthe signals are processed for a nose-fee, echo cancelled transmission, and for obtaining a at high-resolution image (1920 x 1020 pixels) onthe television screen] A cell phone or digital camera i another application with multiple ASIP. processing. 34 Embedded Systems Ina cell phone, a number of tasks have to be performed: (a) Speech signal-compression and coding. (b} Dialing (¢) Modulating and Teansmiting (d) Demodalating and Receiving (e) Signal decoding snd decompression (P) Keypad imertace and display imtrtace handling) Shon Messe Service SMS) peotocal- based messaging (hy SMS message display. For all these tasks a sirgle processor does not suffice. Suitably synchronized multiple processors are used ‘Consider a video conferencing system. In ths system, a quarter commen intermediate format—Quarer- (CIF—is used. The numberof image pixels i jus 14 x 176 as aginst 525 x 625 pixels ina video picture on ‘TV. Even then, samples of the image have tobe taken at ate of 144 x 176 x 30 = 760320 pixels pr second and have to be processed by compression before transmission on a telecommunicaton or Viral Private [Network (VPN). [Note:The numberof frames are 25 or 30 per second (as per te stand udopted) fr real- time displays and in motion pictures. | A single DSP-based embeded system does ot suis to get real-time images during video conferencing. Real-time video processing and multimedia applications mes often need ‘multiprocessor unin the embedded system ‘Multiple processors or dual core processors are used when a single microprocessor does not meet fhe needs of the different asks that execute concurenly. The operations of ll he processors are synchronized to obtain optimum performance. 1.7.7 Embedded Processor/Embedded Microcontroller Anembedded processor isa processor with special features that allow it to embed nlp processes into the system, Realtime image processing and aerodynamics ae two areas where fast, pecise and intensive calculations and fast context switching (from one program to another) are essential, Embedded processor is the term sometimes used for processor that has been a specially designed such that it has the Following capabiliies 1. Fast context switching and thus lower latencies ofthe tasks in Complex real time applications [Section 4.6} Fest context switching means ha the clling program or interpted service rouse CPU resisters save and retrieve fast [Section 46 2 32-bit oF 64-bit atomic addition and muliplcstion, and no shared data problem in the operations with large operands with each operand placed ia two or four registers. [Section 7.8.1] 3. ARIE RISC core for fast, more precise and intensive calculations by the entbeded software, Embedded microconiller isthe term sometimes used for specially designed microcontrollers that have the following capabttes: |. When a microconeoller has intemal RAM, large Mash or ROM, timer, interupt handler, devices end peripherals and here is no external memory or device or peripheral ried forthe given application. 2. Fast context switching and thus lower latencies ofthe tasks in complex eeal ine applications. For example, ARM and 68HCIx microcontrollers save all CPU registers fast ‘Am embeded processors term used for processors with Fast processing, fst context-swtching and atomic ALU operations. An embedded microcontroller is the term used for microconeller that has interul RAM, lage flash or ROM, timer, interrupt handler, internsl devices and intemal peripherals an there is 10 extemal memory or device or peripheral requied fr the given application Inzoducion to Ered Sysoms [3s Complex System Embedded Processors Table 17 gives cfecentprocessrs tht cun embed in & complex system, Table 1.7 Processors in complex embedded systems eaten "aavonage Disaivamage Proceso Generel Purpose When intensive NNowngincuing es for Adio! redundant Microprocessor oman we esgring he procesor execution wis that ae reed, aces we used ot need in he sven ‘nd pple and ‘sem design perc options tue edad and ge ‘meddle 10 be oct in the exter memory exes hips Microcontroler sod with itera No engineering cos for Adina) rien devices and designing the processor manufacturing cos and evita and when wit inlral memory, eduodatsplicaton Combed sofware iso devices and penpherals, unis which are no, te oct in he itera eeded inte sven | ROM oh fate devin | ose sed wit sige No cngincering cost Manufacturing co may procesingreled Involved for designing be high | Inetwctons for fers, the signal precessoe ' image, si, and ideo | ‘and CODEC operations. Single purpose ‘Consol 10 and bos They support oer In-house enginceing proceso and peat’ ae proving unis inthe eos of developmen, royalty pyment for an IB or of procesor and timoso-market con ‘pplication specific Pripterasand devices. Sytem and exerte [se procesor specific halware| I proasses fas Manufacturing cost as | Duat core processor Tosigrifcantyenance Reduced engineing | Reema cal woene potions — cay cero Toast tote prey ‘Eagenig att Ree, pmctagwinas” seein apt fone pt mine meee? oet creosote Pera tae ‘nae opesions ake cost. fd Joa aceon ‘Rodents lav ene | 36 Emoedded Systems ADDSP for motile phones. for example. OMAP of Texas Instruments, uses he efective power dsipation methods of dynamic switching box fr poser supply voltage and operating frequency othe CPL’ cone For » number of upplcitins the DSPs cores may not sfice. Darmin specific ASIPS ave specific insructon ses. For 10s. network. media or security applications, smart card, videogame, palim tp computer, cellphone, mobie- Inert hand-held embedded systems, Gbps transceivers, Gbps LAN systems, satellite of missle systems, we need special processing units in a VLSI circuit designed to function a a procor with an insruction-set fr programmability. These special units are called domain-specific ASIP, 1.7.8 Embedding ARM processor Examples of Seam 4 GPPS in Table 1 are ARM 7 and ARM 9. The core ofthese processors ean be embeded onto a VLSI chip or an SoC. An ARM-processor VLSLarcitecture is avaiable ethers CPU. chip or for integrating it into VLSI or SoC. ARM, Intel and Texas Instruments and several ether companies have developed such processors. ARM provides CISC futionality with RISC architecture at he core. The ores of ARM7. ARMY and their DSP enhancements ae available for embedding in systems. [Refer to hip? \wwticomse!doesfasic/modulslam?.Atm and am htm, ARM integrates with other features (for example DSP) in new GPP, which are available from several sources, for example, Intel and Texas Instrument. Exemplary ARM 9 applications are setup boxes. cable modems, and wirelessdvices sich as mobile handsets, ARM has a single eycle 16 x.32 multiple accumulate unit. W operates at 200 MHz. It uses 0.13 ys GS30 °MOSs.Ithasa ive-stage pipeline, It incomporates RISC core with CISC functions [cinegrates wil » DSP shen designed for an ASIC solution. An example i its integration with DSP is TMS320C35 from Texas instruments [Refer to hip:/www.i.convseidocs/sschmdulesart7 hand arm] ‘Mower performance but very popula version of ARMY is ARM7. It opertes at 80 MH. I uses 0.18 jm based GS20 tim CMOS. Using ARM7, ARM9 aed CORTEX-MB, a large number of embedded systems have recently become available Lately, 2 new lass oF embedded systems has emerzed that aditicnally incorporates ASSP chips or cores in ts design 1.7.9 Embedding ASSP ‘Assume that there is an embedded system for real-time video processing. Redl-time processing arise for ligtal television, high definition TV decoders, set-up boxes, DVD (Digital Video Dive) players. web phones. video-conferencing and other sysems. An ASSP that i dedicated to these sprcific tasks alone provides faster solution. The ASSP is configured and interfaced with the rest ofthe embedded system, Assume thal there isan embedded system thar using a specifie protocol interconnects it units through specific bus architecture to another system, Also, assume that suitable encryption and decryption is required {The outpu bitstream encryption protects messages or design fom passing to an unknown external entity} For these tasks, besides embedding the software, it may aleo be necessary to embed some RTOS features [Section 1.4.6}. I the software alone is used forthe above tasks, i may tke a longer time than hardwired Solution for apliation-speifie processing. An ASSP chip provides such a solton. For example, an ASSP hip from i2Chip (hp ww i2Chip.com)} has a TCP, UDP. IP, ARP and Ethernet 10/100 MAC (Media Access Control) hardwired logic included ino it. The chip from i2Chip, W3100A, is «unique handwvied internet coneetvity solution, Much needed TCPAP stack processing software for networking tasks i thus avaloble as -@ hardwired Solution, This gives output five times fester than a software soltion using the system's GPP. I is also an RTOS-Ies solution, Using the sme microcontroller inthe embedded stem to which his ASSP chip Introduction 19 Embedded Systems (37) imerfaces, Ethernet connectivity con be kde. Another ASSP. which is now avilable. she “Sera-W-Ethort Converter (IIM710(. I des realtime da processing by a hardware protocol stack, Hence change im he pplication software or fmvare sexi provides the most economical and mallet RTOS-solation, ‘An ASSPis used as an addtional processing unit for running application specifi asks in place of processing using embedded software "1.8 DESIGN PROCESS IN EMBEDDED SYSTEM “The concepts used during 2 design process are 2 follows 1. Abstraction: Each problem component i ist abstracted, Fo example. inthe design ofa robotic Sem, the problem of abstract ean Be in ers of contol of arms and moors. 2. Hardware and Software architecture: Architectures shouldbe well understood befor a design. 3. Extro functional Properties: Ex functionals required in the system being developed should be well understod frm the design 4. System Related Family of designs: Families of related systems developed eater should be taken ino considerzion ing designing 5. Modutar Design: Modular design concepts should be used. System designing is fas by decomposition of software into modules hat ae tobe implemented, Modules shouldbe sch tha they ‘an be composed (coupled or imtgrated) later. Etfctve modular design should ensure effective (i) function independence. (i) cohesion and Gi) coupling, (@) Modules shouldbe clearly undestod and should maintain continuity (b) Ako, appropri protection sateies ate necessary foreach module. A modules nt permited to change o madly another mole neionaliy For example, paecton Ion device driver modifying the configuration of another device 6. Mapping: Mapping ito various representations is done from software requirements. For example, dufovin fe ancy eng page flcatcmpegter aan ety Term an censaction mapping design processes are wed in designing. Fv example. ina snp ta to spt can hav der nanbe pls clus, The spe dos no proc cach Pixel and colour indvidoaly. Transom mapping of image is dene by appropiate compression and Norage algorithms. Transetion mapping ix done to deine the sequence of images. 1. User interface Design: Usenet desig san ipevtan prof design Usernerfaceste designed a5 per user requirements, analysis othe envionment and system futons. For example, nan automatic chocolate vering machine ACM) sytem, te user inerface isan LCD mln graphs dispay. can display a welcome messge 2 well ws speify the coins needed tobe ised into the machine Fo cach type of chocolat. The same ACYM may be designed with ouchsreen User nerface (GUT), oF it ‘may be Gesigned with Voice User Imerfaces(VUIs). Any theseimerace designs has be validated by thecustomer,Forexample the ACVM customer who installs emachine must validate message language and messages be displayed before an interface desi can poczed oie implementation Sage. 8. Refinements: Each component and module design need tobe refined erative tlt becomes the ‘most appropiate for implementation by the sofware team. mim “The software design process may require use of Architecture Description Language (ADL). Its used for representing the following: () Contol Hierarchy (i) StrctalPartioning (i) Data Structure and Hierarchy (i) Software Procedures. (=) Figure I-11 shows the activities for software-design cycle during an embedded software development Embedded Systems process and the cycle may be repeated bil less show the verification of specifications. Development oo Anaiyes| 1 | | | il omascrse || ow [Le & | j i, | | Ilr | || | ke eel a /~\ [ee] es
  • a Fig. 1.11 Activities for software design during an embedded software-development process 1.8.1 Design Metrics ‘A design process akesito account design mews. There ar several design mestcs for an embedded system, nd these are listed in Table 1.3 1.8.2 Abstraction of Steps in the Design Process {A design process i called botom4o-top design i it builds by starting from the cormponents. A design process 1 called top-to-down design if it first starts with abstraction of the process and then after abstraction the details are created. Topto-down design approach isthe most favoured approach. The following lists the five levels of abstraction from top to botom inthe design process: Design Mei Power Disipaion | reformance Proces deadlines Emgincerng cost Manufacturing cast Hsiitiy | preter evelopment ime Time-to-marke System and wser safe | Moinrnance Invoducton to Embedded Systems Table L8 Design metrics used in the embedded systems —_—— Deseripion For many systems, paca baery operated syste, suchas mobile pone o digital ‘ama the power consmed by the system i an important fxr. The batery aed to be recharged les fequety if power dissipation is small Instone exeetion ine ia the system measures the perfomance. Smaller exeeton| time means higher peformence. For exile, 4 mile pore vice signals processed between antenna and speaker in O.s shows pone perfomance. Consider another. For frample, 4 igs camers, shooting 4 4M pac sil image in Os shows the camera performance. Thee are numberof processes ia the syste, fr example, keypad input processing. graphic isla etesh oto signal processing and video sera processing. Ths ave deadlines ‘iin which each of them may Be eqired 0 fsh computations ard give resus ‘hes nce keypad GUIs and VU Sie ofthe system is meseured in terms of (phys! space reuied,Gi) RAM in KB and internal flash memory requirements fn MB of GB fr eaaring the software and for dat Storage and i umber of millon lope gle io be hada. Int cost of developing, debugging and testing the hardware and sofware sealed ceinering cos and onetime ecg cos. (Cost of manufacturing cach nit Fesiblity in design enables, witout any significant engineering cot development of| Gieret version of» product and advanced versions later on. For example, sofware fntancenedt by adding entra fonction necessiated by changing enviroment and software reenginesing. time taken in ays or months fr developing the prottype ad nous esting for sstem funcinlites I inclads engineering ime and maklag he prototype ine “Time taken in days or months afer protorype development to put a product or wets and Sysem safety in terms of cel fl from hand or able, the (ea phooe loking bly and tracing bi) and ia terns of user safety when sing a product (or example, utomobile Brake or ego). Maintenance means anges and abtons te system: for example, dingo oping softwar ita and harewre. Example of software rience i oa see or functionality software. Example of datz maintenance is addons Angi, wallpapers, ‘ideo ips in ob phone of extnting card expiry dt a cse of smartcard ample of arate mainfenanosisaddlonl memory o changing the memory sick nail computer sd digital camera (1) Requirements: Definition and analysis of sytem requirement, Is only by 2 complete clarity of the equred purpose, inputs. outputs, uncioning, design metrics (Table 18) and validation requiremen's for finally developed systems specifications that well designed sytem canbe crested. Tere has to be consistency in the equiremedts. 40 Emboddod Systems (2) Specifications: Clear specifications ofthe cequzed system are sunt. Specifications ace «be precise. Specifications guide customer expectatwns from the product. They also guide system architecture. The designer needs specitiatons fr i) hardware, for extmple, peripherals. devices processor and memory specification, i) dat types and processing specications, ii) expecte system ‘behaviour specifications iv) constrains of design, and («expected hie eyele specifications. Press specifications are analysed by making sso inputs on eves outputs on cventsand how the processes activate on each event (inept). (G) Architecture: Data modeling designs of atibutes of dala structure, data ow graphs (Section 62), program models (Section 6.1), software architecture layers and hatUware architecture are defined Software architectural layers areas follows 1. The first layer isan architectural design. Mere, a desig for system architecture is developed. The question arises a8 to how the different elements—data structures, databases, algorithms, contol functions, state transition funtion, proces, dala and program flow-—are to be organised 2. ‘The second layer consists of data-dsign. Questions «this stage areas follows. What desig of data structures and databases would be most appropiate forthe given problem? Whether data organised asa tee ike sruture will ke appropiate? What wil be the design ofthe components in the data? [For example, video information wil have two compenens, image and sound 3. ‘The third layer consists of imerface design Important questions at this tage areas follows. Wht shall be the interfaces to integrate the components? What isthe design fec sytem intreation? ‘What shall be design of interfaces wsed for taking inputs Fom the data objec, stetures and databases and for delivering outputs? What willbe the port structure for eecevirg inputs and transmitting outputs? Components: The foun tayer sa component level design. The question a this stage isa ftaws, ‘What sal be the design ofach component? Thee national requicement inthe design of embeded system, thateach component shouldbe optimised lor memory usige and poser dissipation, Components of hardware, processes, interfaces and algorithms, The following iss the common hardware compenents 1. Processor, ASIP and single purpose procesors in te system 2. Memory RAM, ROM or intemal and externa sh or secondary memory inthe system 3. Peripherals and devices internal and exter othe system 4. Ports and buses inthe system 5. Power source o battery inthe system During software development proorss we can model the components a object-oriented, Table 1. list the stages as component-based objesoriented software development process (5) System Integration: Built components are integrated in the system, Components may work fine independently, but when integrated tay nt fulfil the design mets, The system is made o function and validated. Appropriate ests ae chosen, Debugging tools are used to corect eroneous functioning, Each component and is interface system integrated after te design stage. Program implementation in «language and may use an integrated developmen envionment (IDE), and source code engineering tos, Which shoul follow the model, software architecture and design specifications. Prograin simplicity should tbe maintained during the implementation process. « ‘The design stages range from abstrtion A» detiled designing to verification activites. Continuous ‘refinement in design can be made by effective communication between designers and implementers. Soflvare design can be assumed to consist of four layers: architecture design, dala design, interfaces design and ‘component level design. lnvodton Embedded Syste («) Table 1.9 Components-based object-oriented software development process ‘Actes ior Model Deficiency Suge | Component tht could be wed in software development identi Suge? Selection of availabe clases (single logically bonded 70098) OM Ke or bust nxn sottare component rier ary eee Sips} Sertcomponets, wich ar avalable and eusable by re-engvcering and case the ele eich ae onsale components ae at avaiable in regu Stage 4 Re-ngincer components and crete ueavalbe components weit Stage S Couset software fom te components and tes them | sa lee Actions at each step Research by software engineering experts have shown that on an average, a designer needs to spend about 50% of the time for planning analysis and design, 40% for testing, validation and debugging and 10-15% on coding. Action required tobe taken a each step inthe design process sisted in Table 1.10 6 eave conte il fl validation of software Table 1.10 Action to be taken at each step of design process ‘Benga Wate Desripion Anatyis, Design i arly “The ces of sali i aed to improve design to moet specications and mets Step for improvement Verification Sysem design must be veiedw ena that mets the design mts gven in Table 1.8 1.8.3 Challenges in Embedded System Design: Optimizing Design Metrics Following are he challenges tha arse during the design process. Amount and type of hardware needed: Optimizing the requirement of microprocessors, ASIPS und single purpose processors in the system on the bass of performance, power dissipation cost and other design metres are the challenges ina system design. A designer also chooses the appropriste hardware (meniory RAM, ROM or internal and extra flash o secondary menor. peripherals and devices intemal and external ports and buses and power source or battery) taking into account the design metrics given in Table 1.8: for ‘example, power dissipation, physical size, number of gates and the engnecring, provtype development und manufacturing costs ‘Optimizing Power Dissipation and Consummpion: Power, consumption ding the eperaionl and ile sate of system shouldbe optimal. The following metheds are used to meet the design challenges, Clock Rate Reduction Power disipation typically reves 2.5 pW per 100 kz of reduce tock rate So reduction from 8000 kHz to 100 kHz reduces power dissipation by about 200 IW, which ic nary similar to-when the clock is nonfunctional. (Remember, total power dissipated (energy required) may not reduce. This is because on ducing the clock rate, the computations will ake alongs tme nd total energy required equals the power dissipation per second multiplied by computation ine} fa] Emboted Systems bad Te power25 Wt typical te esl dspaton ded o pea ins nd few ter ais By psa eck a ler fetency odin the powerdown noth pcs th drapes Sra) Power rd teat genre de) Kai gue nlc oes {beveled owe sion wine ats Wadatd RF (Rade Fcc) power defends on he RF Sone ne gn ih ede oe ona in“ON" stress vee asa neo SENMOSPET uanior and Oat ede eat goraion Voltage Reduction Inportable or hand-heddevics such as acellular phone, comparedto 5 V operation, ‘aCMOS ercuit power dissipation reduces by one sath, ~(2V/SV},in2.0 V operation. Thusthe time intsvals reeded for recharging the batlery increase by afactor of six. Wait, Stop and Cache Disable Instructicns An embedded syste may ned tobe run continuously, ‘without being switched ofthe sytem design, Uerefoe, is constrained by the need to limit power dissipation ‘while itis ON but sin idle state. Total power consumption by the system while in eunning, waiting and ile states should be limited. A microcontoller must provide for executing Wait and Stop instructions forthe power down mode. One way to reduce power dissipation ito cleverly incorporate into software the Wait and Sop instrtions. Another i to operate the sytem at the lowest voltage levels inthe ile state and selecting, power down mode in that state. Yet another method ito disable use of ein structural Units ofthe processor for example, caches—when not necessary and to keepin disconnected sate those structure units that are not needed during «particular software execution, fr example timers or 10 units. Operations canbe perfrmed at low volage of educed clock rate in order to contol power dissipation. For ‘ebeded system software, performance analysis during its design phase must ala inclode the analysis of power dissipation during program execution and during standby. An embedled system has to perform tasks continuously From power up to power-off and may even be kept “ON” continuously. Clever eal-time ‘programing by using "Wait and ‘Stop insirections and disabling certain units when not neded is cme ‘met of saving power during program execttion Process Deadlines Meeting the deadline of all processes in the system while keeping the memory, power dissipation, processor clock rate and cost at minimum is a challenge Flexibility and Upgrade ability Flexibility and uperede ability in design while Keeping the cost ‘minim and without any significant engineering cos isa challenge. Flexibility and upgrade sbiity slow different and advanced versions ofa product ote inroduced in the market later on Reliability Designing a relble product by appropriate design, testing and thorough verifeation is ctallege. Te goal of testing is to find eros and o validate that the implemented software sas pr the Specifcion and eqiement Verification fest an activity to ensure pei function ae eorecty ‘mpeneated.Vaaton refers to an activity wo ene tha the system hat hasbeen created is a per the requirement ageed upon tthe analysis phase, an to ensure is ait. “1.9 “FORMALIZATION OF SYSTEM DESIGN Farmalizaton of system design i done using a top-down approach by abstraction (Section 1.82) and by + Detling equirements and specifications of hardware and software Introduction to Embedded Systoms ‘+ Dotining architectures of hardware and software + Covdmg and impemsntaton a per architocture {Testing validation and verification of system Since a diagrammatic mode! clears the design conceps beter than abstraction, 2 modeling language, foc formalization ean be used, The Universal Modeling Language (UML) is used. In UML. a designer deveribes the following 1. "User Diagram’, “Object Diagram’, ‘Sequence Diagram, ‘State Diagram’. “Class Diagram and “Activity Diagram 2. Clases and Objects, which describe dently, atrbutes, components and behaviour 3. Inertances of the clases and objects 44 Interfaces of the objcs ad their implementation atthe objects 5. Strvetural deweription of the dexign components 6. Behavioral description in toms of sate, sate machine and signals (Section 6.3) 7 Se Evens desertion ton 65 will describe UML in detail. Chapters 1 and 12 will describe the model design examples detail, “1.10 “DESIGN PROCESS AND DESIGN EXAMPLES 1.10.1 System Design Process Examples Chapters 11 and 12 wil deseribe design examples in det 1.10.2 Automatic Chocolate Vending Machine (ACVM) Lets consider an automatic chocoite vending machine. This interesting example given here helps reader to understand several concepts of programming an enbeided system as 3 muliasking system Figure 1-12 shows the diagrammatic representation of ACYM, Assume that ACVM has following ceomponent: [thas Keypad on thetop ofthe machine. That enables child to interac witht when buying a chocolate “The owner can also command and intract wit the machine 2. Ithavan LCD display nit on the op of the icine, It displays menus, text entered into the ACVM. ‘nd pitograms, welcome, thank you and other messages. Ic enables the child as well asthe ACYM, ‘owner to paphically interact with the machine. Ils displays time and date. (For GUIs, he keypad land LCD display units or uch seen are basic units.) 3. Ithas coin insertion stot anda mechanical coin sorter so that child can insert coins to buy a chocolate. Tthas a delivery slot 50 tht cld can collect the chocolate and cons, if refunded 5. Ithas an lnteret connection port sing a USB based wireless modem so that owner can know stats ‘ofthe ACYM sales fom aremee location ‘ACV Functions Assume that ACYM functions areas follows: |. The ACVM displays the GU anf the child wishes to enter conactinformation, birthday information ‘or get answer to FAQS; it splays the appropriate menu 2. Tedisplays a weleome messege when in ide state, I also continously displays time and date atthe Fight botiom corner of display seree. It can also intermittently display news, weather data or ‘advertisements or important information of interest daring ide state («] emoesia Syston s 4 ‘When firs coin i inserted. a timer also stars. The child iv experted ts insert sl requiee! eins in 2 minus. Alter? minutesthe ACV will display a query to the chil if the child docs not insert salfclent coins. Te the query is not anywered the coins ate refunded. Within 2 minutes if sufficient coins are collected, it displays the message. “Thanks, wat for few ‘moments plese", daliversthe chocolate through the delivery sll and displays message. “Collect the chocolate snd visit again, please” Hardware units _ACVM embeds the following hardware units 3 4 Microcontroller or ASIP (Application Specific Instruction Set Proces-or) RAM for storing temporary variables and stack ROM for application codes and RTOS codes fr scheduling the tasks Flash memory for storing user preferences, contact data, user address, user date of birth, user iemiticaton code, answers of FAQs “Timer and interrupt controler A TCPAP port (Iniemet broadband connection) tothe ACVM for remote conto and forthe ownee to ei ACYM status reports ACM specific hardware to sor cons of different denominations. Bach denusninatio coin generates ‘se of stats and input is and port-incerrypss. Using an ISR for that port, the ACYM process eas the port status and input bits. Te bits give the information about which coin has en inane. ter cach read operation, the satus bits are veset by the routine Power supply a=) {Use _wweeiess_} Moser [tester [eerste Fig. 1.12 Diagrammatic representation of the ACVM Software components ACVM embeds the following soltware components 1 3 4 s. 6 Keypad input red task Display sk Road coins ask for find Deliver chocolate task TCPNP stack processing task TTCPIIP stack communication task ins sted 1.10.3 Smart Card nN ‘Smart card is one othe most used embedded system today Is used for evedit-eit bankcard, ATM card, e-purse or e-Wallet card, identifeaton card, medical card (Tor istry and diagnosis details) and ead for @ Irroducton to Embedded Systems 45 number of new innovative applications. [Reader may refer to a frequently updated website. tpi! wor sguthery @ia.ne fr the answers of Fequentl asked question about card. |The security aspect of ‘paramount importance for swurt card use. when used for financial and banking-elaed vansictions TRcoder ‘may cefer to huip//wworhome hkstarcomalanchan!papertsmartCardSecurty! and hip.J/www rescarch, ipmcomsecure_systemssard hum fur details ofthe card-securty requirements | ‘The smart cai is a plasie ear ISO standard dimensions, 85,60 x 53:98 x 0.80 mm. [isan embedded ‘system on acard SoC (System-On-Chip 150 recomnmended standards are IS07816( 0 4) fr host-rauchine ‘contact-based cards and 18014443 (Part A or B) lor the contactless cards, The silicon chip is just few ‘multimeter in sie and is concealed in-between the layers ts very small size prec the cad from bending Figure 1.13 shows embedded-system hardware components for a contactless smartcard ‘A Embedded Systm Contsel.ies St ard Components eer ems (erase! aA ta ratio aoe ee one 77 le [eer 1p Tima [ime na | mptece | ret Cansoter ‘snc’ | ones Key Weasor | ‘Crest ‘System Power Sirly onca Fig. 113 Embedded hardware components ina contactless smart card Embedded Hardware ‘The embuided hardware components areas follows ‘+ Microconieoller or ASIP RAM for temporary variables and sack (One time programnchle ROM for application codes and RTOS codes for scheduling the asks Fash fr storing user data, ser aes. user identification codes, card umber and expiry at “Times and intapt contol ‘carieeqoncy 16 Mie goneting cuit and Amphi Interfacing cite forthe 10s Charge pump fr delivering power othe ante for ransmision and for syst iris. The charge pp tres chage fom recived RF (rai frequency) a the card antenna in its vicinity. [The charge ump sasimpecicithat consis ofthe diode and bigh vale feraelecics materi based capacitor “The dels ofthe basic hardware units rs follows: sd Shifted Key (ASK) modulator 4% Embedded Systems 1. The Microcontroller used can be MC5SHCIIDI or PICIECRS or a smartcard process Philips Smart XA ora similar ASIP Processor, MCSSHCIIDO has 8 KB intemal RAM and 32 ks EPROM and 273 wire protected memory. Most cards we 8-bit CPUs. The recent introduction inthe cards is of {1 32-it RISC CPU. A smartcard CPU should have special features, fr example, security lock. The Tock is fora certain sections ofthe memery. A protection bit atthe mirooontolle may protect | KIS ‘or more dats From maification and access by sn extemal source or instractios outside that memory ‘Once the protection bit is placed at the maskable ROM in te mierocontoley, the instructions or data ‘within that part ofthe memory are accessible fom instructions in that part only Ginter) aed not accesible from the extemal insrutions or insrctions ouside that part. The CPU may disable wecess by blocking the write cycle placement a he data its onthe buses For instructions and data protection at the physical memory ater cetin phases of card iniializaion and before issuing the card to the User Another way of protecting iss Follows: The CPU may access by using the physical addresses, which re diferent fom the logical address used in the program, 2. ROM is used i the card. The usual size is 8 oF 8 KB Fr usual or advanced cryptographic features in the card, respectively, Full or put of ROM bus activates only after a security check. The processor protects apa of the memory from access. The ROM stores the flfowing. i. Fabrication key, which is unique secret key fr each ca. It is inserted durin fabrication. ii. Personalization te, whichis inserted after the chip is tested on a printed circuit board. Physical, axdeesses are used in the testing phase. The key preserves the fabrication key and this key insertion preserves the ex personaliation, Aller insertion of this key, RTOS and applications use only logical adicesses ii, RTOS codes is. Application codes ¥_Avulilization Tock to prevent madiication of two PINs and to prevent access to the OS and pplication instntions, It stoes afl the card enters the utilization pha, 3, BEPROM or Fash scalable. These means that onl that put ofthe memory required fra particular operation will unlock for use. The auhorier wil use the required part: the application will we the other part. I is protected by the access conditions stored therein. lt toes the following: {. PIN Personal Identification Number. the allotment and writing of which is bythe authorize for ample, abank)andits seis posible ty the late only by using the pesonaliationand fabrication keys. It for identifying the ead user in Future transactions. Card user is given this key Altematvely, nifiable password is given tothe user and password opens the PIN Key. ii, An unblocking PIN for use by the authorizer (say the bank). Through ths ey. the card iret ‘entities the auhorizer before unblocking. Dats ofthe user unblocks forthe authorizer and Storing of information onthe card is posible bythe authorizer through the host ii, Access conditiors for various hierarchically aranged da ile, iy. Cand wer dat, for example, name, bank and branch identfiaton number and account number (or health insurance details vs Data post issue thatthe application generates. For example, in case of e-purse, the details of previous wansacions and curent balance. Medical hisiory and diagross dtalls andor previ insurance claims and pending insurance claims record in ease of a medical car vi also stores the application's non-volatile data vil Invalidaion lock sent by the hos after the expiry period or ea misuse and user account closing rexucat I hacks le data files ofthe nsx or ekencitay individual ile or both, 4, RAM stores the temporary variables and stack during eard operations by cunning the OS and the applicaion Introduction to Embedded Systems. far J 5. Chip power supply voltage exact by scare pump eitcut The pump extracts the eae fran the ‘signal rom the host analogous to what mouse desi a computer and delivers the regulated voltage tothe aid chip, memory and 10 systom, Signals cas be Frm antcana or rom lock pin. na typical curd operation axing 0.18 technolo. 1.65.5 V isthe teshold init and for. pn ieenology, 271055. 6, 10 System of chip and host interact thewugh asynchronous svial UART (Section 32.3) a 9.6 k or 1116 of 115.2 k baud. The chip inerconmics to card hosting sjstom (reader and writer) etter Through the gold contacts oF though a centinster sized antnaa on each side. Te later provides ‘contactless inerconnection between the 10 pins which are mean or contact based interaction, RST {Reset Signal fom hast) and Clock (Hem hos) 17, Wireless Communication foc 10 interaction i hy rations dough the antenna coils fr coat interaction. The card and host interact tough a card modem and a ost modem, The aplication rococo data unit (APDU) isa standad for communication betwen the ear and hest computer ‘Modulation is with 10% index amplitide modulating carrier of 13.66-13.56 Mbps ASK (amplitude shied keying) suse forcontactess communication at dts ratesot~1 Mbps. One-sixtenth frequency subeatier modulates though BPSK (Binary Phase Shifted Keying Embedded Software Smart card eters ihe folio 1. Boot, initsisstion and OS peograns 2 Sit card seve fle system 3. Connection establishment and verination | Conimaication with host 5. Cryptography algorithm 6. 7 softwite components: Host authentication Cand authentication dion paraneers of rvent new data sen by the bot (or example, present balance let) “The sinart card is an exeimplry secure embedded system with security Softvare. The card eth. cryptoprapic soiware, Embedded software inthe card neous special Features in its operating system ove and above the MS DOS or UNIX system features. Special features needed areas fllows 1. Proicted envivnnen.H-mcans vtiware should be stored in he proteted pat oF the ROM, 2. Restricted! rosie ensrnament A. IOS, every method, class and rn time idea soul e sealable 4S Code-sive termed unl be epitnun, The system needs shoud mo exceed 64 KB memory. 5. Limited use of datatypes: multidimensional arays. kone Gb inegcr and eating points ad very limited use of the roe handlers, exceptions (Section 4.22), sigals (Sections 6 Sand. 10), stialization, debugging und profiling [Serialization i the process of converting an objet ino dat stream (oe transfering itt network or From one proces 10 snther. Te deserialize dat arc the receiver end}. 6, A three-layered file sytem forthe dats. One file forthe maser flew toe al ile headers. header ens File status, access conditions andthe ile lok. The second file is a dedicated file to hold file frouping and headers ofthe immedi sucessor elementary files ofthe group. The third file isthe elementary file hold he file header and its le data, 1. Ther is eter a fixed length fle management ora variable length fle management with each file im __ having a predefined offct 8. Clases Forte network, sockets, connections, data grams, characte input output and steams, security management, digital-cenificaton, symmetne and asymmetric keysbased cryptography and digital signatures ’ Emboddod Systoms, 1.10.4 Digital Camera Digital cameras may have 4 1 6 M pine! sil images, clear visual diplay (ClearVid) CMOS sensor. 7 cin wide LCD photo display screen, enhanced imaging processor, double anti blue solution and high-speed provesting cine, 10X optical and 20X digital zooms and can also record high definition videoclips. It therelowe has speaker microphone(s) fer bigh quality recorded sound. I is an auiivideo out port for conrectng to a TV/DVD player or compute. Letus assume that the camera is sill jas a camera. Figures 1, 14a) and (b) sow hardwae and software ponents in simple digital eamera, Assume thal the camera has the following Components | [tebarteaecsentartone ven] [Kor oo | | =m ee | [Dee ——- Fig. 1.14 (a) Digital camera hardware components (b) Digital camera software components 1. thas keys oa the camera. That enables a usr to operate the camera. thas navigation keys to mivigate Uhrough the images back and Forth. 2. Shuter, lens and charge coupled device (CCD) array sensors for images in sizes 2992 x 1944 pixels = 5038848 pixels, YGA (E-mail) 640 480 = 307200 pixels, 2592» 1728 = 3.2 M pixels, 2088 x 1536 pixels = 3 M pitels.or 1280 x 960 pixels = 1 M pixel. 3, Tihas a good resolution photo quality LCD display unit onthe hack of camera to show photographs ‘recorded video-lips. It displays text suchas image, shooting data and ie and serial number. In isplays messages 1 displays the GUI menus when the user interacts with the came. 4. has agelf-timer lamp for fash 5, Intemnal memory lash to store OS and embedded software, and limited nutes of image files 6. Flash memory stick of 2 GB or more for large storage. - Introduction to Embedded Systeme [4 7. teh Universal Serial Bus (USB) por (Section 3.10.3 or Be computer and printer, ih interface. which cannes i toa Camera Functions Assume tht the camera funetions is fll |. teisplays the trame view on the LCD screen so that usce ci aj the camera inclination before ‘hooting the frame 2 Walsplays the saved images onthe LCD using navigation keys 3. When a key fr opening he shulter i presed, the Flash ann glows and the sf timer ciruit switches of the lamp astomaticaly. 44. The rae ight fallson the CCD array, which wansmits tho bits foreach peli each row in the Fame through an ADC. Bits from dark area pines in each row are sed for offset comections inthe CCD signal fr light intensities in each rv. ‘The CCD bits ofeach psel in each row and column are offset crtected using a CCD signa processne «CCDSP), 6, The procesed signa te compressed using 2 PEG CODEC and saved inne jp file foreach rams. [A DSP does compression using the the discret cosine transformations (DCTs) and decompression by inverse DCT. Thoreater.it also does Hulfman coding for JPEG compression. A DAC send the inputs forthe display unit. The DAC gets the inp from the pixel pmecessor. which et the inpus fom the JPEG files forthe saved images snd gets input diretly fom the CCDSP Hough the pixel processor or the frame inthe present view” igital Hardware units The camera embeds te following hardware units |. Mierocontoller oF ASIP 2 Mltiple processors (CCDSP. DSP. pixel processor totes) 3. RAM for storing temporary vribles and stack 4. ROM lor application cades and RTOS codes Fr scheduling tasks 5. Tine fash memory Tor storing see preferences, contact dl, user adress. user date of hi. usce idenieaton code. ADC, DAC and interut controller (Sections 1.3.3, 13.5. 147 and 13.11) USB controller (Section 3.10.3) Direct memvey access conrier (Section 4.8) LCD contmller (Section 334) Baery Software components. The camera embeds the following software components CCD sia geocensng for offset correction 2 JPEG coding 3. JPEG decoding 4: Pixel processing before display 5. Memory and file systems 6. Light. lash and display device drivers 1. COM, USB port and Bluetooth device divers for port operations for printer and computer ‘communication conto on 1.10.5 Mobile Phone The mobile phone today has a large number of features. I has sophisticated hardware and software. {9} Embedded Systems Hardware units» mebile phone embeds an SoC (System-on-Chipy incense follwing hardware units |. Microcontroller or ASIP JAn ASIP is configured to process enewtiny and deciphering and another tes the vice compression, Third ASIC dal, modulates, demodulaes. interfaces the Keybosrd and touch serecn or matte fine LCD graphie displays, and processes the data input and recall of data Fro mesnoryh 2, DSP core. CCDSP, DSP, video, voice and pixel processors 3. Plash mentor stick, EEPROMS and SRAMS 44, Peripheral circuits, ADC, DAC and interrpt conolier 5. Ditect memary access controller (Section 48) 6 1 LCD contcller (Section 3.3.4) Bauery Software components The mobile phone sofware development tools are a follows: 1. OS (Windows Mobile, Palm, Symbian) oF BREW 2) Java 2 Micro Editon J2ME) along with KVM asa Java Viaual Machine Section 574) 3. Java Wireless toolkit with JDK (lava Development Kit) “The mobile phone embeds the Following software component TE Memory and filesystems 2. Keypad, LCD, serial, USB. 3G or 2G pont device drivers for port operations fr keypad, printer and computer communication contol 3. SMS (Short Messaging Service) message creation and communicator. contact and PIM (personal information manager, task-to-do manager and ena ‘Mobile imager for uploading pictures and MMS (multimedia mess “Mobile braser for access 1 the Web Downloader for Java games, ring fone gnes. wall papers Simple camera with (Section |.10) Bluetooth synchronization. IDA and WAP connetions support (Section 3.13) ervey 1.10.6 Mobile Computer “The mobile computer has Windows CE or Windows mobile as OS. [thas w touck sereen for GUL, The wer uses sys to enter commands. Ithava vieual keypad (the keypad displayed en the screen and entries of text and comimands is through te stylus. In addition to phone, a mobile computer bas following software components {. OS (Windows CE, Windows Mobile, PocketPC. Pali OS or Symbian OS) Touch sereen GUIs, memory and file systems ‘Memory stick Outlook. Internet explorer, Word, Excel, Powerpoint, and handwritten text processor Applications or enterprise software 1.10.7 A Set of Robots ‘Consider a set of robots. One robots the master robot (music director) and seven ae slave robots conductor). Assume that thestisused to ply an orchesta Figures 1.14) and (b) show hardware and software components {nthe sot of robo. Assur: that the robot has the following component 1. The master robot signals the commands and slave robots play accordingly Introauton to Embedsed Systoms e) Each mbt is asumed to have ive degrees of freedom. Each robes hava mochanical ystem of five degrees of freedom. At each degree of freedom, thre is a servociotor A servomatar conto by PWM methud (Seetion 1.7). Each motor fs controlled in squence tlt the robe pron the esiced etn 3. sch root hava mierocontraller with expansion ports, Po. P8. Actually axngle ASIC cam perfonn ‘line port fonctions of a microcontroller, Howevesnce the engineering cst of ASIC development is igh. «general purpose microcontroller 6BHCT2 or 8051 is use. “The port eutpuls comect he metors snd PWM outputs dive the motors in cach robo Each robot has eral 10 with EDA protocol (Section 3.13.1) Tneral memory Mish to store the OS, embedded sofware and limited amount of music There is a mas file processor Fo playing the music. Slave robots have speaker outputs fe playing ‘Master Robot Functions Assume that maser robot functioning iv a follows |. Hreceives comands from s emote controle to stat and sop the rasic and the code forthe speviic orchestra toe played 2. sends PWM signals othe pos for moving the sticks in oth hands as per the program, 3. Wesublishes and binds the sockets the vitua devices) connection with the slaves. I sends the signals through rockets using DA protocols. The byte streams respons to the clients ae as pe the Music File tobe played by the save ‘Slave Robot Functions Assume tat slave robe functioning i as follows: 1. establishes and binds the sockets (he viral devices) connection with the mast 2. Mt receives rom a miner socket the commands accep () and write (it alo receives commands 10 start and stop music ad the code forthe specific orehesta tobe played receives the signals through sockets using IeDA protocols. The bye steams from the server areas per the music ie being pled, Hardware units Robots embed the following hardware uit 1. Microcontroller or ASIP 2 Masi file procesor 3. RAM for sexing temporary variables and stack 4. ROM for application codes and RTOS codes for scheduling bot setions and asks 5 Timer Mash meniory for storing wer preferences and musi Files 6 IeDA controller (Section 3.13.1) 7 8 Dincct memory access contllr (Section 48) Powersupply source or battery Software components Robots embed the fllowing sofware components 1, Socket functions 2. Music coding 3. Music decoding 4. Memory and ile systems 5. Light, flash and display device divers tam 6. IrDA and socket port device drivers 17. Motor devers 8 10 15Rs ) 52 Embedded Systems ~iScoto,Tener |_owac: Pune | [se tseen i usuoh or rOAos es Fig. 1.15 (o} Hardware components in the set of robots (b] software components in the set of robots in which a master robots signals the commands and slave rabots play according to the signals from the master “1.11 “CLASSIFICATION OF EMBEDDED SYSTEMS ‘We ean elasify embedded systems into thre type as follows, 1. Small scale embedded systems: These systems ate designed with a single 8 or 16-bit microcontale: Fy have ite adware and softwar complies ad inset ene eign They mayeven ebay ops When deeaping ened swash anc semble dcr meted develomen envsanmen(IS8 ose the mica or procevor ular te nai programming os Ying" lneue grams se compa io the aebly and execuabe codes te ppromy located ne spent meray he setae ak to whi the memory avalble and keep WO te need ty litt poverdaspaton when Ue 1. Medium scale embedded systems: These ssems ae uu designe with ingle or afew 16- or 32-bi micecontoner: DSPs RISC. Ths systems may aso employ the ready aaa single perce proceso od IPs espind later Yor te ato anton for expe Ds ineracing [ASSP« and IPs ay ao have to be appropri configured by he SskmSfate before ing ints ino she sen] Media sealed syiems hae ot haar sd sft competes For compe stare Sein.efelowin opammagolear sve ices Cevtav RTOS, sore cove ensnsing ol ims dugg a at ieee Aevelmestenvionneat Siar el so provide solaton 10 adware complesiies 5. Sophisticated embedded systems: Sopisieted embeded system hae enous barwae anon compleisand ray ce sve IP, SIPs, sable posse congue pce ti programmable less They ae wed fr eating ede aie tha ee Rarote and Sotvarecodesign an compen ht ave oe netted ial stem The a eonsaine by te prcesing sessment hart nts Cerin sofa tons ach neyptn rroguction to Embodied Systems e and deciphering algorithms, discs cosine tansformation and inverse rnsformation agoritnss TCP? IP protocol stacking nd netor: rier functions are implemented in the harvaré to obain kita speeds. The software implements some of the functions of the hardware resources in the ssn ‘Bevelopment tots fr these systems may not be readily available a a reasonable cost or may not be valle all In some cases, « compiler oF eget compiler might have tobe developed for these [A retagetable compiler is one that configures according the given target eafguraion in em "1,12 “SKILLS REQUIRED FOR AN EMBEDDED SYSTEM DESIGNER “Anembeded sytem designer has o develop product using tre aailable too within the given specifications, cont and time free. (Chapters 6, 13 and 14 will cover the design aspects of embedded sysen. 1. Skills for Smal! Scale Embedded System Designer: Author Tim Wilmsinurs i his book ‘sats that the following skills are neded in the inividua::""1 or team thats developing small Scale ymem: “ull understanding of microcontrollers witha basic knowledge of compute architecture, digital electonie design, software engineering, data communication, contol engineering, motors and ctuators, sensors and measurements. analog eleconic design and 1C design and manufacture” Specific kills wil be needed in specifiesuations. For example, contol engineer knowledge will be eee for design of contol systems, and analog electonic design knowledge willbe needed when design the system interes. The basis aspects of the following tops will be described in this book eo ‘prepare the designes wha aleady hak & good knowledge ofthe microprocessor or microcontoller to be used. (i) Computer architecture and orgarination. Ci) Memories. (ii) Memory allocation (iv) Interfacing memories. (v) Burning (a term used for porting) the executable machine codes in PROM or ROM. (v! Use of decoders snd demultiplexers. (vi) Direct memory access, (Vi) Pons. (vi Device rivers in assembly (x) Simple and sophisticated buses. (x) Timers (xi Inteupt servicing snctanism. (i) C programming elements. (aii) Memory opinnizaton. (xiv) Selection of hardware and microcontole, {xv Use of ty Circuit Emulators ICE}, erose-usemblers and testing equipment (ivi) Debugging the software and hardware bugs by using st vectors. Basic knowledge in other reas—software engineering, da cosmmunication, contr enginesrng. notors and actuate nd measurements, analog eletronic design and IC design and manvfacture—can be obtained from the standard text books avslable. A designe interested in small-scale embedded systems may nia need at ail concepts of interrupt latencies and deadlines and their handling, the RTOS programming tons described in Cages: 9nd 10 andthe program models given in Chapter 6, 2. Skills for Medium Scale Embedded System Designer: ¥aeledge of *C'1C#+lhava programming, RTOS programming snd program modeling sis are mst to design medium-scale tmbedded-systein. Knowledge of he following are etal.) Tasks or threads and their scheduling by RTOS. (i) Cooperative and preemptive scheduling. i) Iter processor communication functions. iv) Use of shared dl. and programing the cca setions andre-entrant functions. (v) Use of semaphores, mailboxes, queues, sockets and pipes. (vi) Handing of erat latencies and meeting task deans (i) Use of various BTOS functions. (vi) Use of physical and virual device drivers. [Refer vo Sections 426, 7.10and7. 11] Chapters 4t0 1 give detailed deseriptoas ofthese seven along with examples and Cher 11 and 12 provide on understanding oftheir use with de hep of casestudies. A designer must haan: to an R708 programming tool with Application Programming Interfaces (APIs) forthe specific microcontroller to be used. Solutions 0 various Functions like memary allocation, timers, device divers and interrupt handing mechanism ae readily availabe asthe APIs of hx RTOS, The designer needs to Embedded Systems ‘now ony the hardware organizaviomand us of tes’ APIS. The microcontroller press thn epee small sytem element for he designe ad ite Knowledge may suc, 3, Skills for Sophisticated Embedded System Designer: A wa is needed to e-design ant solve the high level complexities of hardware and software design. Embedded system haste engineers should have skills in hardware units and hasie knowledge of (C7AC+ and Java, RTOS snd ‘other programming tools. Sftwareengincer should have basic knowlege in hardware and ar knowledge of. RTOS und ther programming tos A Final optimum design solu sthen cbtined by system integration, ‘Summary ‘An embeded sytem is one thit hs embedded software it computer hawae, which makes it ayo Software tots. N&2~ 2G BRK SRR RORSL BO In this chapter, we wil lear the following 1 8051 architecture in brief and its processor. memory. ports, Counterstimer Seria 10 and interrupt handler wits 2. Real world wterfacing, and internal and external buses that interconnect the rocessor with the system memories, 10 devies and all other system units Imverfacing examples with keyboard, displays, ADC and DACS ‘Advanced processors x86, ARM and SHARC architectures Processor and memory organization ‘Insarucion-level parallelism and superscalar, processing, pipelining and cache tuuts for improved computational performance of the processor by faser ‘rogram execution Various types of memory and their uses Devices and memory addresses allocations Performance metrics to measure the performance of a processor 10. Processor selection for embedded sytem 1, Memory selection for embedded system ” 2.4 “BO5T ARCHITECTURE ‘The following subsections summarize the 8051 architecture in brief. A ceader may refer toa standard text for details 2.1.1 8051 Microcontroller Architecture Figure 2.1 shows the architecture ofthe classic 8051 microcontroller. Classic means the original version, based upon which new enhancemetts and vesions are provided ‘The classic version consss of following hardware: 1. A 12 Mie clock, Processor instruction cyte time is! us. 2. An B-bit ALU. The internal bus width i 8 3. CISC Complex Insirvction Set Computer) architecture. (CISC provides many modes for addressing operands in arithmetic, laical and other instructions, Several complex instructions take more than one cycle time. Complex instuetions implement in hardware not by separate hardwired logic circuits for each instruction but by a microprogram contol circuit} 4. ‘Special bit manipulation instructions. 5. A program counter, in which the inal default reset value defined by the processor is 00000, 6. A stack pointer, in which the inital defaut value defined by the processors 0x07. 2 2, 13. (ase) Fig. 218051 Architecture {A simple architecture, with n0 floating-point processor, no cache, no memory management unit mo ‘atomie operations uit, no pipeline and no instruction level parallelism, (Sections 2.3 and 2S). There jis no DMA controle (Section 4.8) in the classic and mast other versions. 'A Harvard memory achitectre(Setion 242). The program memery and data memory have separate ‘adress spaces from 0x0000 ad separate control signals). (On-chip RAM of [28 bytes. The B052 version provides for RAM of 256 bytes; 32 bytes of RAM are sso used as four bank (ets of registers. Each estr-set (bank) thus has eight registers. The external datafstack memory canbe add upto 64 KB in most versions In cetain 8051 enhancements this iit has been enhanced to 16 MB. ‘There ae special function registers (SFR). These are PSW (processor stats word), A (accumulator), B tepiser, SP (stack pointer) and resisters for serial 10s, times, pots and interrupt hander. 8351 version has on-chip ROM; 8751 version EPROM; 8951 version has on-chip EEPROM or flash ‘memory of 4 KB. Several versions provide fr higher capacity ROM. Additional program memory can be added extemally upto 64 KB. In extended 8051 and unified address space versions (8051 EX and [MK versions) this limit hasbeen extended to 16 MB. ‘Two extemal interrupt pis, INTO and INTI Four pots PO, P].P2 3p P3 of 8 its each in single chip mode. Section 2.1.3) Thee are two timers (Section 2.15) anda serial interface (SD. Itcan be programmed fr three fll duplex UARTT modes for ‘serial TO. [JO with each bit ofa word successive transmitted onthe data ine fr atime interval} The ‘Sl can also be programmed fo half duplex synchronous 10 (Section 2.1.6). tc Embodsed Systems 114 Classic version has no pulse widlh modulate ad prs on support v9 DAC. (Seetion 1.3.7) thas no modem, 0 watchdog timer, 0 ADC. Ceraia vrion spon witchog timer and ADC. Siemens SAB 80535-Nsuppors ADC with programmable rogram codes rea trom program memory). {sis because of the use of Harvard architecture (Section 22) for system memories ‘An iterfacing circuit consists of decoders and demultiplexers and is designed according tothe available como signals and timing digrars of bus signals. Ths circuit sonnet al the units processor tvemory and the 10 device through the system buses Is apart ofthe glee circuit used in the system and in GAL (generic array logic or FPGA. Figure 28 showsa simple diagram of typical computer system in which buses provide an interconnecting rnetwrk between the processor, memory, and IO systems. In real world interconnections, the network Foxes by buses in the main subsystems. “The system bus imerconnects the subsystems, which interconnects the procesor withthe memory systems andalso connects another st of signals called the 10 bus. Figur 2.10 shows the sytem and IO buses, Iisa twoevel bus architecture. Using an 10 bus allows a computer io interface with a wide range of 10 devices ‘without having fo implement a Specific imtrface fr each 1O device. An 10 bus ean also suppor variable umber of devices, allowing users to add devices toa system after it hasbeen hardwired, Beviees an be designed to interface with te bus allowing them to be compat with any system that utes the same typeof [bus The 10 bus creates an interface abstraction that follows te processor to interface with awide range of 10 devices using a very limite set of interface hardware. Deus descriptions of popular 1 buses and wireless communication are given in Sections 3.10 193.13, PCI and USB bus (Section 3.12.2) interfaces to devices are designed to meet the PCI standard and USB (Geeton 3.103) standard ‘All thats required isa device driver (Section 4.2.4 in an each operating system—a program that allows tne operating system to conta he 10 device (Section 86.1. ‘The downside of using an IO tus to interface to 10 devices i that al the 10 devices in a computer must share the 10 bus, and 10 buses are slower than dedicates connections between the processor and an 10 device because the 10 buses ae desined for maximum compatibility and flexibly 75 ‘08 and Advanced Processor Architectures, Memory Organization ard Rea wold tracing ooncr Cock for He XTAL Te025 | MAS att ep pets = OM 007 moor (arogwrie) (rage mr ‘rc wito) @ = r 0000 White concn FFF ‘g2.9- (a) Timing of signals from processor when interfacing memory anil ports in 68HC11 (6) Circuits for the interfacing memory and ports in 68HC11 ‘An interfacing circuit consist of decoders and demultiplexers as well ss an 10 bus bridge controller. The imterfacing circuit is designed as per available contol signals and timing diagrams of bus signals. This, circuit connects all the units, procesor, memory, 1O bus bridge controller nd the 10 devices through the system as well as through the 1O buses, 10 bus bridge controller may be apart of the glue interfscing circuit sed in the system and isin PLD (programmable logic device), GAL (generic atay loge) or FPGA. ‘Multilevel Buses Figure 2.10 shows a two-level bus architecture, Figure 2.11 shows a three-level bus architecture, 152.2. 10 Addresses of Ports and Devices in Real World Interfacing ‘Memory Address-Mapped 10 Operations Many processors and memory organization require ‘memory-mapped IOs, 10 device and port addresses are interfaced such that these ate distin from the memory if 76| Embedded Systems —l [fon oa bce | erent ca SS 5S oS [Toone] Cetera] ows] [bene] Fig. 2.10 Memory, system bus and 10 bus interfacing in a two-level bus structure (mae = reas] | 1 Cater Pr St i = a L_, 1 — contr Ledarinan | {(gsaaeices"] [use rers | 2.41 Separate memory and /O buses to communicate with the memory system, and the 1/0 system using 3 bus controller and a separate disk 10 bus aise Menry ies eo dt nd ose, and 10 aes forte 108 Te floving are fees of meno mp Os The prcsr ha or 1 aes sce or prs an devises, * The nanctons aswel eco ea fre optons noes a mem 10 parandve addresses are the same. ‘as prletiats {051 and Advanced Processor Architectures, Memory Orgaization and Reak:wordItertaong | 77 + The processor has no separate input-output and memory load-stoe instructions {+ The arithmetic, logical and bt manipulation instructions that are available for data in menvory ae ato avalable for 10 operations. The process can dcctly manipulate the data taken from or sted tthe 10 por or device. The manipulation of ll istuetons i the memory can be dane using an scum any fegiteror any other mcmocy address where the 1O por byte is transfered afer, during or belie the arithmetic ological operation Almost all microcontrollers. therefore, have no separate instructions for 10 processing, The #051 njerocontrollr (Section 2.) an example ofa memory-mapped 1O-tased processor an memery orgnization, ‘The 8051, 80196 and 80196 microcontollers have preassigned device 1Oadresses for ther intemal devices sd these addresses are not configurable. Figure 2.12(a) shows tha device addresses are within the RAM and are distinct fom memory aditesses. Movorola processors have no separate nsrutioné for 1 processing. Consider another sytem with a 68HCII icrocontoler. ‘configuration is shown in figure. Pon A, 10 contol register PIOC, Port C, Band port contro! (CTL) registers have addresses ber wezn (00 to (x04. On-chip RAM is configured between Ox003F to x00. [The port addresses and on-chip RAM are configurable by the bits ofthe configuration register in 6SHC1 Forexample, the above device addresses can ao be r-configured and assigned between 0x0 100 and Ox 1040 10 Addresses Mapped !O Operations Some processor and memory-organization requires IO ales ‘mapped IOs operations. Consider assem withan 80x86 processor Figure 212) showsthe memory ress cn the lef side. I shows the port adresses allocated in TBM PC for timer, keyboard realtime clock an serial por (called COM2) on the right sie, This figure shows tht device addrestes need not be distinct, they can be the same asthe memory addresses ass contol signal will distinguish between them, The following ae featwes of 10 addres-mapped 10s 1. The pracessor is scparte 10 adres space for ports nd devices 2 The insrwtions and contol signals for operations on bytes at the memory and 10 ports an devices are distinct, making the desi simple, 10 devices and pot addresses ar interfaced independent of ‘memory, without considering the memory addreses that ae asigned for sliwaze and da, 3. The processor has separate input-output (or ead ad write) insretions nd memory load-store (for ‘ead and write insructioas. 4, All he arithmetic, logical and bit instevctions that are avilable in memory are fist operated using the accumulator and then fom there Byes are transfered afer an arithmetic or logical operation, ‘The IC subsystem has input units and ouput units, aso called 10 devices. Al 10 ports and devices have adresses. These ae assigned to deviees accoring to the sysem processor and intemal hardware coniguation Direct ALU operations on pot byte(s isnot provided The addresses of device depend on the syst hardware configuration. Most processors follow memory- ‘mapped IOs and process the memory and ober devices data with the same instructions. Some processors se 1O-mapped 10s; forexample, 80:86 processors process these wih diffrent st of instructions (input ‘outpetinstetions) and control signals. 2.2.3 Device Addresses in Real World Interfacing During processor instruction, a device when addressed, it ges selected and communicates with sytem bus or 0 bus using aset of adresses. These adresses are selected either as per decoder circuit desig ora pe the AB %0 Big Endian 0 4B cD F In general, programas donot need to know the endianness of the system they ar working on, except when the same memory location is accessed using leads and stores of different lengths. For example. if ‘byte store of 0 into location Ox1000 was peared on the 32-bit systems in Example 2.10. a subsequent 322it load From 01000 would run 0xS0ABCDOM on the itle-endian system and OxCOABCDEF on the big, endian system. Endianness soften an issue when transiting data between ferent computer systems. as big. endian and litle-endian computer systems wil inte the same sequence of bytes a diferent words of dat, ‘Toget aound this problem, the data must be procesedto conver it to the endianness ofthe computer that will read it Figures 2.10 and described the memory, processor and 10 units organized onthe buses. It canbe safely concluded thatthe memory organization has a tremendous impact on computer system performance and is ‘often the limiting factor on how quickly an application executes. Both bandwith (how much data can be loaded or stored ina given amount of time) and laeney (how log a particular memory operation takes to complete) are critical to application performance Other important issues in memory system desig include protection (preventing different programs from accessing each others data) and how the memocy system interacts withthe IO syste, 051 ard Advanced Processor Architectures, Memory Organization and Real-world tracing | 103, “There may be on-chip memories as RAM andlor register files. windows, caches and ROM in a micro “The caches are the integral pars of the wemory-organization within a system, The software designer should enable the se of caches by an aropnate instruction, wo obain greater performance during the un of ‘section of a program, while simultaneously disabling the remaining sections in onder to vedce the power dissipation and minimize energy requiremenis. Hardware designers shoud select a processor with mulway ‘ache units so that only that par of a cache unit sets activated that ha the data necessary to execute &subet fof insiruetions, This ako reduces power dissipation Processor Memory Organization: Princeton Architecture Figure 2.23(a) shows processor and ‘memory organization in Princeton architecture. 80x86 processors an ARMT have Princeton architecture for ‘hain memory. Vectors, pointers, variables, program segments and memory blocks for data and stacks have Afferent addresses inthe program in Princeton memory architecture. Processor Memory Organization: Harvard Architecture Figure 223(b) shows processor and memory organization in Harvard architecture. A processor having Harvard main-memory architecture has rom 2). bes 21. 22. /* Base Segment for 32 byte of Frogram Variables Data at RAM */ 23. _beastart = 0x10010; 7* Smart card base segment data at the base segment data file named here*/ ero Pane ktes Mrm Cams otros ions {13] 4. _BottonotHeap = 0x10900 5. text rom 6 Ue crypting Java Card program instr. the file named here*/ Joa (-== stmt) 8. data ram Oi 10. /* Shadow Segnent for 256 bytes of Initials: from RON from */ —Datastart = 0x10000; 12. /* The card shadow segnent data at the date file named here*/ a. (-~~.datay 13, _vatasna = ox100FF; ud J* Command for copy into the RAM * 15. a. rom 16. bes uv @ Data at RAM for @ copy /* Base Segment for 2 kB Program Variables Data at RAM */ 19. _besstart = 0x10100; 20. /* Java card base segment data at the base segment data file naned here*/ 21. a. (-=--.be8) 22. _bssEnd = Oxi08FF; 23.7 2a.) ‘The memory mp that inchades the device 10 addresses is designe after appropiate adres allocations of 25. * (--~~.bes) 26. bssBnd = 0x1002F: the pointers, esters. dt setsad data stetres Ite min menery 8 oF Farardahecan te pense ay imenory map wil be separate. For example, 8051 rads fom the program memory by spa ce ok a insttons Ginpst-cupa nsttons). Example 2.15 "2.8 “PROCESSOR SELECTION Consider another memory map [Figure .25(4] for another exemplary card. The locator specifies diferent map sections as follows: A hardware designer must take inte account following procestor-specitic features |. A processor which an operate at higher clock sped, grocesses more inructions per second. 2. A processor gives high computing performance whea there exist (a) Pipeline(s) and superscalar SECTIONS Tee eee ee ee architectures, (b pre-etch cache unit caches, and regiser-files and MMU and (c) RISC architecture, ees 3. A processor with register. windows provides fast content switching ina mltsking sytem, Ae 4. A powereficentembedded system requires a processor hat has programmable auto-shut down feature : for its units and programmability for disabling use of caches when the processing nee fora function Embedded Systems 2051 and Advanced Processor Architectures, Memory Orgarization and Real world Intrtacing or instewction set isnot constrained by limit on execution deadline, Processor uses Stop. Slep and Table 2.7 Essential processor capabilities in four exemplary set of systems ‘ait instractions, nd sperial cache design 5. A processor that has a bust mode accesses extemal nemvris as reads Fast and writes fost Pricer caps Cae Cnet Cane me & A processor with an atomic operation unit povides arias olin to shared data problems when Required ‘Automat ice deve Wabi.pon voice designing embedded software, ele special progzarining sill and lft eto be made when program Choco Vending acqisto,Wocedta Network Tamer Proceso tes shared variables and data buffers amoag multiple asks Machine, Acn: Congreso den Fat Sis fetes, We 7. When coding in asembly language or designing compiler of locator. dat may store in bigeian sieeSearm Kal | Compreion Adee Milf cheat prog rode ina system and the lower ordrbytes store athigher ates: forexamplen Motorola processors ae ares tee ae Data may also store in Fitle-endian mode in a system. Lower order bytes stort lower adresses and ee vice vers: for example, in Entel processors, A processor may also be coiure atthe inital program }— = a — stage bigendian or litle-endan storage of words: for example the ARM proce sr Regie proceso Micrconvaller——_ Microprocesor Muliprssser Sytem Microprocessor The StrongArm family processors frm Intel and TigerSHARC from Analog Devices ave high power {DSP ted llcency features Moliprocessor The processor selection processes canbe understood by considering four representative cases, Fisly Sytem desgn- able similar to Table 2.7 ible Then 3 processor having the equired situa unis and capable of Proceso insrucion -05101 001-004 (20005-0001 0.01 ~ 0.005 shine sired proces perfomance in syste schon — yee intima TP Case J. Systems in which processor instruction eye time ~ | sand on-chip devies and memory Show at sedan oi s ; San suffice Examples ate automatic chocolate vending machine. 58 Ktps moder, rob. data eee ates cee ernie eae ‘acquisition systems like an ECG recorder or weather recover or inulin! temperature an pressure Area bus wih 8 2 2 “ recorder and teatime robotic cone. ints 2, Case 2: Systems in which processor instuction cycle time ~ 101040 ns require on-chip devices and ee ee Bee rg a memory do not suffice and medium processor performance is required. Examples are 2 Mbps router, Sehiosue image processing, voiedata acquisition, voice conipresion. video decompression adaptive ruse 7 ; 7 ! contol system wih sting stability and network sateway. Progum comer 2 2 4, Case Systems in which instruction evee times of 5 to 0s gre and high MIS or MFLOPS ond sack itr, psfocmance is needed Examples are multipo 100 Mp etwock tanseier at 100 Mbps switches, Siosk ststernt ——Esernal Extra rine Internal Inert Toutes, multichannel fst enerypions und decryption. syste. Pera enor 4, Case 4: Systems in which instruction eyele time of even Ins doesnot sulfce and multi-processor Cops - va system is required along with use ofthe eating point and MAC units. Examples are voice processing wee ‘ideo processing reine aio or video processing and mobilephone systems Ditteren systems require different processor features, A hardware designe takes these into view and Peete twee No ve Ys. Ye ! selets an optimum perfarmance-giving processor. ai sai j 2.8.1 Microcontroller Sele COffchip RAM in Noonshipslfices Yes Yes ves There are numerous versions of $051. Additional devices wd writs ne provided in these versions Aversion ta oct and microcontrollers selected foe embeded system design as per the aplication as wel a i cos. 1 Embedded sytem in anatombie, for exarpl, requires a CAN bus (Section 310.2), Then a version COnctip egiser No Ye Yes Ye vith CAN bus contr is selected windows ad files 2, Au805t enhancement 8052 has an addtional timer ao miooes 3, Philips P83C528 has PC serial bus (Section 3.10.1), sehng res 4, 8051 fansly member 83C152IA (and its sister JB, AC and JP microcontrollers) has wo direct memory fe a ne aa access (DMA) channels on-chip (Section 4.8) The 80I96KC tas a PTS (PerigheronTransactions imenain‘icw:— erocenetler Serve) thar sapports DMA functions. (Only single and balk ransfer modes ae supported, not he conte er exe burst transfer made) When a system requires det transfer to mesmory from external systems, the to wocesor DMA contol, ingroves the system perfonnance by providing fra separate processing unit forthe ams data transtrs from ant the peripherals. Embedded Systems jne — = 5 Presser camilin Cue 4 Cae 2 Case coed | Required Auomu Voice de Malicpon ie | Chace Wet acquis, Wice-date Nevwort Traneciier— Presor ‘Mactine. Data Aegui-Campressoe, Video Fast Swine, Rowters. Video sion Srstem, Real Compression, Adaptive Multichannel Fist pressing end ‘ime Robotic Cnt! Crise Conia Stem Encryptions anole Pen | Nenwork Gateway lasruction and das No Yer Yes Yes with Sing Sabin, decraions Sites | | caches and MMU Cmehipmenory —Yevonctin.——Nenctpes——Nasonchipdos Nosy fmverePmont ties an neni Gono Esta items 16 2 18256 ie | imine ted ery wed Heavy wed Hey mad peo i Srsumy ofa No Mont Noses) May be tay es | reyoing Harv ms} DMA center No te ve aye Evemiplary 8051. 68HCII or 12x86, 80860. 80940 ARM. Sunspare armors | pocour niyo Ta tony oS PICIGFSS Powerc | 'scaal wien mile pos and michael opsratos ee ats sai 1, robotic system motor needs signalling the rate above 50 to 100 ms. Hence there is enough time available for signalling and eal-ime contro f multiple motors at the robot when we use a processor with instrution eyele time =1 ys 2. The processor speed nee! not be very high and performance needed is much below f MIPS, So n0 ‘aches and advanced processing units like pipeline and superscalar processing are requted 3. A four-col stepper motor ness only a4-bt input anda DC motor needs I-bt pulsewidth modulated output, Therefore an 8-bi processor suffices. 4, Frequentaccesss and bitaranipulations at 10 posse needed, CISC architecture therefore sce 5. The program can fit i 4 KB or 8 KB of ileal ROM on-chip. Stack sizes needed in the [rogram are smal! so that can be stacked in an on-chip 256 or 5I2-byte RAM. A ‘microcontroller is thus needed. No floating-point unit is needed 051 and Acvanced Processor Architeetures, Memory Organization and Real-world ntertaong 117 Microcontrollers appropriate for the above case are 8051, 68HCII, 6SHCI2, 6HHCIO oF 80196, Microcontrollers GSHCI? and 6HHCI6 can he used due to availabilty of tage umber of pos. The G#HCI2's instruction cycle an clock cyl tne equal 0.125 ps, Number of port eqs 12 in 6SHC2. Therelone, 6 oF more degree of fecdown mbt with 6 or nee motors ean be driven directly trough thse pors, STOP and WATT instructions in the processor save power when the robot isa est) Example 2.17 Case Sty of Yair Oats Sonumeeesion Syste 1, Voice sigals ae pulse-code modulated. The rte at which its ae generated is 64 Kbps. A suitable algorithm can process the data compression ofthese bits with an instruction cycle tine of ~ 0.01 to (0.04 js (100 to 25 MHz) when the processor uses advanced processing units and caches 2. Let us assume thatthe processor nstuction cycle time is 0.02 us (50 MHz)” With a three-stage Pipeline and two-line superscalar acter, the highest performance will be 300 MIPS. [Refer to Example 2.11 for an understanding of the computations of MIPS}, I suices for not ony for voice but aso for video compression, 3. Frequent aecesses and complex instructions may not be needed. {4 The program cannot fit in 4 KB or 8 kB of intemal ROM on-chip, and stack sizes needed inthe program ae big, Instead large ROM and RAM as well s caches are needed, 5. Notloating-poim is needed as mos the it manipulation instvctionsare processed during compeession, Exemplary processors that are snpropriate forthe above case are 80X86 and ARM family processors Example 2.23 6 1. Transfer rates of 100 MHz pls are needed in last switches on a network. Assuming 1D insructions er switching and transceiver ation, nsrution cycle tan is ~ 0.001 pls. A mliprocesor system is needed for GHz transfer aes 2. Let us assume thatthe processor instruction eycle time is 0.01 ps (100 MHz). With 4 five stage pipeline and two-line superscalar architecture, the highest performance wil be 1000 MIPS. [Example 2.11. Multipcocessor system is thus needed for 1000 MHz pus switches 3. The processor should have RISC architectue for single cycle instrction processing at ach ff stage and line. 44. ROM and RAM us well as caches are required, 5. No floating-point is needed as mostly the bts are processed fr 10s. a Exemplary processors that are appropriate forthe above case are ARMT, ARMY and Pentium, Example 2.49 Kearse «en eo 1, Real-time video processing requires fast compression of an image needing use of DSP. Many real-time tasks have to be provessed: for instance, scaling and rotation of images, corections for shadow, colour and hue, image sharpening and filter functions. In such cates, a multiprocessor system with DSP(s) and that has the best processing Exemplary processors that are appropriate for multiprocessor system are ARM integrated with TMS family DSP(S) or ARMII or TigerSHARC. _ jn) Embedded Systems "2.9 “MEMORY SELECTION Once the software designer’ coding s over andthe ROM image fle is ready; the hardware designe is faced withthe questions of what typeof memurv and what sizeof each shouldbe used. Firs a desiya-tble. 2 in Table 28, is built. The memory having the required features and address space is chosen. Following are the case studies. The actual memory requremest is known only after coding s per the design functions and specifications. ROM ond RAM allocations for various segments, data sets and structures willbe avalable from the software design. However. prior estimate ofthe memory type and size equirements can be made {Remember the memory ave avalable as: | KB, 4 XB, 16 KB, 32 KB, 64 KB, 128 KB. 256 KB, S12 KB and IMB. Therefore, when 92 KB of memory is needed, hen a device of 128 KB is selected.) Example 2.20 (a) Case Study ofan Automatic Washing machine Consider an automatic washing machine sytem. Assume that machine isnot saving the pictures and _raphics.(a) An EEPROM first byte is required to store these (wash, rinse cycle I, rinse cle 2 and Eich 10 device has sinc eof sess, Each 10 device alo has tinct tof device registers ~ data ‘registers, conto registers and sas registers. At advice adds, there may be more than one rept Te device adieses depen onthe sytem hardware. Basel on the merry mp with 1 device adresses cst rogram is designed locate the linked abet code file an generate & ROM image. Absolute addressing moe Accelerator Accumulator ane A ames Arithmetic uni reitrs ARM ARM? and ARM Asynchronous serial Auto indes Boe addressing Baud Rate Boot back fla Branch raniher cache Burning us interface unit cise Cote Compaiiliy ‘Keywords and their Definitions Embedded Systems Defie al he ass sin an inst. |ASIC, IP core or FPGA, which sears he cove execution which may so inl the bus interface uit, DMA, ead and write units esr: with thee cores. ‘Areisertht provides input toan ALU and that accuses resins operand from te ALU. Aigh perfomance version of the AMBA used in ARM procs. ‘Aunit to prfom aiimetc and log operations as per theists. [An essed opensource specification fr on-chip intercom that se, ssa framework for SOC designs and IP itary develpnen Regie that hold he input an tpt operands und es with she ALU. |A family of high performance rice cade density ANM?. ARMS. ARMO Ghd ARM Il processors. which are sed in embeded ystans asa chip, or as core inan ASIC Two fii of RISC procestor for an SOC frm ARM and Texas siren ath available in single-chip CPU versions and ia fie esos or embeding at VLSIchip ARM 7 bas Princeton architecture or tie nan emery and ARM fs Harv Architecture. ‘Data byes or fame nt msi uniform phase dtfeencsin serial ‘When after executing a instuction, the index register contents change scat [Adressng an ade from where first element of data suture ts Rate at which ser its are eeivd athe ine ding & UART communication, |Afiash with few sectr sir oan OTP device enable soape of bootup rogram a dat Cache 1 holdin advance the next Sto insbuctons © be exceuel onthe ‘rogram branching to this {A proces in which is tend rom a sin xase fxm to he Is and Os ina device as per input 15 and 05 ‘Aoi ietconect the intel buses with the external buses fr conch, ‘ress and data bi AcomplistedIsraston Set Computer that has ne feature tat provides a big fnsteton set for permiting multiple adéessing modes fr the source and ‘esination operands in an aston. Phe hardware executes he instructions inadiferent number of cycles as prthe adessng ode used inan instruction Usability of codes by vicious generations of xi de composer studio covec Control unit DAA ata cache Device address Device programmer Device programming Derceegier Device Dinytone Digital Pitering Direct address pas beam 8051 and Advanced Processor Achitecures, Memory Organization and Reatword Interfacing | 123 | ‘An IDE for T DSP specific code composing which provides an enviroment ‘ilar to MS Visual C+ consis of te allowing: level (Cs wel DP assembly debugger. compiler, assembly optimise, RISC ke sembly «cde and RISC scheduling for psu pertrance ad eine pote its fle 10 funcions, comprehensive da vsaliztion dpa and GEL erping language based on © ‘A ant for digi xing alter ADC and ater operon ud deci 0 get snag sina using DAC ans ae operons. wedi processing ao or (CCD deve piel an vdeo signals ‘Toconolandsequonceal he processng sons ing an stron excain Direct access aangement for example, pial DAA sei a and out port irc transfering the awlog input and capt wsng Wp 19 | mse ind 7 slave CODECS. (Cachet old the dats in content adresse memory Format Discrete Cosine Tranformation funtion sed in abe of DP fonctions, for ‘exanple, the MPEGIMPEGE compression, A device address sd by processor to access ise of esters. teach ess there maybe one or more device egies A system or unto programing a device by baring-in ROM ine Programing of tts by buring ina mesa of mracontlr or in 3 PLA, PAL. CPLD or any ctr device -Aresstrin dvie for byte, word of dua. fags contol is Several device rege ny have a common ares {A pv or virual uit a as theese f reise dat registers contol reps and suns esters. and which he proceso abiecesiie amen ‘benchmarking program tht measures the performance of & processor for ‘processing integers and strings (characters) I uses a eachasek progr ‘salable nC, Pascal or Java bench a CPU, 20 te pesfoman of he 1OorOS cali. MIPS = 1757 Dirysones ‘A iter for the signals that se DSP functions ‘A ltl usable tes in an stretion, Wis sully the aden page in the memo {A dict memory acess by a contr ital or extra. DMA operons fasta the peripherals and devices of thesyzem obtain access the ster memeries diet, without te proceso comune wander of be byte 1 rmemory block. ‘Dyna RAM, which tess cotinsusly by a device called DRAM refs cvetrle, Once programmes, it auto read and writes the sire st of bis repeatedly by scaming the DRAM menary ce A proces of lining echoes | sina received afer delay and which spetimposes over the eign sige Forerarpl, na hl oat the ils we hear te orignal sound as wel asthe ‘echoed sound, Smal there may be eco in electron ial i) eos bewac EPROM erKow Erase tine lead pon arithmetic Flach Flesh losin poi artmeic Hightvel language support Inder register Inrvction cache Insect decoder Iestruction frat ‘usrction quenog ait Instruion register astro 14 Insertion et merece cenit. taal bus Java Aceletor wa MAC unit Master Embedcod Systane pes ol fy Eleni Design Attomaio, EDN Emhadled Herta Conan, ‘Ayn of menory ca byte of which is erable nny ies and Be !mogtanne by inns proranas wells by avi propane A type uf memory tt rsable many dines by UV Hight exposure and Programmable by a device pagar, Time taken for eevee ering Acithete wing signs or unsigned ic ges employing processor registers ‘memory. A meron in which set of sets erase simelatenoity, typeof memory ina sor of bytes ht sera many tines (masinum 10000) ia Ha at he came instance i 3 Single cyte, Each rao bytes then programmable y the wnt insiutin ofa programas well aby adevice progeammer Arithetie wing provestur registers or mene; when the dein numbers ad Festal uber te sre in tad sting point npresetaon ‘A singing wit fr yven proceso suc that faites progra coding ‘nC wresher high eve fngges rl abe he ning ke machine ees by an inemal epiaion ‘A coger bling messy alos fa vail na aay gut tbl i, A cate 10 soyuenilly old the irwtions dat have Bec proche i Pplice hoe puri eect ‘The cuit wo doe tis evade the st a tthe cnt it axconingly Font of exprening a nston Auntie a qucusofastetons ad pie hee int the ccs A rior ld ts cate intutn for excel, A elite of execu fs ions ina proces A urge prucssorspecite set of isructons A crit consi of he aes sues, alpen amd aap ‘Asst pts that ea in parle he inal been vase sear is ofa paces fs eo GLb Ins I pres, A accelerator tha lps inthe exevton of Java cos fat than & JVM, Machin codes tht usethe coupled byte css fav progra an the (rogram ona gives sytem ‘Aunt sl in DSP operations fast eacustion OF Ba, + (31 0 sae expresions. A proceso, device osystem wich syctzonaly or asytchronusly ontos ‘the oupt to several ifeentpocesiers. devices and systems cal sles, 5051 ard Advanced Processor chiecues, Memory Organization ard Rea word itacing | 125 Meese Memory adds reir Memory deta reir Memory management unit Memory map Microarchiecare Noise elimination OMAP 5910 procesor Onchip paral port (On-chip serial por Opcode Perfrmanee beneloarking Piptiving Prec conrol wnt Program couuter Progr flr insracion ROM or oT Pulse accumulator counter "Realtime video procsing ‘The maver cn couse sn ait aes sive fa save hs iinet adres Te avr cnehineturcviveaminpa fiom any sone by cata ist, A highspeed communica niche! Buteod Serial Pur | register hat hast ales fora memoey anit For placing i he bus sing bus itr it A retro he dats for ai a emmy uit ‘unit to mangge he poh, paging and segmentation of memories, ‘A meinory aes allocation table seh tht the map eet he ava Iemory ales for varius uses the pracesor A merery map dines the areses ofthe ROMS and RAM the sysem When proceso actinctare refers specify othe achietransuction Set and programmers models thet aeramicte referee the implemeniation of hase architectures, & processor say have CISC sbiesure wh am RISC meena plementation, rally inetd sgl eompunents A proces tat inintes wc ‘ATI proceso funigue uci in DSP chips of igh peso with ow prover consumption Tho prt a hip which uses Ur send 16 ts ata instance ‘The port na eip ws reeves or sends sisal an instance with 2 fii ate ap Pa te UAT ins byic sin forthe entation ds he proees Htincs the upoa o poee¥s e peronaa o the opcndts Maxie faresatatng he peste of ste ‘Thetis pipsiing also inthe supercross I meas an is ALS “itvilevinton abun. nis tse the poses pth nsoeion isting acaton instante tthe ig rossi ope nh esti is taking plac. Thre maybe mali pipet i apres topos ple ‘A wit ofc insratons in alte a dt ia ance fom tbe mesney ‘A prosssur giver to al he cue insti aie tae eset es fet yea eb “Aninsrucion in wich he pogrom ear onan pie ages ‘ay event a its neal changes Jog pura eee A.gpe of mary which it programmable nce by a device panes OTP sa cuesine prgranmable wen. ‘Account cout the apt pulses during a st neal. Whe wed 63 timer with areal ole vale it factons asa pte wid ltr Pressing of ideo signal such hat alo moins anes ar proceso ‘in atime frame such that cach processed fame maiatns constant phase fees inthe ines hate hem 126: Embedded Systems RISC wth CISC furctoualiy +A poceser with RISC inplemeataton but use programs it smart. CISC nase A Re! Israston Set Computer that ison eatuehat provides sal insttion set and permite limited addressing modes forthe source and destination operansinan aint or logic wsrcton The hardware executes ‘etch estrcton ina single eycle Segment register | regis to pont 0 the staf a segs for a program code oF daa stor sting o sock Store [A proceso or device or sytem. which receives the input from the master procenoror device or sytem, This ave ith one having a distinct adress Ed chosen bythe master Special function register ‘A epiaerin $01 forspeil ution of ccunultor dpi, ime coma timer ae, seri buler ell consol, power down contol. prs. et Stock pointer A regatrtht hold anaes to define the availabe me mary sesso where the proceso can push the egters and variables 0 sack operation ad rom ere they canbe popped Stock A block to memory that hols the psbe valus Foran first-out data transfer ‘on popping bck he values Supercar processor A processor with the capacity to fetch, decode and exeoue more than one Gsrcion npr tan stan. ‘Synchronous communication + Dutabyesorramesmintsin vom phe derenees inser communication. System reister Processor regis Thunb? insraeton set Aniston st ia which ach nstuton i of 16 bison 232: proceso. Ie ves redoed cae deny ks Gs isto et which ensles32-it Pevfronce at 86-bit system cow. They ze wed by ARM procesor. Timing diagram ‘agatha eft the elatve ine itr ofthe signal on the exter buses with spect wth processor clock pues Video accelerator Am aceertor forthe video out Wochdog Timer tines whichis setinadsance ant pogramcoete maesuchthais overow indicates that 2 proces ic tuck same where std therefore the processor resets sn estan Review Questions 1. Exlpin 8051 acitecturalfestares, What ae the devices iterally presen! inthe else BSI. How do ye inerface a frorammable peripheral interac in 8051? Desert serial interac, inecouners and inteape in 01 Describe eal-erditertacng. Explain interfacig to keybon Compare memory-mapped 10 and 10-napped 10s “What sre the common srt unis in mos processors? Compe Harvard and Poncsen memory organizations. ‘What are te Special stra! wien proceso for gil camera systems, rea ime vdeo procensing systems speech compresion systems, voce compresion ystems and veo games 051 and Advanced Processor Aehtectses, Memory Organization and Rea‘woietacng | 127 How do having prt caches fo incon, dt and branch hp 9 What see advantage ving nly ache wis 0th nl ht x pat of he ache wii activated, which has the aecowiy ac exces sions Lis or xen process with ultway ace. 10. Wh do you sd MAC ut at a proces inthe seni? 1, Esplin tree sage pipeline, supencaler procesing and rach aoa pendency pestis 1 What ae te vantages in Harvard architecture? Why i the ee of acing ck sd dt table a progran tvemory les in Harve memory cite compare Praccten tenn aiete” 1. xpain he perormance mewes of proc: MIPS. MFLOPS a Dhzyums pe seca 14 Why should pros eve no functions oats er modules aes placed incre memory blocks 15, How dothe ARM7. ARM, ARM If nd SwongAvn ifr! When wl yo pofer ARMY, when ARM9 al when ARM? 16, How does a memaxy nap help in designing oar progr? 17 What do youre byte ems: Quan CIF, EDO RAM. RDRAM pexpherl eamsatons sever shadow segment ‘on-chip DMAC and tine-vison mules 18 How ds decoder help memory and 1 device ieracing! Draw fur erly cuts Practice Exercises as 19. Draw the memeryeranzation in 8051 20. il you ase am 8S to for server in a oho asin incre and pon of HOST? 2A, Atwo by dc mas mules By ante by two mati, dt ran th 3 esr oer kes 2m ulin tan 210 al lpi tke 0 mat wl ee enecton Gime? How wa MAC uni ily. Ase ht hse times ate sarin DSP witha MAC wi 22, Anaya 1 imegers cach of 3 is Letaniteger be ao sind in he tay muti hy 1024 Let tbe tase ahs in immary be G40 How wl he is Be fred or te OP, 4 and 9® ln a ig-saian sate () ite ode? 3 Weean aku tt he mem of an ene system is als a deve List dhe rier ike aces cota egies andthe cone of Virtual le aed RAM dsk deve 24, Nowudhyshih-perfomnee ented sen we eter a0 RISC praesor or pacer with an RISC ce with eade-opiniaed CISC neton xe Why? 25. A circular qaeue hs [carter the memory ables, ach of 2s What wl Be he ta meron pace equi. nluding the spe fr hath tbe ste pons? 26, Esme the menny sequent fra 00mage dita carera when the esoton fa) 1024 x 768 pels (6) 640 40. 20 240 and 16D 20 pce ad ech mage sles n compres pe fort. 27. Whatarethe spec retwal unite processors fr digital ee elsime video processing. speech compression and video game stn? ss fr, (Him: Use of Devices and Communication Buses for Devices Network ‘The following facts have been presented in the previous chapters: # Embedded systems’ hardware consist of pro- cessors, microcontrollers or DSPs and basi hardware units such as power supply, clock circuits, reset ;, memory devices (ROM, flash and RAM) of different sizes and speed of access, and 10 peripheral devices and ports for c the UART, modem, transceiver, timer-counter, Keypad, touch screen or LCD or LED display, DAC, ADC and pulse dialer ‘+ Embedded system microprocessors interface with a real world 10 devices, such as DMA and bus controllers, peripherals, IO ports and keypad. ‘© The controllers, peripherals and ports have add- resses using which the processor accesses bytes and { words. An embedded system connects t0 devices such as the keypad, touch sereen, multiline display unit, printer or modem or motors through ports, * During a read or write operation, the processor accesses that address in a memory-mapped IO, as were accessing a memory address. A'decoder takes the system memory or IO address bus signals as the input and generates a port or device select signal, CS and selects the port or device. RARL BO owen ‘Me ca think of «compute withont 10 devices far the view capt, mone. Resta Inu, CD aud meric storage, We cant think of a aie smartphone witlew the deviees for LCDor touchscreen, (0 pot terface ey titers, dlr peer reo inerfoce and flash meray storage, iniars. we can sink of an enbedded stem svn [0 evces,jiners another levies: lfc the devices play tems significant role in aay embeded system A device connect and acceses a ft the system nocessor and memory eer imermally or thrush an aera conteler oe txough o rt si oc prt having an assigned port eldesex snl wo sem adresses Distributed devicesare nensorked using spice 10 uses. Fr exanple. ae the se ofan eatanobile: all ened devices in antomobile have amici and rnenvork trough bus. Dhedercesinanauroneile are dnb at lifer loans These are netwarked uxng a bu elle Control Area New (CAN) us. Sir eumera onerces toa computer an priner tough a USB bus o Wleroth device. Advanced networking devices such a transceivers and ences and deersping devices oper a high speed A hardicare engineer designing an embedded sesten nus, therefore, clears inulerstand the featares ofimerface circuits and ther sped of operations al te uses tha nerve he devices We wil Kean the fllscing topes ts ease 1. Seviol ent parte inpn, exp and 10 pts 2. Sunchramonsserie-communicason devices and examples of High-Level Da ink Control 43. svnclnonons serial-commanicain devices end her example, BS232C and vaRT 4. Pail ports dd parallel communication deviees Wireless levices Sophisticated interfacing feataves in the estes for fs 10s, es aseeiver tid realtime wie el ideo 105 2. Taming and soning devices, cmd the concept of v8 tne clo, sensar tiers ona wate viners Inver frente Circ (EC) crxmnicain bus etc oigte dseibuted ACs aed the CAN bss the contol nensrak beeen he dsibated devices fn the amemotiles 9% Univeral Serial Bus(USB) for fast seria ransmission and recep between the hast embedded sytem and distributed serial devices like the kere 8 printer: seauner and ISDN system 10, 1BM Standard Archtetur®-(IS and Peripheral Component Inerconnect (PCIVPCEX (PCT Extended buses berweer «host computer or sstenn and Chased devices, systems or cards; for example, PCT bus berween the PC and Network Interface Card (NIC) i130) EEmbodded Systems 11. termeremabled embeded devices and ther nework protocols 12, Wireless protocols for mubile an wireless nencorks 3.1 IO TYPES AND EXAMPLES A serial pon sport or serial connanication, Sera communication means that aver a gven line or channel fone bit :an communicate and the bits transmit at periodic intervals generated by a clock. A serial port ‘commurication is over short or lng distances. ‘pale port is a port for parallel communication, Parallel communication means that multiple bits ean commuricate over set of parallel ines at any given instance. A parallel port communicates within the same board, between ICs or wires over very short distances af at most less than ameter. {A seial or parallel port can provide certain special features and sophistication (Section 34) by using a processing. element Portscan interconnect by wireless. Wireless oc mobile communication is eral communication but without wires, canbe overashon ange pesonal ares network swell as long-range wiles etwoek, and transmission takes place by using carrer frequencies. The eatier modulates the serial bits before transmission in aie [Sections 35 and 3.13], A receiver demodulates ad retrieve the serial bits back. Serial and paallet poets of 10 devices can he clasilied into following 10 types: () Synchronous serial ‘input Gi} Synchronous serial output ii) Asynchronews serial UART input (is) Asynchronous serial UART output (x) Parallel port one bit input (i) Parallel one bit output (vi) Parallel port input (vi) Parallel port jutpu. Some devices function both a input and as output: fo example, a modem. 3.1.1 Synchronous Serial Input ‘The par | in Figure 3.1(a) shows asynchronous input serial por. Each bit in each byte and each received byte isin syneonizaton, Synchconzation moans separstion by a constant intcval or phase eiference [par 2 Figure 3.1(a)) clock period equals, then each bye a the por is received at input in period 8 T. The bytes are received at constant ates. Each byte atthe input port separates by 8 and data transer ate Fr the serial line its is bps [1 ps I-bit per second}. The sender. along withthe serial bis, also sends the cock pulses SCLK (serial clock) to the receiver port pin. The port synchronizes the serial data-input bits with clock bits, “The serial data input and clock pulse-nput are on sue input ine when te clock pulses ether encode or ‘modulate eral data input bits suitably. The reciverdetecs clock pulse and receives data bits after decoding or democulating When a separate SCLK input is sent, the receiver detects atthe middle, positive or negative edge of the clock pubes that indicate whether data-input i 1 or Oand saves the Bits n &-bit shift register, The processing clement tthe prt (peripheral saves the byte ata port register from where the microprocessor reas the byte ‘Synchronous serial input is also called master output lave input (MOSD wren the SCLK is sent from the sender tothe receiver and slave is fored to synchronize set inputs Fom the master as per the master clock inpuis. Synchronous sera input isso called master input slave output (MISO) when the SCL is sent othe ‘sender (slave) from the ecever (master) and the slave is forced to synchronize sending the inputs to master as er the master clock’ outputs ‘Synchronous serial input is used for imerprocessor transfers, audio inputs and streaming data inputs Devices anc Communication Buses for Devices Network io oe _— CLE 3 ee oe = Teen ie — 1 csorrounotour 612 FEY sera 0008 oS no p01 Mecracosor rea | Rote ie Ss BisteDals hasooat ‘sane pos = Pau ferstaie# (Optra ae = Step at Save Enbectad Sytem ° ° Fig. 3.4. (a) Input seria port, Output Serial port, Bi-directional hal-duplex serial port, and Bi directional ful-duplex serial port (b) Handshaking signals at COM port in computer and (6)2 UART serial port bits 3.1.2 Synchronous Serial Output “The part 3 in Figure 31) shows a synchronous output serial pot. Each bitin each hye sin synchronization witha clock. The bytes are sent at constant aes [prt in Figure 3.(a]-T te lo period equals then the ata rancer rte ig Fp. The sender sends either the clock plies at SCLK pin ortho srl data output and ‘lock puls-input through same output ine when the clock pulses either suitably modulate or encode the serial ouput bits. (v3) 7 the microprocessor writes the bye ‘Synchronous serial output is use for imeprocissoe tanfes, audio outpats and searing data vats, 3.1.3 Synchronous Serial Input-Output ‘The part Sin Figue 3. (a) shows synchronous serial input-output port. Each bit in each hte synehonizes withthe clock input and output. The byes are senor recived at constant ates ax shown in pars (2) and in Figue 3.13]. Te 10s are on same 10 Fine when the clock pulses suitably snodulate or encode the sei ‘input and ouput, respectively ifthe clock period equals Then the data transfer aes I/ Thos. The procesing element at the port peripheral) sendsand recsivesthe byt at port register tor fom which the microprocessor writes o ead the byte, ‘Synchronous serial inpuoutpts are also called maser input slave outpt (MISO) and ng (OSD, respectively. ‘They ae used for inteprocessr transfers and steaming daa. The bits ar read from or wsiten on magnetic ‘media such as hard disk or on optical media such asa CD by using devices with serial synchronous 10 pors. ‘The part 6 in Figure 3.1(a) shows the 10 synchronous port when input nd output fines are separate ler output stave 3.1.4 Asynchronous Serial input 1 3.(0) shows the asynchronous input serial port ine, denoted by RxD (receive data Each RXD bis reccived in each byte at fixed intervals bu each received byte is natin synchronization, Te bytes can separ variable intervals or phase differences. Figure 3,1(), on the Fight sid, shows the starting point of receiving ‘he bits for each byt. indicated by alne transition fiom | to Df a pried T. When a sender sbils afer very ‘lock perio T. shen byte a the port is ecoved a input in period 1OT of 11°F The te of 2T is duc to we ‘of atonal bits atthe start and end ofeach byte. An addition time of IT is taken when a Pits xe belone the stop it ‘The bit rane ate (Tor the serial ine bis) is (1) baud per second bu different bytes may be received at varying interval. The word Baud itaken from 2 German word for raindrop. Bytes pour from the sender like raindrops at irregular intervals. The sender doesnot send the clock pes along with the bits “The receiver detects bits tthe intervals of T fom the midae of the Fest indicating bit.n=9, 1... Wor 1H, finds out whether the data-input is or O and sass the bis in an 8-bit shift epister The processing clement atthe port (peripheral) saves the byte at a port regis, ram where the miroprrcessor read the bye ‘Asynchronous eral input is socalled UART inti the seca input is according to the UART pro! (Section 32.3). Asyneitonous serial input is used For Keypad and modem input 3.1.5 Asynchronous Serial Output Figure 3.1() shows the asynchronous output eral ort line. denoted by TxD (transmit data), Each bitin each byte is sent a fixed intervals but each output byte isnot in synchronization (ts separated by 2 variable interval or phase difference), The Figure 3.1(c) shows the stating point of sending the bits For each byte, ‘hich is indicated by a line transition fom | 100 fora period T. The sender port of TxD does not send clock pulses along with the Bis. ‘The sender ransmitsbytes tthe Minimum interval of 9. Bis start from the mide of the stat indicating bit, ‘where n=0, 1, 10or I and sends he bits through 10-0 I-bit shift epister (Figure 3.1()). The processing clement atthe por (peripheral) sends the byte ta port register to where the microprocessor writes the byte Devices and Communication Buses for Devices Network Asynuliranous seal outputs also called UART output ifthe seria eutptis according toa UART protocol (Section 3.2.3) Asynchronous serial ouput is used for nviden and printer inputs. 3.1.6 Parallel Port A parle! port can have one or mutibit input o output and can be bi-directional 10, i) One bit input, oatput and 10 ‘iy Bight or more bit input, eusp anc 1O Section 3.3 will describe parallel device ports in deta 3.1.7 Half Duplex and Full Duplex ‘The put 5 in Figuee 41) om the lf side hows the 10 serial port (bi-directional half duplex serial port Hall duplex means that at any point communication ean only be ne way (inp or output) ona bi-directional Tine. An example ofhalf-duplex mode iselephone communication. On one tlephore line, we can talk only inthe half-duplex mode. The pa 6 in Figure 3.1) shows the separate input and ouput serial port lines, Fall ‘duplex means tha the communication can be both ways simultaneously. An example ofthe full duplex synchronous mode of eonmunication is communication between the modem and computer through the TD and RxD lines [Figure 3.(6). Thee are two types of communication ports for 10s: eral and parallel, Seria line port communication is sychonous when aclck ofthe master device controls the synchronraton ofthe bts on the ine. Serial line Port communicaton is asyncronous when clocks ofthe sender and receiver are independent and bytes are ‘receive not necessarily at constant phase diferences, Serial communication can be ul duplex. which means simultaneously communication both ways, or half duplex, which means one way communication, 3.1.8 Examples of Serial and Parallel Port Os ‘Table 3.1 gives clastication of 10 devices into various types. Italo gives exsmples ofeach type Table 3.1 Examples of various types of 10 devices Imes grocesor data anser,eadng fom CD ox hd ik ui inpt, video pat ial tone. network inp vansceiver inp seam iat renecntoler inp srl 1 bes inp eaing fr Mash memory wing SDIO (Sere Data ‘Asocation 10) cad Serial synchronous ipa Serial synchronous output ner pocessr da transfer. malproescr commbniction, wrt 0 CD ce tacd disk, ao output, video ona, diner outa. nerwork. deve tpt remote TV Cont. wansceiver put, snd serial 10 bus ou, writng to Flash memory wing SDIO card Keypad contol srl dt, mie, eyboad contre data in modem np, character inputs on serial line [also called UART (aniverel receiver ind transite input when accodting to UART mode) Seva eynchronousixpar (Gent) [xs] Embeted Syms TO Device Tipe Eom Serial asynchronons output Out rm mad ost or pie, he opus ine [also | UUART ouput wben according t0 UART model Paratel port singe bt input) Completion ofa reson of 2 whee. sticvng preset presse in 2 | baie exceding the ype limi ofthe erie weight er the pan of an | Re bias cme (or fespons fom transits, Exh of acnsnand a it. anne ver acined nde pe enples ofa pra nea mesae fron th ner eae nde ee rn esta, a ‘ected and fran rtbered acknowledges, ‘We ve wns forte St one O i fea, Ts pees misitretin hy eier he i ag bas (U1, 3.2.5 Serial Data Communication using the SPI, SCI and SI Ports “Microsontolers have internal devices fr SP or SClor Slat explained below. Bach device his separate regis forcongol, status, srl received data bis and ransmiting serial bits. Each device i programmable as deseribod below. The device can be used in progranuned IO modes rin merge driven reception and transission ‘Synchronous Peripheral Interface (SPI) Port Figure 3.3(a) shows an SPI poc signals. Fire 3.00) shows SPI port in 68HCIT and 68HCI2 microcontroller. It has full duplex feature for synchronous ‘communication, There ae signals SCLK for serial lock, MOST and MISO output fom and input to maser. va] Entess Spt Section 3.1. Figure 3.31) shows programmable leaturs and DDR feature of Port D. An SPI feature is rogramimable rates for elock bts, and therefore for dhe sera out of the data bits downto the interval of 15 ys fran # ME crystal at HCH ‘PIs also prograramable for defining the occurence uf negative and positive edges within an interval of sitvat serial data ou or in, tis also programuble inthe open-drain of totem pole output Iron a maser toa live and for device selection as master or slave. Tis can be done by signal to hardware inpu SS (slave cect when ) pin. In the hardware the slave select pin connects WI" at the maser SPI device and 100" at is save. Defining SPL as slave o¢ maser can also he done by software. Programming a bit atthe device st register does this, ‘NHCI2 provides SPI communication device operations a 4 Mbps. SPI device operates up to 2 Mbps in ‘SHIT Serial Connect interface (SCI) Port Figure 33.) shows an SC! port programmable features nd DDR. ‘st hits in 68HCII/I2. SCI a UART asynchronous mode por. Communication i in fll-duplex mode forthe SCT iransmission and receiver. SCI bau rates are fined as prescalng bits. Rae not programmable separately for vidas serial in ancl ur lines. Abad rate canbe selected among 32 possible ones by the thee-ate bits and t00 Dspay odo t | = Messages Note BB Teen Steen ‘Pon can hava or2 __ ai ‘rmore asoresses alone ort ard om ‘ew adress Bue np = (eee ues | enol ORD, ° jo a : Se ‘ay Fig. 2.4 (a) Parallel input port, output port, and a bi-directional port for connecting the device {(b) The handshaking signals when used by the IO ports Example 3.4 JBM personal computer as 2 pall port with 25 pin conector. There are 8 10 pins, 5 input pins for Stats Signals (our ative ih $3 $6, one stve lw S7) rom external device por (or example, iting deve port) and 4 out pins for conrosignals (one active high C2 and thee ative low (5, Cl and C3. The 8 pins ae ground pins Pisa 0 V), The satus pins and contol pins ate provided for hendshakng between zripheral and compute. Devioes and Communication Buses for Devices Network 145] Faure 3.4) shows the handshaking signals Am extemal input device to the devi port makes tle request, STROBE. altri is ready 10 send the byte and the system 10 device ses the acknowledsement, PORT READY when BR, (receiving bullet is empty. ‘An extemal output receiving device sends the message ACKNOWLEDGE when the IO device port ms the BUFFER FULL sipnal The processors sent the INTERRUPT REQUEST message when BR, transmit buffer is empty ot ul (available for next write) or when the receiving buffer is ful (available Fr next read), This enables the processor to interrupt and rerausmit next byte(s) in next eye or recive the bytet) from input using the appropriate service outnes for ouput or input fom the por, respectively Example 3.5 Intel 8255 is «programmable peripheral interface (PP) chip. A PP device has four adresses, the fr the Ports and one for the control word. Thre are thee Bit ports: port A. B and C. Pon C can also be rogrammed to fusion in bit se-eset mode. Each bit ofthis port can eset 0 | of reset to 0 by an appropriate contro! word, Alternatively. the pots can be grouped as Group A (Port A and Post C upper four tits) Group B (Port Band Por C lower four bits) 1. Inmode O programming fora group, each port group doesnot use handshaking signal 2. Mode 2 programming is used for port A input 38 well as output In mode ? programming forthe _0Up A, por A uses handshaking signals, STROBE, PORT READY, BUFFER FULL. ACK and INTERRUPT and port A functions as a bi-directional 10 por. 3. Mode I programming is either for porta input ora ouput In mode | programming forthe g104p A orB, for A or Buses only one ofthe two handshaking signal pis ether(STROBE. PORTREADY) or (BUFFER FULL, ACK) plosone INTERRUPT signal, “The following characteris are taken ito consideration when intrcing a device por. 1. A device pont may have mul-byte data inp utes and dts opt bales Seppose there ssn eight utes, Assuming that adevice (asthe 80196 miroconrole)cansenecate te nerrpt, one on receiving a byt. one on eeivng the fourth byte and one when te bute Tl the th ‘ean for servicing these inept increases upteight tes compared tothe ese when there a single byte episte instead of ber. 2. A port may have a DDR (Dats Diresion Register) (as inthe 6BHCIT mirocontoller This an avamage since each bit ofthe pois now programmable, I cin be se input or euipat DDR Programs he port bits 3. Port LSTTLivng capability and por-oating capably are important chaste, A port my ‘bean OD open ran) por. Ith eo driving capability unless the drain connects the posi supply voltage. the given port has OD gates an appepratepllp resistance or ansistr connected ¢ach port pinto provide the diving eapabili. The ain or collector connects tthe supp volage provide the pall up. 4. a given pos quasi bisection (a in 80196 then port pins ave limited diving capability. hich sufices fora pernd of one rae clock eels and ves LST at fr tht pened When this device port comectsto more tan one LSTTL hen an pyopriate pulp cic wl be required forthe po pins as ‘5. There may be mule or temate functionality in the pot pins for example 8096 if pr pis. achpinof Phas analtenative use as mult-chanel analog input acy for analog inputs. Anker examples 8051 two pos PO and P2. These portbis lo ave an aerate function a tha they bring out when needed the intemal maple buses forth extemal program an memories whence th fae, Emvedded Systems intemal memory is instlicien Each pin of P3 in SI has multiple wes, These are use during serial communication, simericounter signal, nterropt-signals,and RD and WR contol signals forester tnemorcs, 68HIC11 ports B and C ate of $bits each and have alternative uses for the port pis in i Gav of tre alternate functions is o bring out the mteral address and data buses. respectively. 6. A port may have provision for multiplexed outpt te connect to multiple systems or units 4. A port may have provision for demultipleed inputs from multiple systems Or unis ‘Apaallel device port can have parallel inputs, parallel outputs, bi-diectional and quasi-bi-diretinal TOs ‘A parallel device port can have handshaking Pins. parallel device port can also have contol pins for onerol-sgnal outputs (o external circuit and sats pins for inputs of status signals to extemal cuits. 3.3.1. Parallel Port Interfacing with Switches and Keypad |A 6 Keys keypad has many applications. A mobile smartphone device has 16 keys and four menus selec up. don ffl right keys, Assume that an 10 device has two ports, A and C. Thedevice has a processing element ‘which functions asa Keypad controlling device (controller). Figure 3.5) shows how ast of switches or 2 Keypad of 16 keys and four memu-select keys can interface tothe device. Fourbits of an &-bit input port A (A.-A,) can be used forthe four menu select Keys, Assume that the ile sate logic state equals 1, The 16 keys canbe considered as arranged in four rows and four columns “The other four bits of A (Ay-A>) are inputs from Sense ines from four rows, Assume that the ide te Fgh stat is equal to I, The four bts of output por C(C-Cs) are output 0 sense Hines in four columes. "The processing element in device activates fr polling the output port te times each second and sends ,-Cy= 0000, aftera wai it reads Dy-D, and A.A, The processing element computes the code ol the pressed ay and generates @ status signal when a key is found presed, From the bit pattern found at Avy the processing element computes 7-5 ASCII ced ofthe pressed key a that intanee snd can output that cod a By-0,, It ako outputs Dy = | hen specific key is found pressed, else Dy = 0, The processing element aso processes the bounces wen a key is pressed. Tis takes care of bouncing effects. Tae procesing element fs thus funetoning as 9 Reypad controller. ast is keypad specific. Example 3.6 A mobile phone keypad is smart ands called T® keypad. Nine keys are used to enter not only the numbers but also text of messages. The processing clement is programmed a a state machine to compute the ASC ode tobe sent. slate machine generates the slates, For example, a Key marked as number 5 in state (0-5) in eset sate, whichis also its ile state. The key-ste undergoes transition to state (1, 5) when itis pressed Fist ime. When its presedsecondtime within |, the key sate becomes (Ij). Thissat corresponds fb character itis pressed third me within 1s, he key-state becomes (Ib). Te sate ofthe key changes ina cyclic fashion. (1,5) (1j) (14K) (1,8), 5) (The taston ofa key tate oocurs ‘only iit found pressed within I s of te previous transition andthe appropiate ation takes pace as per the sine. The processing element computes the ASCII code from the read value of Ag-Ay and Key state at an instance. After processing is over or after I, te Key-state resets 0 (0,8) "Two key states simultaneously or separately undergoing transitions can define a transition to anther state: For example, win there i transition wo (1, state after another Key tte i (1, 4), then (13) lundergoes another transition (o (1, j), and When that key state is (0, #) it remains at (9. Devices and Communication Buses for Devices Network oats | 1650.1 (Pati or San ine) arto | ‘cnt ‘els Phase ara Sacks 0, 1,2,3,4,in4 Prantl. [+-} indexeot detector at 360° ~~ To6 LEDs Tapia capper ator ais) ever taneisore Fig, 5 (a) Parallel input port Aand afourbit output port C used for interfacing a set of 16 keys in keypad and four menu select keys (6) Parallel input port A connected to an encoder cect which senses the rotated or linear position of a moving shaft and port B connected to 6 LEDS (c) Four bt porallel output port C connected to a stepper motor A parale device having a number of input and oupot bts canbe used to find the code ofthe pressed Key ina matrix of kes, A keypad controller has processing element to compute the code ofthe pressed key tnd to generate a status signal when any Key i found pressed, A mobile phone keypud controller processes the states ofthe Keys to enable application of same keypad fr dialing as well as eliting SMS messages 3.3.2 Parallel Port Interfacing with Encoders Encoder is. device that measures angular o iear poston ofa rotating or moving sha Ithas application i ‘robots and industrial plans. A rotatory-angl encoder has multiple acks ona rotating disk. Bach rack has half ofthe segments transparent and half opaque. linearencoder as amultsloted pla. A set of n infrared (OR) LED and photoransistor pairs generate bit inputs fora port. The encoser comets to parallel pot, shown in Figue 350). 3] Embodded Systems 3.3.3 Parallel Port Interfacing with Stepper Motor A stepper-otor rotates by one step angle when is fur evils ae given curensin a specific sequence an tha Sequence is altered, For example, assume that cueents a an instance equal + i 0, 0.0 in four els X.X’.¥, ‘Y" The motor rotates by one step when the curents change 00, +0, 0, Te sequences at intervals of Tare changed as follows: 1090, 0100, 0010, 0001, 1000, 0100, ...FThe bts in the nibble (et of bits roate by right shifi] Here ! comesponds to + i The motor thus rratesn step anges in interval of nT), The sequences sae changed orotate the motor in the opposite diretion, as follows: 0001, 00010, 0100, 1000, 0001. 0010 [The bits the nibble (set of 4 bits rotate by left shift Atemately the coils re given the cutens inthe sequence of 1100, 0110, 0011, 1001. 1100, 0110... oF 0011, 0110, 1100, 001, 0011, 0110, ... The motor rotses(n/2) steps in imerva equals fo (1/2). Tis the period of clock poles that dives the motorby change of col curents tothe next sequence. The coils connect to parallel port 4 output pins, as shown in Figure 3S(c) Altematvely, a processing clement called stepper-motorderiver canbe used. The driver i given two outputs from the port clock pulses ‘5d rotating direction bit For example. ifr= |. motor ots clockwise and ifr =0 then motor rotates at clockwise. The motor rotates as long as clock pulses ae given a the ouput PC,-PC, 3.3.4 Parallel Port Interfacing with LCD Controller ‘An LCD controller has processing element that needs three control signals inputs and 8 inpudoutpu bis for parallel set of 810 bis. Eight-it parallel out port B pins PBy-PB, connect LCD controller 35 shown in Figure 3.6(a), LCD controler also connects to one bit PC, at an output port for RS (riser select) signal. Wonca _—— tose é 1 mor Lee! =| lI Soler a__|| j i — —B__| | “rae coma, Soar uo Sears —| Lop display Conmroter | Phe | L ay - “en Seven Dey pecs ata bs for dea, contol andstaus wore RR o ‘ata er Touched Poston Fig. 3.6 (0) Eight bitparallel output port 8 connected to an LCD controller (6) 8-bit parallel output Port B and 8:bit paralel input port A connected to a touch screen control circuit Devices and Communication Buses for Devices Network [we | When RS is eset 80, PBy-PB, communicates contol wor ta contol ester ofthe LCD contoliec. When RS is set as 1, PBy-PB, commbnicaes data tothe LCD contol The LCD controler also connets to @ one bt PC, at output pont for R/W(readite). PCy is set to ‘when status register of LCD controle is rea fom PBy-PB, PC, is eset.00 when writing inte LCD controller ‘he PBy-PB, bits. The processing element generates al signals required for LCD displays The LCD controller is ent cone! words and data weds fr initialization and programming PB PB, bis, and PC, output foreach word to LCD controler The controller then has tobe enabled by sending 1 at E pin connects one it PC; at ouipt pon fr E (enable), There i an interval in whic the controller may bein sable state. During this interval. eames ace nsirtions or data through the output of contol word o¢ ddta port pins. For example, a como insttion sa clear display. The intra processing clement hs to cear the bytes atall the Naddresses in N characters LCD display. Assume that na typical LCD, itis 150 us. When he firs 1 is writen at E, then Ois writen and a 150 ys delay program is called in-between; dhe E oulpt creates a negative going pulse at LCD contol. It dsables sending of any contol word or data fra period of 150 ps LCD controller has M displayed character ROM adresses. M = 128 for 128 ASCII codes. For each distin ASCH character, there is a 64-bit graphic. The LCD controller has an intemal CORAM (character ‘graphic RAM), Foreach ASCH character, 8 bytes ae set from font table ROM to CGRAM adress, CGRAM has N adresses. N= 64 when 64 characters are displayed atthe LCD, An address changes by incrementing ‘or decrementing the cursor position othe previous Ornext address onscreen. By ending appropriate contol words followed by dat, the LCD controler is programmed to display up o 64 characters on the screen, ‘A paral device having 8 omput data and 3 bts for, RS and R/W canbe used to connect oan LCD conte. 3.3.5 Parallel Port Interfacing with Touchscreen ‘Touchsercen is an input device cum LCD display device. It is also interfaced through 10 port B functioning as data bus far display, contol and status words oan LCD display’ device onto, The imertace ‘uses an adaitional input port A fra byte, which cresponds tothe adres ofthe position touched on the seeen. ‘A touchscreen is either resistive or capacitive. On tuching a a position on the seeen, there is change in resistance or capacitance, which depends onthe touched position. A touch can be finger or sys. The sys is abou one-ih thinner than.a pencil and abou haf ofthe length ofthe penil The resistance o eapacitance is part of a bridge citeit that generates an analog voltage. An 8-bit ADC is given an input from a bridge circuit andthe 8-bit ADC output connects to 8-bit input por A. Eightbit parallel 10 por B pins PBy PB, E. RSand RY W and eigh-it parallel input port A connect to {ouch sreen circuit ports as shown in Figure 3.6). An interrupt signal INTR isisued whenever the screen is touched, Example 3.7 ‘A PocketPC has a touchscreen, The touchscreen device facilitates GUIs Ican display menus as well as viral kejpad. Using the Keypad on screen an sys, St of characters can be entered for creating ‘orediting SMS messages, emails, or other files. They is held ike a pencil and is wed to touch the virtua keypad and then the device selects the menu and commands onthe screen {s0| Enteled Syste Devies and Communication Buses for Devices Network 1 5. An 0 device may consist of multiple gigabit (622 Mbps o 3.125 Ghps transceivers (MGT. Special are examples of cuits Support circuitry 1s needed for this ete, Rocker [0 ™' serial transeceiv that provide supp ciciey at this oe (6. vice foe a 10 may integrate a SerDes (erilization and de-serialization) subunit, SexDes is a ‘andardsubunitinadevice where the bytes placed at "iransmitholdng bulfe” serialize on ansisson, and once the bits are eeceived these de-serialize and ae placed atthe “receiver buffer’. Once the device eres sunt is configured, serialization and de-serialization is done ewtomaticaly without the use ofthe processor insevtions, The great advantage ofthe SetDes unit is that these operations ae fast whon compared to operations without SexDes. (A. device for 10 may integrate a DAA (direct scces aeangement using analog 10s slong with one master and seven slave CODECS) of McBSP ‘A device port may not be as simple asthe one fora stepper motu pos or fora serial line UART. Nowadays. {nul channel butfered serial port with high speed communication subunit when seilizing. ‘complex embedded system has highly sophisticated 10 devices. oe example, SDIO ard (Section 3.2.6), 10 7. Recently nitiple 10 standards have been developed for 10 devices. A support to the raultiple 10 standards may be needed in certain embedded systems. A technology, Flexible Select 10 ™* Ula technology, supports over 20 single-ended and differential 10 signaling standards. Advantages of [A poratlet device having 8 input dat bits from an ADC and S 10 data bus and 4 bits for INTR. E, RS and R/W can be used to connect & port interface with + processing efement to a touchscreen. The [ADC generates input bits for the port fom the analog signal. which is a per the touched positon on the sereen, ” 3.4. SOPHISTICATED INTERFACING FEATURES IN DEVICE PORTS ‘devices with fast serialization and de-erialization of data, fat transceiver, and eal Lime video processing system. The following are the few sophisticated interfacing device and port features 1. Letthe operation voltage evel expected for logic tate | = 5 V (TTL or CMOS). The Schmit rigger circuit has a property thal when a ransiion fom 0 | overs only ithe wltage level exceeds 2/3 of the 5 V level is there a trantion to I. Similarly, when « tamsition from 1 420 occurs, only ifthe voltage level lowers below 1/3 of the 5 V level i there tramsition to 0. Hence, de Schmit igger circuit eliminates noise as large as 2/3 of 5 V, or 3.3 V. when its superimposed at an input line tothe device. One great alvantage of the in-built Schit riggercivcuit atthe pos conditioning ofthe signal by noise elimination. Otterwise, a device port input will ced un extemal chip for Schmit trigger based noise elimination. Sucha device is wie in transceivers or repeating systems, which re used in long distance communication, 2, When device pot is waiting for inseuetons. power management can be done athe gts ofthe device, Lately. a new technology called Daaate from Xilinx) hus been developed for we at pots. Datta is 4 programmable ON/OFF switch for power management: DatGate makes it possible o reduce power ‘consumption by reducing unnecesary tngeling of inputs hen these arena in ws, The seat alvantage ofan inbuilt DtaGate-lie circuit at a device ports reduced power dissipation when the device por is operted at fast speeds. Sich a device i exremely wsefal in systems connected 10 common us aod there is @ need 10 contol unnecessary input toggling. For example. in a bus interface unit the input signals should scivte only when the input hast be passed tothe circuit, As the aumber of bus interfaces inthe ystem grows, the demad to prevent needless switching of input signals increases. 3. Earlier, port interfaces used tobe ether open drain CMOSs or TTL or RS232Cs. (i) Nowadays. a system maybe fequited to operate ata voliage lower than 5 V. [Recall Section 1.1.) Low Vaitage TTL (LVTTL) and Low Voltage CMOS (LVCMOS) gates may be used atthe device pons for 1.5 V 10. (i) Nowadays, system may be requied to operate using advanced 1 standard ineraces. Examples are High Spoed Transteceiver Logic (HSTL) and Stub-series Terminated Logic (SSTL) standards STL is used for high-speed operations; SSTL is wed when the buses ae tobe fsotd fom relatively large stubs 4. A device connects oa system bus an als to 10 bus when its networked with other devices. Device and bus-impedances during an 10 should match. Es, tine reflections occur. Recent developments make it feasible to match these dynamically. Forexample, anew technology, called CITE (Xilinx Controlled Impedance Technology canbe used. The great advantage ofan inbuilt evie for dynamically matched impedances is that when resistors are eplaced with digitally, dyeamically conrolled and matched impedances inthe devices, there are no ine eflecions and therfore no missing bits or bus Faults. vale standard device os are abvious S, Am iO device may iterate digital Physical Coding Sublayer (PCS). Analog audio and video signals ca then be pulse code modulated (PCM) atthe sublayer. The PCS sublayerdietly provides codes from analog inputs within the device tel. The codes are then saved inthe device data buffers. The ‘ulvantage of an inbuilt PCS at device port is that these is then no aced of external PCM coding Besides hese operations ate perforned inthe bockpround as well ay fast IL Improves the system's povformance when there are mulimedia inputs atthe device 9. A device for 1O may integrate an analog unit Physical Media tachment (PMA for connecting direct inputs! outputs of voice. music, video and images. The great advantage of inbuilt PMA is tha the evice detty vonnects to physical media. PMA is needed for real-time processing of video and aio inputs al the devi Nowadays, 10 devies have sophisticated fesures. Schmit rigae inputs are wsed for noise elimination. Device with iow volage gates and devices using power management by preventing unnecessary toggling atthe inputs ae wed for sophisticated applications. Dynamically controled impaance matching is anew technology nd it eliminates line reflections when interfacing the devices. The SerDes subunit serializes and deseritizesoutpas nd inputs inthe devices. A port may have DAA, MeBSP, PCS and PMA subunits Fr video and audio devices for anal 3.5 "WIRELESS DEVICES Wireless devices have become very common i recent year for serial transmission of bits Wireless devices use infrared (IR) o¢ radio frequencies after suitable modulation of data bits. WDA (Section 3.13.1), Bluetooth (Section 3.13.2), WiFi, 802.11 WLAN (Section 3.13.3) and ZigBee (Section 3.13.4) have become popular protocols fr wireless communication of daa bits fom a source tthe ‘An IR source communicates over a line of sight and the receiver phototransitor is used for detecting inftaed rays. Example of spplications of IR communication includes handheld TV remote conwollrs and robotic systems, IR devices use KDA protocol 152 Embodded Systoms Radio frequencies communicate over shor and long distances. The tansmitier and receiver use antennae to ransit and receive signals ad modulator and demodulator o cary the data its using RF frequencies, Mobile GSM wireless devices use 890-915 MHé, 1710-1785 MHz, or 1850-1910 MHz bands Mobile CDMA wireless devices vse 2 GHz carier frequencies. Bluetooth and ZigBee wireless devices (Sections 3.13.2 and 3.134) use 24 GHz or 900 MH frequencies The number of frequency bands is limited, while a large numberof devices may need to communicate Therefore time and fequency division multiplexing are used. An innovative method is radio frequency hopping over wider spectrum, asin Bluetooth devices, The wansmitted carrier frequencies hop among, different channelsata given hopping rate. The transmitter modulates the data bitsas per protocol specifications, “The receiver tunes to these hopped cartier frequencies ata given hopping rate and inthe same hopping sequence asthe ones used bythe ransmiter. The receiver demodulate and detecsthe data its as per physical: layer protocol used for transmitting Several wireless devices network use FHSS or DSSS transmitters and receivers, Popular protocols are HDA, Bluetooth, 802.11 and ZigBee. “3,6 TIMER AND COUNTING DEVICES Jost embedded ystems need a timing device 3.6.1 Timing Device [A timer device i device that counts the regular imterval (ST) clack pulses at its input. Te counts restored tn inesemented on each pulse. thas output bits (ina count riser or atthe output pins) fr the period of ‘counts. The counts mallipied by interval T gives the time, Te (counts-intal counts) x ST iaterval gives the tine interval between two instances when the present count bits ae ead and the intial Counts are read. thas a input pin (or & control bitin a control register) for esting to make all coun bits=U. tas an output pin (or a status bitin statu register) For output when all count bts equal afer reaching the maximum alu ‘which also means timeout on the overtlow, 3.6.2 Counting Device ‘A counting device isa device that counts the input for events that may occur at irregular or regular interval. “The counts gives the number of input events or pulses since it was las ead Blind Counting Synchronization & counting device may be a fre running (blind counting) device with presale forthe clock input pulses and for compariag the counts withthe ones preloaded ina compare register. The prescalar canbe programmed as p= 1.2.4.8, 16,32... by programming a prescaler register, [alvides the input pulses as pe the programmed value ofp. It has an output pn (ra status bitin the status register) for output when al count bits equal 0 ater reaching the maximum value, which also means after timeout or on overflows. The counter overflows after p x2" xT interval. cean have an input pn (ora control bic in contol register for enabling an output when all count bits equal count preloaded in the compare register. At that instance, status bitor ouput pin also sets in and an interrupt can ocr for event of comparison ‘quality. Tis device is useful forthe alarm or processor interrupt preset instances or after preset intervals with respect fo another event from another source. Devices and Communication Buses for Davions Nework 153) ‘The counting device may beth fee running (bind counting) device with a prescalar for the clack input pulses, for comparing the counts with the ones pretoued ina compare register ay wells or eaptring counts ‘on a input event. This device function ar ilar othe above, But tere san ation tpt pa for sensing anevent and for saving the counts a the instanceof tat event. AL this instance a status bit ean ao set aad a processor iterupt can occur forthe capture even The above device is useful for alarm generation ad processor interrupts athe preset times as wel as for noting the instances of occurences ofthe events and processor interrupts for requesting the processor to use the captured counts onthe events. Alam generation canbe synchronized with the input capture evens Wiring counts into the compare register does this. Counts inthe register are et equal o capture resister counts plus additonal counts, which define the interval afer which an alarm is tobe generated, ‘A blind counting free running coumter with presating, compare and capture registers his @ number of applications. 1 i uefa for action o initiating a chin of ations, and proces interrupt atthe reset, instances as well a for noting the insances of occurences of the evens and processor interrupts for requesting the processor to use the captured counts on the events for future actions 3.6.3 Timer cum Counting Device A timer cum counting device isacounting device that his to functions (1) Keounts the input duct the events a iegoar instances and (2) It counts the clock input pulses at regular intervals. An input ora status bitin the timing device register contots the mode as timer r eaute. The counts Bives the numberof input evens Or uses since it was lst read. I hasan output pin (ra satu it in satus ester Fr cup when al coum Bits ea after reathing the maximum value, which aso means timeout or overiow intemupts to the proceso Table 35 lists twelve uses ofa timer device I also explains the meaning of each we. Table 3.5 Uses of Timer Device “Applications ond Explanation RealTime Clock Ticks (tunetioning as ystem eat eas). [Real ine clack isa clock that one the system tsi doesnot sop andca'tberes cont vole con't be eased. eel ine endless {Ses ard never veturs! Rea Tee Clk se fo icks sing preseling bas and set bis in spproprite conrl registers Seton 3.8 ives the deta Initiating an even fle 2 reset delay ine. Dely ic asp coun lade Iniatng an event or a pair of evens ora csi of events) aera comparison between the preset time with counted value. Preset ie is edd in 3 Compare Regist smi preseting on aise] Capering the count ae athe ine nan event. The nfoation of rine (stan ofthe event) |S toed tthe cptare resister Finding the time imeral tween two evens. Counts are captured at each event in the cape restr and read. The neva ae ths fd ot, service routine des he coats ed oni ‘Wai fora messge from a queve ar mix or seraphore ra preset tine when asing an RTOS ‘There is a predefined wating peso befae RTOS lets 2 ak us without wag for the mesge (Section 74) eon) Emoeddes Systems ‘Watcog tire. W resets the sytem after a defined time Section 27 gives det 8 Bout or Bit Rate Control or serial cormerication on a fine or network. Ter tines interups ein the tie of each Baud 9 Input pulse counting wher ving. ime, which s eke by giving non periodic ipa nea of the cock ings The ine sa a counter iin place of clock inputs, te inputs re ven othe timer for ea instance becouse 10 Scheding of various asks, A chain of softwaetimer items and RTOS uses hee itera seed the asks. u “Tine scng of varius tsk A slitaking or mltipogrammes operating system presents the deson that lil tsk oF propsams ae ening snulanenil by switching between yrograns ‘ery rapidly, for example, alr every 166 ms. This proces is krown a8 conte seh, RTOS Shtches afer preset time lice frm one runing task the nest. Bach ek can therefore re in redefined sts of ine 2. Time division muliglexing (TDM), Ter devices used for matpexng tipo rom a mamber ot efunncl Each chanel input is lone distin and xed ee lot ope TDM outa (For hanple ple tlphone call are the ips and TDM devi generis the TDM output for launching tothe opal re A timing device bas number ofstaes and Table 3.6 gives the stats. Table 3.6 States in a timer ‘Sater Rest Sate (til eoua equals 0) Init Loud State nia count odo) Present Stat (Couting or idle or before taro afer overflow or ove) ‘verfow Sie (count received to make count equal Oller reaching the maxim coun) ‘Oven Sate (evel counts received afer eahing the ovelow ste) Running (Active) Stop (Blocked) state Frise (Dooe te (topped after» pee ine interval o tino) Reset enblealiabed Sate enabled etn of count equal O by at input) ‘Lond enabediiobed State eset count equals intl coun sir the timeout) ‘Auto Re Load enbledsabed State embled cout equal ina eran er the timeout) Service Routine Execution enabledsbl State (enabled aftr tenout or overtiow) 3 4 s 6 ‘Atleast one hardware timer device ia must in system, Iis used asa sytem clock, Let number of system clock ticks needed befor a system intemupt occurs equals umTiks. Te hardware timer gets the input from 4 elockout signa fom the processor and activates the system clock tick as pe the numTiks preset atthe hardware timer, On each system clock Hck, the user-mode task interrupts and te system takes contol, The system enables the privileged mode actions and the CPU context switches as pr the preset slate ofthe system, ‘The system contol ations are performed by operating system (software), Devices and Communication Buses for Bevees Network 155 Figuce 37 shows hardware timer vont! bis (and signals) and status fags. Como Bits ave 38 per the hardware signals and corespondins hits at control register. Control bits (r signals) can be of nine type: ‘These ate: (i) Timer enable (to activate a timer. (i) Timer start (stat eouming a each eloek input (i) Timer sop (to stop counting) sium tho next clock input (iv) Presealing bits (o divide the clock-out Frequency signal from the provessor. (9 Up count Enable (to cnable counting up by incrementing the count ‘value on each clack input) (vi) Dow csunt Enable (to decrement on a clock inp. (vit) Lad enable (i cnable loading ofa value at register into the time) (vii) Tm-inlerupt enable (to enable imerupt servicing ‘when the timer ous (overfows) and reaches count value equals 0) (x) Time out enable [to enable a signal ‘when the timer overflows (eaches count equals 0] 1 anoter device Tenis ott cn aes Ter —— | i reste soo. ||| Deancount [uae re “er \V"_les ‘ols FLL} | joes mer rc ea oun LYs-4 ae fs ht + commivene t aaa Yo eet ea cae om Coes —Veedge erate 2 Ane ni sone a ck ein a keen Fig. 3.7. Signals, clock-inputs, contol bits and status flags at registers or memory in a hardware timer device Stats lagi as per the corresponding hardware signal time-out from the hardware time. This flag and signal set when the mer al bits (own value) reac to 0. “Table 37 lists ten forme of the timers forthe uses lise in Table’. Software timer (SWT) isan innovative concep. fi ‘The system clock or any other hardware-iming device ticks and generates one interupt or a chun of Ierupts at periodic intervals. This imecva is as per the count-value set. Now, the interupt becomes a clock input to an SWT. This input is common to all the SWTS that are in the lst of activated SWTS. Any number of SWTS can be made active pu ina ist of active SWTs. Bach SWT wil set a status flag on its Uimeout (count value reaching 0), Figure 37 shows the cont bis and satus bis in an SWT. SWT control Die are set as pe the application. There is no hardware iaput or output in anv SWT. A flag sets when the SWT count-value reaches 0 after reading the maximum. Table 3.8 lists all the variables of SWT. It includes the conto-bits and status flags. SWT thus has similar control variables and Mags sin the hardware 'SWT actions are analogous to that ofa hanware timer. While theres physical limit (1,2 or 304) forthe numberof hardware timers in a system, SWTS canbe limited by the numberof intetupt vectors provided by the user. Processors (microcontrollers) aso define the interrupt vector addresses of two o¢ four SWTS. Embedded Systems Load sotiare timer ww numtias an Sion — -[___Sotware Tier Contos vatas 7 Stas Flog . pegeunt ‘swrjole nate ve - “IT ame C1 ee eee ‘Execule a Service Routing, for example, for an AUC Sean ane Frame 000 camera ure &. 30) SW Tnoout ig. 3.8 Control bits, status flags and variables of a software timer ‘able 3.7 Ten forms of a timer Hardare ineaa ner 2 Satwae une wh rere cele hte ine : 2 efosSScttuwar ume Ar TOScan cic te ck sk pe eset shar tier {op tro ancten OS Nels Non Section 921] 5. Nereperatctineoucn (odin ser onrow at) Asie wy be oanmele forties incon a 6 SSRReec stat he ovetow nis ne) kgs on vena ea ito runing sat rm il state Wi alo usd for eforcing te dels between wo Sates een On te ever reaching a sate one sot ine sats and after theme out another tale of ent sca Up count ston Timer His timer tat increments on each cout input rom a eae, Bow coun ation timer ti timer that decrement on esth counting ‘Tnr with isoverow sts (lag), which ua resets as 00 8 inert service routine tats ning. “Time with overiow-fag, which des ot at reset Born ing vise rena fra nar of sina yt () The aly beanie nanbe ftv rence inte nue Aon heat ce hawe Une hesse che o! m Ofcom aye ira me va eee cal Skt he pct ond poz spr ls, Ug theses clk rer thc deembfetae incre Testnon ae prance ded {Otten dtc rasa coat ey 8 eps tout ornate ek np The state nro ees ner Chef loon sng al Sf newest ming vies Tee tumbe of contd ie ot ts apn ach eri Deviees and Communication Buses for Devices Network 137] Table 3.8 Variables for contro! bits and status in a software timer Tar Sor Vv Rese Value 32/168, Inia Load Vatu oui) 3/16 Countale (Preset value} 32/164 Maximum Vale 12/1618 Minimum Valse 32/168 Timer un enable bit Timer interpt enable it Timer rset eae bi “Timer lad erable Bit 10, “Timer rel (ater fnised state) erable ie Ovetow eg 3.7 “WATCHDOG TIMER ‘Watchdog timers tming device that can be set fora preset ine interval and an event must occur during that interial else the device will generate the Timeout signal. For example we anticipate that st of tasks ust finish within 100 ms, The watchdog timer disables and stupsin case the asks finish within 100 ms. The watchdog timer generates interrupt after 100 ms and executes a routine that rns Because the tak failed to finish in the antcpsted interval. A software sk can alo be programmed asa watchdog mer (Section 9.33) A inietocotroller nay so provide Torte watchdog timex ‘The watchdog timer has 2 numer of applications. One application ina mie phone is that the display is ‘ured off in ease no GUL interaction takes place within a specified im. The interval in usally sett 15,20, 25.030 sin a mobile phone. This saves power Another application ina mobile phone shat a given mem is nt selected by a click within a preset time imterval. another menu canbe presented or a beep can be generated to invite user’ tention. ‘An application ina temperature controllers that i @ congo takes no action to swith ofthe current within the preset time, the current is svitched ai and warning signal sed indicating controller fare Failure to switch off curent may cause a boiler in which wate is heated 0 bus Example 3.8 S6BHICI! microcontroller has a watchdog tiner in the hardware, There are two registers, CONFIG (system configuration contol register) and COPRST (computer operating propery and processor reset on flue), ‘They are for programming te inlerupts of watchdog mer. CONFIG has abi, NOCOP. It configures when the processor writes the configuration wer at adress Ox003F. NOCOP isthe 2™ it of CONFIG. It this biti reset 0, the COP facility is enabled. [COP meaas computer (6SHICI1) operating groped watchdog timer. The COP watchdog timer provides for Keeping a watch on execution time Of the ser program.) ‘When user propram takes a longer time in a routine than pgned or expected te wer provides for Storing at desired intervals: first, the GxSS and then the OxAA athe computer reset contol egiser COPRST. By keeping a watch means that as soon 2s the watchdog timer overflows (cme ous), the program counter is eset according to 16 bits atthe lower and higher bytes tat re preloaded at addresses OxFFFA and = Embedded Systems 158) : Er Socom, which eae a when tees on pws up or eet cot he oie te 3.3 “REAL TIME CLOCK time clock (RTO is lock hat ease occurances of Fe Tn cues on exch ent (vero) of hi lock, This ting devi one= a ets ovis ever loaded with anther value, Once tse, its aot modified late, The RTC is aera etc seth cunt time and de. Te RTCs aso used ina syste nia of cnt! thie sptem (OS) arte preset system lok periods ut interval ierrupts on its cat tck(imcou, Example 3.9 (Assume ht a hardware tier of n RTC for calendar is programmed to nterap aterevery 5.15 ms Sane at teach ck (ntemup) a service routine runs and updates ata memory location, Within one J5 Gott) tere willbe 2™ teks, te memory lation wil ea 03000000 fer reaching che maou, a OREPAEFR. Within 256 days there wil be 2 ticks, the memory Heaton will each 000000000 “Mer eaching the maximum wale OxFFFFFEFE. Note tha batey wns be used to pret the memary for that ong pei. akan pecesor cock afer 0.5 ps. Ill overfow and execu an overfiow interrupt sevice routine wi pO ys 92768 ms Te trp service own can generat pot bit output aes every tne runs sac ocala software routine or sends a messge fra task, Iin'=30 the RTC iad softer wil tun every 30% 32.768 ms, ich is close to 18 Ta ae dk ina fr trop a esl itv is present ina mice, BHC tsa riser called the Puke Accumulator Cont Register, PACTL and (wo lowest significance bits Bey RTg ("and ®), PACTL isi ony- 1 the RT Tyas 0, an interupt can occur aftr 2° pulses tthe Esock. the Block pulses are of 2 MHz and thus Tis 05 us, the ntesrupt em a eal ime clock cour ater each 4.096 ms. the RT pis 1, an interup can occur after 2 pulses ofthe cock, that flr each 8192 sf the RT-R pir 1, the interup can occur afer 2” puss ofthe Devees and Communication Bes fr Davies Network 159] E clock, that safer each 16:384 ms Ifthe RT, RT pris 11a iterup can cur after each 2° pulses fof the E clock, that if fer each 32.768 ms. The realtime clock is based om a free runing counter in 6SHCH. RT}-RTy bits cont its at of ticking, The interrupts from a real time clock are disabled or enabled by 1 bit in clock control (CC) register The interrupts from real ime clocks are also locally masked by the 6" bit, RTL in timer interupt ask register2, TMASK2, Ths bits set to unmask ind reset to mask the real ‘ime clockintrrups. FRTI and bits permit the interrupt request fr ral ime clock timeout then the microcontroller Fetches the lower and higher bytes ofthe interrupt servicing routine address from the addesses OxFFFO foc higher byte) and ONFFFI (for lower byte). This is the vestor ade for real ie clock iterups in @8HCLL. The interop service routine must clear (0) the RTE, which s interrupt fag for the eal time clock iteeups. ‘The RTIF isa bitin timer interrupt flag register, TFLG2. The TFLAG2 isataddess 0x0025. tis et by each interrupt from the realtime clock interrupt and therefore it must be cleared in order to «enable next iterupt before returing fom the corresponding sevice routine and before the next reakiime clock-inerupt occurs ‘Areal time clack (RTC) provides sytem clock and ithasa numberof applications. Kis aclck hat generates system interrupt at preset intervals. An interrupt service outine executes on each ck (imeout or overflow) this lock This timing device once started is generally never reset or ever reloaded to another vale. ~ 3.9 “NETWORKED EMBEDDED SYSTEMS tach specific 10 device may be connocted to others using specific imerties; for example, an 1O device ‘aie: andisintefaced to an LCD controller, keyboatd controle or print enol using specific interface. Bos communication sitplfes the amber of conncesons and provides mana protocol fo interconnecting Aitferent or same type of 10 devices ‘Any device that compatible with a system's [0 bas can be added to the system (assuming sn appropriate device driver program is avaiable). anda device tha seompatble with a particular 10 bus canbe integrated Jno any system that uses that type of bus. This makes systems that use [0 buses very lesb, as oppesed to tee interconnections between the processor and each IO device, and it allows sytem support to many Aiferent 10 devices (depending onthe nsods ofits users). andi also allows users to change the 10 devices that are attached to system thee noods change ‘The main disadvantage ofan {0 bus (ad buses in general) is that each bus has fixed bandwidth that mst be shared by all the devices, which connest to the bus. Even worse, eletrial constants (wire length and transmission line effects) cause buses to have less bandwidth than using te sae numberof wires to coanect just two deviees, Essentially, there i a trade-oTbetween interface simplicity and bandwidh sharin, Assume ‘tat bandwith of a busi 200 Mbps. Ihe bus communicates two devices simultneonsly then it does so by 100 Mbps communication by each, 10 devices communicate with the processor through an 10 bus, which is separate From the memory bus thatthe processor ses to communicate withthe memory system, Embedded systems connected interally on the same IC or sysiems at very shot, short and Tong distances, and can be‘hetw "ed using the followings types of 10 buses, each functioning according w specific protocols {Using a serial 10 bus allows a computer or controler or embedded sytem to interface network with a ‘wide ange of 10 devices without having to implement a specific interface for each 10 device. When | 160 Embedded Systems tae 10 devices inthe disibuted embodded systems are etworkel atk istanees a 25 em and inp spaae Obs allowsacompute econo ented tno ere wilh anuber fina sytome ter short dances waar Raving inplerncit pectic ech 10 vce Soto 8 It esrb he ral! bcm ph 3, Uae te eret oan compete entero eb yc 1 vie can neice pnysndcanetwek wider penr comptes wang o vce, uted Sony Section 312 debe thse tens 4. Uning’s wiles peo allows a handheld computer, contol rmbt 0 devi mri a tne ith mumber of handel syscm 1 devi st sot stances 0 10 perl ee network (WPAN) potecol. witht Haig topes specie Stier cach 10 device. Section 3 deserts wiles bs omnia protocol Embedded ystems are distributed and networked using «eral orpaalle bus or wirees protocol software and appropriate hardware, eee | Senar bus conte orexarple, | | se ortac orca i == Seta ) oa) 5s SS ‘Gowirtmre] [Tooneeneme ] [ieonteneass Processor of ] [— Proceasorof | [Processor of [LPeeweme | |__ Tevet || ysteme | TO besos nrc Fig. 3A processor of embedded system connected to system memory bus and networked to other systems through a serial bus ” 3.10 “SERIAL BUS COMMUNICATION PROTOCOLS Figure 39 shows a processor of embedded system connected fo system memory bus and networked t other systems through a serial bus, Sections 3.10.1 t0 3.105 describe popular serial buses. Devices and Communication Buses for Devices Network vet} 3.10.1 PC Bus ‘Assume that there are number af device ceeits ina numberof processes ina plant. am IC each for measuring temperatures and pressure. These ICs mutually network through a common synchninous serial bus. EC (Unter C connects busi popular bus for these cies, There are three PC bs standards: usta 100 Kbps FEC. 100 kbps SM IC, and 400) Kops °C. The PC was originally developed at Philips Semiconductors, The FC Bus as tines that carry its signals—one ln is for cock and one ifr biirectonsl data There {sa protoel le FC bus, Figure 3.1) shows te signals during a wansfer ofa byte when using PC bus Each device his ress using which the data transfers wake place. The master can address 127 other slaves at an insane. Has processing element functioning 38a bus conlleror& mirocontollr with PC bus interface eiruit, Each stave can also optionally have an PC bus eoniollr and processing element. A number of masters can als connect to the bus. Hever, at any instance, there canbe only one master. whic ise that initntes data transferon SDA (serial data) Fine and which transmit the SCL (serial clock pls. From the master ot sane, daa frame has Fields beginning fom start bit as per Table 3.9. Figure 3.1000) shows the format ofthe bits atthe PC bus Table 3.9 vita bt silat he one in a UART, Tei eae the adress ik defies the ave alos being se the data fame (of many bytes) by te masts | Secon fed of 7 is Third fll oft control it Ie eines wether a read or waite cyt is in poses. Fourth fed ofl conrot it Nexabitdefines wheter the present as an acknowledgement (rom th ave) it it of Wb leis nad for I device dat be {tis a negative acknowledgement it (NACK) fram the maser: Iactve, he | acknowledgement after a transfer isnot needed from the slave eee | {ckrowledgement is expected rom tesa Iisa stop bi ie ina UART. Sat field of “The disadvantage ofthis bus isthe time taken by algorithm in he master hardware that analyses the bitk FC incase the slave hardware dees not provide forth hardware that support it. Some ICs support ocol and some do no, In that ease, interface circuits for those ICs are alo required. Also thee are ‘pen collector drivers atthe master. Therefore, a pull-up resistance of 2.2K or an ative circuit for pall up of line to gic # Fer on eah Kine i esse. [PC is seal bus for interconnecting ICs. ha star bit anda stop bit liken a UART. ft has seven fields forthe stan, 7-bt addres, defining a read or write, defining byte as an acknowledging byte. data byte. [NACK and end 2.10.2 CAN Bus [Number of devices and controllers are locted and are distributed ina car An automobile uses number of distributed embedded contoes,incladng those for the brakes, engine, eletre power, lamps, inside ‘emperature control air-conditioning, gate front dash bord display meter display panel and cruising contol Embedded controllers must network through a bus. CAN (convoller area network) bus isa standard bus in Aistibuted network. Its mainly usedin automotive electronics is also sed medical electronics and industrial plant contoles. Embedded Systems stan Be ‘Stat Ades Bi 7] nace Reade Secure HBG 5000 | heisroron ° Fig. 3.10 (0) Signals during a transfer of a byte when using the 'C (inter Integrated Circuit) bus (b) Format of SDA bits at the FC bus ‘he CAN Bus [Figure 3.11(a) network hs a serial ine. which is br-dvetional. CAN bus his mltimaster and molicat eatures. A CAN device using CAN controler receives send itatany instance by operating fat the maximum rate of | Mls (bitperiod = 1 ys). Itemploys a twisted pair connection of 120 ohm tine impedence at each controller node, The pai ean run up toa maximum length of 40m. 1. CAN sail line pulled 10 logic level | hy a resistor (active or passive) between te line and 4.5 V {0 +123 ¥. Line is at logic | ints idle tate, alo called the recessive sate 22. Bach node has a bufer-pte between an input pin and a CAN sera line. A node gets the input at any Jnstance from the line after sensing that instant when the lite is pulled down 10 0, The later scaled dominant site 3, Bach nade hes a current driver circuit between output pin and serial Tin, The node see bit 0 fine by pulling the line O by its driver for abit period. An NPN transistor s wed curen-driving transistor theemitter of which also connects t the line ground and colector connects tothe line. Using a driver {consisting ofa buffer inverter gate connected to base ofthe NPN transiso), the node can pl he tine {00 which is otherwise at logic in is ile stale. This lets other nodes sense the input 4, Anode sends the dats bits data fame, Daa frames always start with | and always end with seven (Between two data frames, tere ae minimum thee feds, Table 3.10 gives the deals of each ile jn a CAN frame, Figure 3.11(b) shows the format ofthe bis ina CAN frame, 5, The CAN-bus line usualy inerconnects{0 GAN controller between the line and host node. [4 host rode is one that has controller for use as bis master] The line gives input and gets output during ‘reception and transmission using physical and data link layers a host node. The CAN controller has @ BBIU (bus interface unit consisting of buffer and driver, protzol conte, atus-cum-conol registers, receiverbuffer and message objects. These units connect the host node through hes interface circuit coves an Cmmuncaon Bus 6D Howe {res} 6. Thete isan arbitetion meted galled CSMAVAMP (Cammer Sense Multiple Access wih Arbitration ‘on Messe Pity) A nul sts ansmitting on sensing 2 dominant bit, which indicates tha amther ge is wansmiting. Table 3.10 Each field in a CAN frame isla Pincton| Fist itd of 72 Bie This biraton Fel, which contains he pake’ 11 dation aess ind RTR (Packt means t fis ent on he us) RTR sland fr Remote TTramisson Request The eeving adressed device i a desinaion adress specie in 1-2 uid and RTR i denon the basis of wheter he data Peeing seni dat forthe device ra eauest the device It ase ‘fies the vce which ats is being sentor tbe reget being ide: When in KR bi ti ean thi pcks i forthe device t destination aes. I hsb i at (ominont ste) means thik ia request forthe dt om the device Itiscontl fit Te fis iis identier extension. The second bi ays The it 4 Bs are code for eta ength Second field of 6 bis Third fill of 01064 bite ‘ns fethcepes n te at length code in con fe Forth fl ied dase tis CRC (CyeieRededoney Check ld with IS-hit CRC ps it {Fidos no bt present dete bi Te ses nate west et ero any, Ug he | of 16 bts: trnsaonen Fit is ACK sk’, The Sener sends ita and te eave, wich wo ‘sh fas Oi his sot when tle ror ecepion. The sealer ‘Sig (inthe ACK sl, retest the data fae. The seco Bit he "ACK deli: signal he end of ACK fel Ite ansiting male sss tse ay anowledzement of Jat sme wan a specifi ime Slat should rac | “This ithe endothe Fre specification and has seven ‘CAN is a serial bus for interconnecting a cental contr! network. is widely used in automobiles. It as fields for bus arbitration bits, control bits for address and data length, data bits, CRC check bits, ‘acknowledgement bits and ending bts ith fd of 2 be ‘Sich fld of 7 bis 3.10.3 USB Bus Universal Serial Bus (USB) ia bus between hait system and numberof interconnected periperal devices. A maximum 127 devices car connect to hos, I provides fst (yp to 12 Mbps) and aswell stow spee (up {o 1.5 Mbps) serial transmission and reception berwcen host and serial devices. A USB hos, which includes onioller for function as bus nastercan comet sh memory cards, pen ike memory devices, digital camera, Printer, mice, PocketPC and video games, The are three standards: USB I.I(a low speed 1.5 Mbps 3 m ‘channel along witha high speed 12 Mbps, 25m chanel) USB 20 (high speed 480 Mbps 25 meter channel), and wireless USB (high speed 480 Mops 3). USB protocol has this foature—a USB device can be hot plugged (atached). configured and used, reset ‘reconfigured and use it can share bandwidth with other devices, detached (while others are in operation) cnet oo [bedded cortotor Ls S55 Gong eon corer [1 mutica marta sranamion ooaras ca 120 hm ine impedance twsied pax CAN and CANS wires Seal 0 bos oa = oe ee CAN eonoter CA canter CAN contoter (AN conte ie Ie — =i Erbeedea Embedsed Enbeded Emesies | conttersystoms | | contote system | | contotarsystem 0 | | conmatersytom | (@npie consater) | [fara take conan] | ash bows) (wansnaion) | MEE sonvt io Ovastin © GIED sseccne. sexier (raptor etek ROR) HE AC andor er CE) 7 enn ramet (5 o- 64 bits data length code (J Sit minimum inter frame gap site ane (anda rca) j fife Siosnaro 1 ig. 3.1 (a) Network during a transfer of data when using the CAN (Controller Area Network) bus (b} Format ofthe bits at CAN bus ‘and reariached. Auaching and detaching can be done without cebooting. The host schedules sharing of brndwidth among te attached devices. A USB device can either be bus-powered use powered. nan, there isa povker mangement by software at host for USB ports. {USB host connects to devies or nodes using USB portrving software and the host controller connected toa root hub. A hab is one that connects 1 ater nodes or bulbs. A tee-liketoplogy form as follows, The root hub connects to the hub and node at vel 1. A hub t Fev! I connects to the hub and node at level 2 and ‘0 on, Only the nodes are presenta the last level, The root hub and each hub ata level connect in a star topology with the nex eve. The USB device descriptor data structure has hierarchy. which i sfllows: I nx device descriptor at the roa that as numberof configuration descriptors and each configuration descriptor ‘hs number of interface descriptors and which has numberof end poi descriptors. LUSB bus cable has four wires. oe for +5 ¥ tw for twisted pairs and one for ground. Tere ae termination impedances at each end that areas per the device speed. Eletromageetc Interference (EMI-shieled cable is used for 15 Mbps USB devices. Serial signals are Non Retum to Zero ((NRZI) andthe clock ix encoded by inserting a synchronous code (SYNC) field before each packet. [Refer to Table 3.2]. The receiver synchronizes is bit recovery clock continuously. The data transfer is of fourtypes: (2) Controlled dato transfer (b) Bulk data teasfer ) Interrupt ‘riven data transfer () Iosynchronous transfer, USB is potted bus. The host controler circuit regula polls the presence ofa device as scheduled by the software, It sends a token packet. The token consists af fields for type, diecton, USB device addcess and Ont nd Gra Bs De fis ‘device end-point number, The device does the handshaking thug handshake packet, indicating successfol_ ‘cunsuccessfil tansmission.A CRC fel ina dat jucke enables transmission eri detection at he receiver USB supputs three types of pipes—ta) “Sica” with ny USE-defined protocol I is used when the ‘connection 16 already established and the data low sar th) “Defias Control for providing accesn. {) "Message forthe contol functions of the device, The host configures each pipe for the followings (ay data tandwidth tobe used, (bans serve type and fe) buffer izes ‘Wietess USB is wireless extension of USB 24nd it operates at UWB (ultra wide band) 3.419106 GH Fiequencies. Is used for short-range personal area network: thigh sped 480) Mbps 3 nto 110 Mbps, 10m ‘chasnel).FCChas recommended host wice adapter HWA) and device wie adapter(DWA), which provide wireless USB solutions. Wireless USB also suppontsdual-ole devices (DRDs). A device can be a USB sevice as well asa Tinted capability bos. For example, a witless USB digital camera uses a USB host when connected to a printer and a USB device when eannete o personal computer wireless USB device i used to provide rp ce computer and mobile service provider network, USB isa serial bus that interconnects a sysemn,Kataches and detaches device from te network. Hues @ root hub. Nodes contsinin the devices canbe oxzanized like a tree structure. Iis mostly used in networking {he 10 devies lke scanner in acomputersystem, Wireless USB isused fr remote connections without Wires. 3.10.4 FireWire — IEEE 1394 Bus Standard Digital video camera, digital camcorders. digital video disk (DVD), set-top boxes. and music systems multimedia peripherals, latest hard disk dives, and printers need highespeed bus stndard interlace for ‘communicating diet to a personal computer. FireWire (IEEE 1384b) isa standad for 800 Mops serial Jsasyachronous daa testers A FireWire IEEE 1394 port can operate al up to 10 Mbp ad the nest machines include FireWire ports ‘hat support IEEE 1344b which operate at up NOM Mls. Since FieWire cam rane dat aa guaranteed Fate. is aso used in real time devices, suas vids dice dat transfers A single 1398 port can interface up (0 6 exer Fie Wire devices. lt supports beth plug and play and hot plugging. I also provides self-powered and bus-possred suppart an te Bis FiceWire is high speed 800 Mbps serial bus fr inerconnrcti devices and systems. 4 system with multimedia streaming 3.10.5 Advanced Serial High Speed Buses Section 3.2.6 described SDIO. which im advanced high-speed serial bus for handheld devices. An embedded system may need to connect mul gigabits er send (Gbps) transceiver (transmit ana recive) sri! inerface. Exemplary products are wireless LAN. Gigabit Berne. SONET (OC-48, OC-192, OC-768). The following ate examples of te advanced bus prosocol |, TEEE802.32000{1 Gbpstandwidh GisbitEernet MAC (Mulia Access Coto for 125 MH performance 2. IEE PS02.3oe dat 4.1 {10 Gtps beret MAC| for 156.25 MHz dual direction performance] 5. IEEP802.20e draft I [12.5 Gbps Ethernet MAC | for fouchannel 3.125 Gbps per channel ransceiver performance] XAUI (10 Gigabit Auachment Unit) ‘XSBI (10 Gigabit Serial Bus Inerchange) SONET 0C-48 SONET 0C-192, SONET 0C-768 ‘ATM OC-12146/192 venpee Embedded Systems rn PARALLEL BUS DEVICE PROTOCOLS— PARALLEL COMMUNICATION NETWORK USING ISA, PCI, PCI-X AND ADVANCED BUSES seater sue cones thigh send oe subsystems having eng of 1 devices at ery sb ae re eutebs wibout having ment 2 spines Fr each 0 device cies (25 cn i 3 ot embeded susp fe twos, cn communicate ough @ Fee ee pra bus has ae numberof is spr he pool. Figure 3.12) md) Srna bedded sytem A conse em rary bw and petwarked to ter Systeme through a parle bs PCI oning PCI bridge and AMBA-APB bridge spectively. a Sars S [ates [omnis (Spent) [Geaphie Conioter| [ScsiControter | { 10 controler ainteD | oom J LS snontor cet | oo i so @ (fovea) oped (808 | rime] mons | {o) and (b) A processor of embedded system connected to system memory bus and networked to other subsystems through a parallel bus using PCI and AMBA-AP; bridges ‘We need an interconnection bus within PC or embedded system toa numberof PC-based 10 cats, systems and devices. This bus needs to be separated from system-bus that cospects he processor to memories, The Fig. 3.12 ‘evi ard Communication Buss or Devices Network (7) “yen usa ineonmston as operate at iene of pas temp devise ply deen tse desecr mene te is cn wo cr har sk contol, in Fan ee cece ad scumingUispay, HIGD He Tard a ea wsng DEC 2100 PCL Cae eae ie aol e devices which pert ic unto, may conti procs aaa A tre Each doves tiapelic mony desing spa mera vecors easier anne yal devi 10 pot ese, Ab appr pins rd prot meres these to het sem or computer Seay cate Cl bsimerae swith cessor csuniaton with th mmr bi 0 Fae et pe peso hava snl da bs cones twitch mule suchas he PC serpents any BC tems alugh some prcesor negra the sich module eno te sane do cathe pero eds he nb chip oq tila syste hereby eg ae nth commit wih he nny tough memos bs and dedicated et wits ae pemcen thes seme A sepwate 10 bus cote he sich t0 10 devices Sepa sh a boaeane wed became te IO sytem genre designe for maximum exibiiy.tallow en 6 ives yobl ints tothe compar, wie be memory Ds sige 10 ue mcm posible tandwidth econ te proceso ar merry »ysem. re imeomesion bes frcommuniaon etvcente sand advice ae ISA an ISA Extended ea caren ten forthe bn eer PCI or PCIX. [A vat fs CompactPCI PCD Scots 12110312 dsc tee paral! bs communication pack Parallel bus interconnects 10 devices and peripheral over very short dstanes and at high speed. ISA, PCT Ad ARM buns are examples of parallel buses. A. parallel bus interfaces the system memory bus though 1 ide switching circu 3.11.1 ISA Bus ISA bus (sed in IBM Standard Architecture) connects only ton embedded dovies that has an $086 o $0186 te 82K proctor ad in which the processor addressing and IBM PC architecture addressing limitations hd interuptwoctor ates assignments ue taken into account. There is no geographical addressing, Th fniaion for memory access by system using the ISA bus of the orginal IBM PC ere as flows: ISA bus momory access can bein two ranges. 610 to 1 MB and 15 to 16 MB. The former range also verlap with the ange wsed by video beards ad BIOS, [Not: Linux OS dees not support he second range For accessing dietly a device. | Fhe 10 port ales liitaons for devices areas follows: The #086 to 80286 processor has 10 mapped 10s, not memory mapped 10s. Though the instruction set provides for 10 jnstruetions Fr 64 KB IO adresses, the IBM PC configuration ignores the adress fines Ayyt© Ays and these are not decode, Therefore, only 102410 port adresses are avalable. A hexadecimal adressing scheme wit hee nibble adessng between 0 to ARF only can be used fora device. The Aye to Ajsbils are thus immaterial, The following ae the addresses allocated in IBM Standard Architecture (ISA) 1 Adres allocated are 01000-Ox00F for DMA chip 8237. The akresses fo other device areas follows: 2 Oxd70-Ox021 adresses allocated are fr programmable interrupt controller 8255. Hex Ox040-0x043 for timer 8253, 4. 0060-01063 for parallel port programmable parallel interface. 14 The hena decimal adresses OB0-083, OAO-DAF, OCO-OCF, OED-OEF allocated are for components on the motherboard 168 Emboddad Systoms 5. Reserved addresses from peripherals are hex 220-248, 27%-27F, 2RW2FT, XCU-ACF and 3ED 0 3F0, The akresey allocated are hes 2F8-2FF and 3ER-3FF for IBM COM port. 2 Adurewses ae hex. 320-32P and 3FO-3F? for hard disk and gp diskette, respectively. S. Qnly 32 address between 01300 to 0x31 ae available for prtsype ead: for example, ADC ead 4, Adresses allocated are between hex 380-389 and 30-349 for synebronous conimucaion 10. Synchronous Data Link Control (SDLC) addresses allocated are between hex, 380-38C. within 380-38F (monochrome) and SEN-ADF for (colour and graphics). of interrupt vectors inthe IBM PC SU86 family. Gy 256 vectors are availabe. fterrup service lunetions are now shared at soliwace level for example, SWT irlesrupts. Original ISA specifications did not allow tat ESA bus isa 32-bit data and adres-tines version of ISA, and devices (system using this bus for 1) are «iho supported. An ESA device driver first checks the EISA bus availability on the hosting computer oF systoar. It supports the shoring of interrpt function, SCI (Serial Communication Interface) controller and Ethernet devices. Unix and Linux support the EISA bus-driven card and devices, 1A and EISA buses ae compatible wth IBM architecture, They are used for connecting devices following, {0 addresses and interupt vectors as per IBM PC architecture, EISA is 32-bit extension of ISA, It also support software interrupt functions and Ethemes devices, 3.11.2 PCI and PCI/X Buses ‘Revel the most used yychronous paral! us in the compte system for interfacing PC-based devices is PCI Peripheral Component Interconnect), PCI provides superior throughput than EISA. It sane indepsrst, uke the ISA. which depended on the 1M PC plate intirapevecuors. 10 addresses and ema allnations, Is ctck rate is nearest ro the submatiple af the sytem clock. PCI provides tree types sof syncTnns parallel ineraees. ls versions ae 32/33 MHz. 64/66 MHZ, PCL-X 64100 Mr. PCI Super V2.3 161528 MBps 3.3 V (ona 64-bit bus), 132/268 (ona 32-hit bus) and PCI-X Super VI. for 0) MBps ‘54 i bus 33 V. PT bus has 32-bit data bus extendible to 64 bits. In adlton it as 32-it addresses extendible to 64 bit, Its protoco! spits the interaction between the different components of a computer. specification version 2.) issynchronous/asynchronous throughput sup to 132/ 528 MBs [33 M x 4/66 Mx 8 Bye. t ‘operates on 3.3 signals. A iypical application isan exemplary PCI Card has & 16 MB Flash ROM with ‘outer gateway fora LAN, ‘A PCI driver can access hardware automatically as well as by addresses signed bythe programmer, The PCI feature of automatically detecting the interfacing sysiems and assigning new addresses is immportan for coding device driver The PCI bus therefore simplifies the addition and deletion (ttaclament and detachment) ofthe sysiom peripherals. A manufacturer registers a global number for PCI devie or car, just as, 68HICI or $0386 are globally registered numbers, A 16:bit egistr in PCI device identifies this number to Ft that device auto-detected, Another I6-itrecistr is fra device ID number. These two oumbers allow the device to cay ou auto-detection by its host computer. Each device may use FIFO controler with FIFO butfer for ‘maximum throughput. ‘A device or host identifies its address space by thee identification numbers (10 por (i) memory locations and (it) configuration registers of total 256 B with a 4-byta unique ID. Each PCI device has address space allocation of 256 bytes 1o access it by the host computer The unique feature of PCI bus is is configuration address space. A uniquely assigned interupt type ( number) handles an interupt. For example, interrupt type 3 has the interrupt vector address Ox0000C and four bytes atthe address specity the inemupt service Devices and Communication Buses for Devices Network routine adres, Interrupt type can e Hetween (O0 and OxFE. A configuration register number Stes the fone byte fur the incrupt ype ip). The PI device or host wien intrurted handles te intrupt ype iped. Figure 3.13 shows 44-byte standaed configuration register in a PCI device. Foll abbreviations used i the igure MID: Vendor 1D. Dil): Device ID. RID: Revision ID. CR: Common Regis. CC: Class Code. SR: Status Register. CL: Cache Line. LP: Lateney Timer BISP: Base Input Tick, HT. Healer Type. RA: Hase Address, CBCISB: Card Base CIS Pointer. SS: Sub System. EspROM; Expansion ROM. MIN GNT: Min Guaranteed time. MAX_GNT: Maximum Guaraneed Tine VID, DID. RID. CR. SR. a HT ace compulseily configured. The rest are optional Mor j ora j—PRFOM | —__ rare ——e [the MT MEE cg a om =e S| a [= coor = [ssw | ss00 “loco =m = [=e = [am = | an = Jono wo | oo | cal sa | ao [=co— Jafar [ur] ast joo ‘Oxo 1 — nF Fig. 3.13 64bytes at standard device independent configuration registers ina PCI device or host A PCt conte nest acces one device at atime. Thal the devices within bot compar can share 10 Port dresses un memory Intins but cannot share the eiguration registers. That means that device ‘cannot modify other configurion esisters but can acces other device resources or share the work or inet the other devi. there ane reasons Tor it doing so, a PCI driver can change the defauh hp assignments ‘on configuration vans A deview ca inital at booting tine. This helps in avoiding any addres collision. A PCT device on ‘bootup disables its imerrupt. cadres spaces inaccessible and only the configuration regisersspace remains sccesible. PCE BIOS withthe device performs te configuration tansactions and then memory and address ‘spaces automatically map tothe address space in host computer CI parallel bus is popular in distributed embeded devices, PCL and PCUX buses reused for parallel bus ‘communication and these are independent from the IBM architecture. PCUX is en extension of PCL and supports 64/100 MHz transfers, PCI bus new version support 132/528 MBs data transfer with synchronous! asyhehronous throughputs. 3.11.3 ARM Bus ‘ARM processor interfaces the memory, external DRAM (dynamic RAM controller and on-chip IO devices, which connect to 32-bit data ani°S2-Nadress line at highspeed using AMBA (ARM Maia Memory Bur Architecture-AHB (ARM High Performance Bus}. Figure 3.12(D) shows AMBA-AHB and AMBA-APB bridges. The bridges interface the memory ad exterral-hip 10 devioes, which operate a low speed using AMBA-APB, The maximum AHB bps bandwidth is sixteen times the ARM processor clock. i170) Embedded Systoms -Asovitch,populatly called the AMBA-APE bride, switches ARM CPU communication with the AMBA tacts APB be The ARM prucessor-based mirocontollerhas a single data busin AMUA-AIs hat connects pevje brdge, which imyrats the Bridge ono the same integrated circuit a the proces to reduce the ‘Number af ehipe equi io bul a system. This reduces the system cost, The bridge communicates with the ‘Memory trough an AMBA-AHB, a dedicated set of wires that transfer dt between these two systems. A ‘Gpurte APB 10 bus connects the bridge the IO devices. Separate AMBAAHB and APH 10 buses are seer pecaune the [0 system is generally designed for maximum exbility, to allow as many different I Govices ws posse wo imerface tothe computer while the memory bus is designed to provide the maxinvm posible bandwidth between the processor and he memory system “The APB can connect the °C toushsereen, SDIO. MM (multimedia car), USB.CANand other required imerfaces tan ARM microcontroller, ARM bus is of two types: AMBA-AHS and AMBA-APB. AHB connects to high speed memory. APB. connects the extemal peripherals the system memory bus through a bridge. 3.11.4 Advanced Parallel High Speed Buses Many tlecommusiation, computer and embeded processr-basd producs need ple! buses for stem TO. Three sersions of PCI parallel synchronouslasyachronous buses provide system-synchronous pallet arcs These tree versions may nt have sufTicetly high sped, ultra high speed and large banded hat de auired fr system 10s, outers, LANS, svtches and gateways, SANs (Storage Area Networks), WANs ‘Wide Area Networks) and other products. These do not meet the source-synchronous parallel interfacing ‘Chuiements Bandwidth needs increase exponentally inthe order of audi, graphics, video, interactive video aa prondhand IPv6 Inienet. An embedded system may need to conncet IO sytem using gigabit parallel Spocironots inex. The following ae alvanced tus andar and proprietary prtocls developed ently 1 OME! (Gigabit Ethernet MAC Interchange Interface), 2. XGMI (10 Gigabit Ethoroet MAC Interchange Interface) 5, CSIX-1. 66 Gbps 32-bit HSTL with 200 Miz performance 4 RapidlO™ tnteteonnect Specification vi. a 8 Gbps with 500 MBps performance or 25 ME daa dleetionceginering performance using 8-bt LVDS (Low Volage Data Bu). "3.12 INTERNET ENABLED SYSTEMS—NETWORK PROTOCOLS Figure 3.14 shows an Internet-enabled embeded system communicating to ther systems onthe Interne Inconel enabled embeded systems use hil or MIME type files (Section 3.12.1, TCP (Section 3.122) or AUD? «Section 3.12.3) wanspor layer protocol, and are addressed by an {Padres (Section 3.12.4) and se IP protocol at network ayer An IP addres is of 32 bts (four decimal numbers seperated by dots inbetween) oF {BS bits in [Pvt or Pv6 respectively, IPvd means IP protocol version 4 and [Pv6 means version. A systema one IP adress | communicates with another system at another IP address 2 0 or. using the physical connections toute tenet and the routers. Since the Internets glabal network, the system connects to remotely located 5 seit short range cated system. Network connectiviy is through the layers. Each ayer has protocol, which Spocifis the way in which the data oc mesage from the previous layer transfers to the nex layer. “There are five layers in a TCPIP network. They are the application, anspor, network, dattink and pysteal layers. The TCPAP application layer protocol als specifies presentation ways. Transpot layer protocol Specifies session establishment and termination ways also ‘Sections 3.12.10 3.125 deserbe the TCPAP suites five most used protocols Devices and Communication Buses for Devices Network m1 Embedded systems are Internet cnabladhy using TCPMAP protocol suite protocols foraeworking to Inert and asigning the IP addresses wo each system “ ilar MIME typ leaner using TCP or UDP tranepet lyr arocal ‘Embeds r one C “TOPAP network = {9 Neworcintrtace | [ Neworcintace | [Network taetace | | Networkinetace | WP sdeoss2 1 sees 9 Frat Computer| Paasenss Fig. 314 An internet enabled embedded system communication connected on the internet 3.12.1 Hyper-Text Transfer Protocol (HTTP) Anapplaton yer rata ser ppl This yer cette dt eran a HTML tema pus eet wor sp rea an ese aplaton eRe pl thetipon ter portent he patna Fllwing tera can Iyer seal th spp TCP acing PrP (twee rol) gai yao clack on a wok 21 MIME esis att mail peso il. The examples se inte io. 1 te (SOFFICE Word doce fe 5 gap nage amat er 1 Fred tora igs te ad 3. TTP Pr 8) eis ner cometiviy by Hyper-Tet Ter rt HTTP 4. ET ch 2 or conol 20 for ents ie taser comeciy ty Pe Tae Pot "ETE eon) for Tvl FTP NFS (Netwrh Fe Sen td or sing Hien 2m 5. TELNET (hart 2) mbes erat login emote tris by Terma Acs Pract 6: SAP ont 35) ene eal ser oa ora by Sage Mal Tse ras 4 PoP3 a 0 erates al eee &. NNTP (ha 1) (tort News Tranter Pots a i es are or, 5. DNS hat 5 for Domai Name Sac, 10, SNM Pore 61 Sipe Netwerk Magee Pros 11, Boots and Boxip Par: 6 an 68 fr Bost tcl (ONCE) Serer nd Cet. especie 12, DHCP Dyramt Host Confguatin rac med for emote btn aswel fo conga system. - A pasted monte sigpors milla conection ings ket Es socket is Pa sudporianber A epidced pon mberenbs cena 102 Restrain dey ANA Cnr 72 Embedded Systems Assigned Number Authority. Poet number mus nt sell A user une! red server an have Bort umber above S010, HTTP pont $i is an application lager protocol, The HTTP feature ae a allows 1. HTTP is standard protocol ec eguesting fon a URL (universal resource locator) address. fr expe Ingp www. oegrawhill com.) An URL. detines web page resource. and is usd for eeeivany of sending weh page file. The response fa ch may be with or without applying a press. An HFT “tient requests an HTTP server on the Interne and the server responds by sending a response HTTP is a stateless protocol. For an HTTP request. the protocol assumes a fresh request, Tans there is no session or sequence numer field or no Fick! that i retained in the next exchange. This makes current exchange by an HTTP request independent of the previous exchanges. The lster "exchanges donot depend onthe current one. An e-commesce-tke application needsa state management ‘mechanism, A Cookie isa text file cred during a particule pair of exchanges of HTTP request snd response, The creation i either at CGI oe pressing program or script or at eent (Browser) A prio ‘exchange may then depend on this cookie. By this mechanism, the stieles feature of HTTP is ‘compensated. Th cookie provides a HTTP site management mechanism 3. HTTP i filetranser-ike protocol for HTML. (hyper ext markup language les. This makes iteasy to explore a web ite URL. A request frm cient) is som and epy (responve fim a server is receive 4. The HTTP protocol is very light fa small Format) and thus speedy as compared to other existing Protocols, HTTP is able to tater any type of data to browser (a client) provided its capable of handling that dats, 5. Besides simplicity. another iniportan feature of HTTP isis Hesbility. Assume we ae surfing the web ud our connection bres (oF user does so) then tno we ean start surfing onthe Net fom jus that Point again. Being a stateless proto. HTTP does ot keep track ofthe Mate as FTP does. Each time ‘connection establishes between the wel server ad the cient (browser, bat these interpret this anection as a new copnestion. Simply i a mast HecauNe a web pa fas its URL rescurces listibuted over numberof servers TTP proxocol is hased on the Objet Oriented Programming System (OOPS), Methexs are applied 'e objects identified by URL. Wt means that 2s in the normal ese of Object Oriented Program. the ‘aious methods spy on an objet 1 Brom HTTP 1.0 and 1.1 venion onwans the flowing Features have been include: (4) Multimedia file access is feasible de to provision or the MIME: (Multipurpose Internet Mt Extension) type file definition. (b) From HTTP f.1 version onvares. there are eicht specified methods and eatension methods. An extension method is method added for & specific HTTP, There can be none or one of several extension methods, The HTTP specific methods are a follows. 1. GET 2, POST. 3. HEAD 4 CONNECT. 5, PUT6. DELETE 7. TRACE. 8, OPTIONS, (List four Irom 1). Ineatier versions, GET folfows a space and then document name. Server reiurs the documents and closes the ‘connection. From 1.1, the POST method has permitted form processing. the client ‘wuss the form data o ther information tothe sever Foes I. the server does not lose the ‘connection after esponse and thus response ean be processed befor itis sen (} A provision of user autenticaton exists besides the basic authentication introduced from HTTP. LI version onwards, Digest Access Authentication prevent the transmission of usemame snd *assword as HTML or tex (G) A host header field adds to support those ports and vial hosts that do not accept or send TP packets. From HTTP f.1 version onwards, An error report to client when a HTTP request is Without a host header fl, 6 Devioes and Communication Buses for Devices Network fe) From HTTP 1.1 version onwards, an absolute URL is aoreptable to the server. Earlier nly proxy server accep ha. (f)_Staus codes inthe response. (2) Caching ofa resource is provided at server and proxy). (Byte range specification helps in large eesponse in pars. (@) Selection among various charctenstis on retrieval by the client is feasible when a server sends ‘response to client request For example. two characteristic, lenguage and encoding cane spied in server envionment varabey while the client sends request healer for retrieving 3 resource, “The resource then retrieves in that aauage and with that enceing. The contents sent to client donot change. only the way in which these ae presented to the client change. (0) Length specication hes in pesemation in chunks. 8. An HITTP message header during a request from a cient or during a response from server consists of {pars (a) A start-tine, none or several message: headers (fields) and empty line, and (b) Body of message. HTTP specitis that request message ta consist of request message headers. HTTP also spetifies that response message t consist of response message headers. 9. HTTP provides for entity headers, These conan information about entity body containedin he message, rin case body is not present then information about the entity. not its body. For example. information of content length in bytes, 10, HTTP interaction scheme is that a client requests server drei or through proxy ra gateway. An HTTP message i therefore either rues or resprnse. The format ofthe messages called REC 822 specifies ways of sending text messages on the Internet. The message ding request fom client or ‘uring response from server consists of two parts. (a) Slain, none or several message-headers elds) plus empry ine, and (b) Body ofthe message. The sar lines either a"equeseline” or aus. line" for requestor response-message, spective 3.12.2 Transport Control Protocol (TCP) ‘TCP (Transport Contol Protocol is protocol used in ranspot layer. This ayer accepts messages fom the "upper layer on transsssion by application or session layer. This layer also accepts a data steam from the network layer at receiving end. Before communicuing 3 message to the next network layer. it muy ad 2 header. The message may communicate in parts or segments or Fragments, The header generally has the Additonal bits for source and destination addresses. Aso thereare bis init forthe sequence and acknowledge ‘management, low and error controls, et. ‘There are bits Fr the offset, window, fags. checksum, urgent pointes option and fr puding also, TCP supports the pont to point networking moe "TCP specifies a format of bye steams atthe transport layer of the TCPYP suite. TCP is used fora full duplex acknowledged Now. fs format has a TCP heade of five plus (n-5) words for options and pacing and data of maximum 1 word, Then, 122'*~°n, Here n> S.n equals the number of wort inthe header and is called data offset, which means the number of words after which data its statin the stream. fn >3, means there exists words for options and padding. Padding refers obits use for filling the remaining pat of ty- available field. For example, the option field may indicate the application ta be ran by the destined node. Aa ‘acknowledged flow means that the messages communicate in a point-to-point network mode and that here an acknovledgment for fist establishing 2 connection, Full duplex means tht ota given insigace. rasp 0 1 and ro from Sender to reciver, and thatthe receiver acknowledges receipt. A request and is response «donot form a separate transmission, TCP is vrtua-connection orieted. It does not permit mulkicastng but point-to-point vizual connection, liza Embedded Systems | 3.12.3. User Datagram Protocol (UDP) TCPAP ts sepportatthe transpor layerasimper procul han TCP. When a message connectonless stateless. hen the tansprt ayer procul nthe TCPAP seis User Datagram Protocol (UDP). UDP supports the bevadest networking made. An exasples application for communicating header before a data stream. The header specifies the bits for source ans destination pos tt lngth of message including header and check sam (optiona, During reception, this message to upper layer Hows afer deleting the header it from the received transport layer header. Hear bits add atthe transiting ime in th application or session layer bytes. 3.12.4 Internet Protocol (IP) All Internet enabled devices communicate using Internet protocol (IP) The wansport layer data transmits on the network vides into the packets at the network layer. Each packet ransmits through a chin of routes on the Inte. acket is minimum unit of data that transmits om the Internet through routers. Several pacts forming a source can reach a destination using different routes and ean have different delays. The packet consist of IP header plus data or IP header plus outing protocol along with the routing messages. The packet hs maximum of 2" bytes 2! words. 1 word = 32 bis = 4 bytes) Network routing is as per standard IPv4 (version 4) of TPNG (version 6). IPG isa broadband protocol, ‘Table 3.11 lists the fields in {Pvt protocol header Table 3.11 Various fields at IPv4 header for routing the packets through routers to destination node Field ar the Pade Version [P version bits O10 for IP presen in wide se) and UI10 for BPv6 (Pag IP ret genation for bended later Precedence type i tween 840 10° bi. Bis 111 specifies highest precedence. For example or steaming suo video. 00 specifies consnon dt, i Senice Service ype is between 110 159i. | Biss for QuS (Quay of Service) spiication in ems of sca. sped, delays | Precedence (005 (Quay of Serice) au cst desied or ms be achieved, Fragment 1D Eich message may have muny packets rpmened rough he routers. Each fgment musts provide a unique I foc ienicaton foc reassembly athe receiver end, Flags Flags indicate whether present fragment is lst one, whether fragments a permite and wheter moc fragment vl fllow, Let q = Number of header Words (ord = 32-4, lg bit indies wheter more agmeats fhe packer wilsucced this agent. ag it? desi as tet fragment ont Fg bit 3 checks whether the fagmenaion i permite o no Checksum Header checksim checks enor in neder ransision. Tine Tie otive indicates numberof reason hops pert incase of fied delivery. Provcol ype Type indicates wheter the paket is ansmiting a UDP byte seam or a'TCP steam Grom transport yer The important routing protocols that encapslte after the IP ead in an packer are (Coma Devices and Commurication Buses for Devices Network IGMP (Ltemet Group Management Protocol) IGMP is 2 protecel te manage dt transis between select hos groups. Sever hos oi group. Group multicast se ters hat wes the IGMP CMW Interne Cool Management Protos ICMP sa proto 6 conto routing ereen networked boss CMP dt byt sear isms an Ppt (datagram) ts forma is allows. Fs 20 bytes minimum are he HP header. Nex follows he ls of byt each fr Type and Coe, saccesivel. Next twa bytes are for Cheat. Thea follows the CMP tmesages the forma ru engi of witch variable, Inter routing protocols, fr example the RIP (Rating afomition Pec! snd (OSPF (Open Shonest Pu Fs rocco Inter-Domain(enerioe routing) protocols for example. EGP (Esterioe Gateway Proto), BGP (Borer Gateway Procol and GP (Gateway to Gateway Pred, “The Pheader engi da off) p $2", Here g 25. qual he number won ine header and is ale te dato Number of words afer which daa bis at inthe seam] TP Source and destination IP adresses If >S, her exist wor foc options tnd pang Padding eft ite that ar wed for filing the reusing part of he rill. For example, option # wil mean pine tampa all the stopp of the peket dering tans to destination hough ter. Tne stamping enables packet delay mesorersens to ealeulate Newerk ecormance Quali Header length (data ofsa) Source and Destination addresses options 3.12.5 Ethernet “The inventor of Ethernet LAN is Robert Metcalf. Atpresent about one third f the LANS i the word are the Ethernet LANS, and in each frame, there is header like in a packet. fn Bbernet LAN standard IEEE 812.2 (SO $802.2), 1 a protocol for loeal network of computers, workstation and devices, LAN is used for sharing local computers, systems and local resources sul as pines, hard disk space, software and dt ‘Table 312 gives the feature ofthe Ehernet LAN devies, Data for transmission fagments into the frames. Each frame has a header. Fry, the header as eight bytes. which defines preamble. The preamble indicates the start ofa frame and is wed fr synchronization, “Then the header has sx bytes of destination adress. Six bytes of source adress then follows the destination address. Then there ae six bytes. These are forthe type Feld. These are meaningful only for the higher ‘uetwor layers and the length definition. The minimum 72 bytes and maximum 1500 bytes of data follow the length definition. Lay there are 4 byes for CRC check forthe fame sequence check, ~ 3.13 WIRELESS AND MOBILE SYSTEM PROTOCOLS Figures 3.15(2)(t) and (c show a handheld device or computer system connected to other handed devices ‘or computer tough IrDA, Bluetooth and ZigBee wiceless protocols, respectively. Sections 3.13.1 3.134 ) Shana tack ead rae tats Event Key resset0 nd dala of alps of mage {ake a pire ar ora | prcesor | pan | a dt oa presse Steamers rane at CCD c-pocessr chara L oe | Steers ps ms tun | data atatiome memory butor | Signal’ tak or esbracting ToCOD pits ADC sean «| Of ac compress image deta aT Bia cane ier asks |] Lg fhe |S "SA star wor “| tapas | eH"| apg hacteetsrorr ‘Event: Reset | events | Resatkey state statusbe put t for tasks to enable ire ror7/4 pec | us| entra status bit sets: LP atimotite_| 45 | signal timer stan for enabling Sepa oar 19s groettra) | 2 _-|a (Sgn tacks Send message or tsks 1s Rowe Fig. 43 (0) Use of ISR in the automatic chocolate vending machine (6) Use of SR and ‘three signals 1, 2 and 3 for three tasks in the digital camera example (c) Use of ISRin the mobile phone reset-key interrupt example Example 4.4 Assume a digital camera sytem (Setion 1.104) Ithas an image input device. When the system activates the device should grab image-rame dua. The system awakens and activates on a switch inerrupt. The inerupt is through a hardware signal from th device switch. On the interrupt, an ISR (can also be considered as camera's imaging device-drver function) forthe read starts execution it pases a message (signal) | to @ funetiono program theador task, which senses the image and then the function reads the CCD device fame bute; then the routine passes signal 2 to another function or program thread or ask to process and then signal 3, Subracts offsets using a tsk and compresses image-dta using a task. This task also saves the ‘mage frame dta-compresse ile in flash memory. The camera system again awakens and activates on {nterrup through a hardware signal from a device switch and prints the fit picture image after i decompression, The system on iaerrup then runs another ISR. The ISR routine i the device- 100 (are ae sett 2. Sra evan} mn ine 2 2 {2 Seralevone2}rnrvine? | Stem | Sa o ; Fig. 44. (a) Use of sofware interrupt (SW instruction for ealing an interupt service routines a (1R) in the software on throwing and caching the exceptional runtime conditions ar encountered during computations (b) Use of Ss to signal another routines cr program tasks or program teads to start /* Final codes, which should execute on exception or after try block instructions over */ Example 46 is given here to clearly show that SWI snd execution ofthe ISRs (aso called exception Ihnilers oF just exceptions) on SWIs. The SWIs slo play x major cole in embedded system Sofware by th: use of ISRs for device driver fanetions—ereste (open ( reed (oF other. ed ding compitaion he SW nsacions wll Isced for example 4.6 woping 0B) sepa umber and for tappingy > [0 oes has O ows é ‘war isirvtion SW at will cause proceso interrupt. In response, the software ISR fu onsider the following codes. ‘ ; eation SWI a following ee ‘ach (Exception. tal) exeuteson rowing of te exceptional aly block execton SWlale = - — oa 2 Sater cstng te xcton at winner tren, rm - fware instruction SWL 32 will eause processor interrupt * Codes for execution in which a run-tine exception or munber of run Prager. a tespose the software IR function (codes a ase tee odes {atch (Exception_2 a2) { | executes on throwing ofthe exception a2 duing ty bleck execaon Ce ‘SW a2 is used afer catching the exception 22 whenever iis town ee eee eee eee ae Software instrvtien S133 will cause processor interrpt andi response wil signal software ISR. belos 04, The condicion 1s) trap fention ‘nally {Yt exer ether athe enol etry of athe end ofthe calchfumevon eee, ‘S013 is used after the ty and eth functions fs, ten finally Tanction wil peo Pet "ask, for example, ext from the program or call anther function, if (UA = B) < 0.1) throw al; x= y + sort (A - BI; /* Find if A- Bis ‘A user program under execution cently bythe roesor does ot know when its ry function 100 | | y <0) throw a2; /* Find 1f y > 100. TE yes, throw ate asynchronous, peerage een eee 7 ISR call is evenc-bazed diversion fom the cue sequence of instton (oun or progr) to ‘another Sequence of insractons (omic or program). This sequence of instuctions exes tl de return instruction. 3 Bret an be vo srg ot caution! ova conpntin pion! canon eed : Ivrea hice iecrpin Anceacerh a eee iter inrsin Sein deve eae ee /* Code for action on throwing (trapping) A ~ 5 < 0.0 exception */ “An inter service mechanism exists in astm cal th ISRs from multiple sources (Section 44), [18) Embedded Systoms 5 Diversion to ESR. may o may not ake place on Finishing the execution of any instcton inthe presently unming route, The execution cI te (SRs canbe masked by an instruction ost 2 mask bit Trdcan be unmasked by anoter insuction to reset he wank bi. [Except afew item sources faled now mashable source Section 4.3) An insttion in a fancion program tread or ask an disable or enable an ISR cal of al IR calls (Section 4.43) 6. On an imerrpt cal the instructions do ot execute comiauoisly excl ike aC function o Java treed. These execute a per te intemupt mechanism ofthe system, For example, ‘return’ fom an ISR dfersincerain impart aspects interop mechanism maybe sch tha an ISR on beginning the execution may dis ateraialy oer devices tempt services. These are automaticly re tenable i they were enabled before a service eal. Another iagert mechanism maybe such tha an ISR on beginning the execution doesnt disable automatically other devie() interupt services and there cen be in-between diversion in the case ofthe Unmasked higher priority saterupts (Section 45.1). 1. There ean be mug inter cal dusing unin ofan ISR or version tebe ISR, The ISR calls red ot e the nesing ofthe IRs nie te case te fnctin calls and theres version to ending iar pity mere either atthe end or in-between the imtarupted ISR. Section 76 will expan th distinction between functions, ISRS and asks by hr characteristics. Interupt isan event from a device or harwvare action or software instruction. In response to the interrupt 2 presently cunning program is interrupted and a service routine executes. The routine i called ISR. It is also called device driver in case of interrupts from the devices ts ao called exception handler in cas of interups from the software. ISR-based approach facilitates an efficent synchronization of the fuetion calls and ISR-cals. The timings when an ISR executes are hardware or sofware interrupt event dependent “There is therefore no waiting period due to no need of device polling 4.2.3 Interrupt Service Threads as Second-Level Interrupt Handlers An ISR can be executed in two parts 1. One partis the short exection time taking service routine and canbe called as first-level ISR (FLISR). It uns the eral part the ISR and execute a signal function w enable the OS to schedule forrunning the remaining part Iter. It ean also senda message using a function o enable the OS tw nite a ask later cn afer return from he ISR, The ask waits during execution of interrupts routines an signal functions, The FFLISR does the device dependent handing oly. For example, it doesnot perform decryption of data receive from the network. IC simply Joes the tansfer of data othe memory buffer forthe device dat. 2. The second part isthe long service routine called interrupt service thread (IST) or second-level ISR (SLISR), which executes on the signa! ofthe first art The OS schedules the IST ss per its priority IST does the deviee-independnet handling IST is also the software inerupt tread as iis wiggered by an SWI (software interrupt instruction) forthe signal in FLISR. Figure 4.30) showed used of signal in ISR-FeameReod in digital camera system, Figure 4.5 shows how ADC scan is initiated by an SLISR call from FLISR. Figure 4.5 shows the FLISR and second-level IST “approach to handle the device hardware interrupts followed by software inteupts in upper part and the use of this approach in a camera in lower part. Inteupt service canbe done in two parts: a hardware device dependent code inthe FLISR, which has 3 short execution time and a software interup inated SLISR, which is also ealled IST. A task can alo be sent message by FLISR. The task rns after the IS. eve Ove an erin Sens Maan ws) ‘wertet sa 1 1ST Atread ¢ ara] Bem |r| So [fmt |e ee | Save byte | ‘Sa byte, [sus uae (mn a — [Gara Say rd] ‘ST AGCiead | ‘Gocont ee) 1. Sit ADC sean a et os pl in row and + Far 7) ara a erg Be tt ae 2 Sina abe eaa rare pl afr each ow read 1SAStan stewed |_| iomst and 2 eat sa i i 3 1h nen om as ow 7 ‘SW erupt on eae sina Fig. 4.5. Firstlevel interrupt service routine and second-level interrupt service thread approach to handle the device hardware interrupt. followed by the software interrupt to call 'SUISR-an IST and the use of ths approach in a camera 4.2.4 Device Driver Each device in a system needs device driver routines. An ISR relates toa device driver function. A device driver is a function used by a high-level language programmer and does the interaction with the device hardware and communicates data othe device, sends control commands to the device and rans te codes for reading the device dat. A programmer uses generic commands for the device driver for esing a device. The 8 provides these genetic commands, ‘The examples of generic functions used forthe commands tothe device are device create (), open (), ‘connect bin (), rad (), write) Toe () for 10 contol, delete ( and cose (). Device driver coe is iferentin differen OS, Same device may have diferent codes forte driver whenthe system isusing diferent OS, ‘A device driver function uses SW, which ntates the interupt service. The device uses the system and 10 ‘buses required forthe device service. Device driver canbe considered asa function in software layer ofan application program and the device. Por example, the application program sends the commands to write on dispy seten of a mobile the contact names from the contact database. LCD display device driver calls an SWI, and an ISR does that, ‘withou the application programmer knowing how does LCD device interac inthe system, what are the addresses which are used, what and where and how are the control (command) and status registers used Fora programme, using the device drive's generic functions fr reading o writing fom and tothe device fs analogous to reading or writing any other device or daa fle except thatthe device and file have diferent device identity numbers “The driver routine convolsa device without equicing uestanding ofthe device configuration, conto, status, data endothe registers, when using the genet fuction$" Device driver ras the ISRs ofthe device. Each ISR isthe low-level part ofthe device driver generic function, which executes on software interrupeinstuction, ‘The driver translates a program generic function for wing the device and sends the necessary commands to the device configuration and contol registers. The driver uses the device convo, status and data registers 200 Embeddos Systoms ‘Tre diver does the opening, configuring, initializing, attaching. reins we deve by imiiting the corespondingISRS. Drivers of many devices, such as printers, ouch seen, LCD displ, keypad. Keyboard, are part of the (5, Section 49 will describe device divers in deal t closing and detaching the Een device high-evel fanpage program ina system uses device driver functions. A programmer uses generic commands, creat (}open(), connect), bid (), read {write inet! () delete () and lose "and uses foreach device a device idemity number: Device driver executes the SWls, whch cal th [SRs focusing the device hardware and memory alloted to that. SWls ave dedicated fr the device service and pesform al the necessary scias DE 43 INTERRUPT SOURCES Harare sources can be fom internal devices or extemal peripherals, which interrupt the ongoing routine and thereby caus diversion to coesponding ISR. Software sources for interpre related to () processor eccting ("apping) computational enor for an illegal op-code during execution or (i) execution of an SL ‘mructon to cause processoriterrutof ongoing routine. ath ofthe interrupt scurces (when nt masked) (Or Sroups of interupt sources) demands temporary «ast of contol from the presently exccued routine 10 the ISR corresponding 1 the source. “The itera sources and devices differ in ferent processors or microcontollrs or devices and their ‘essons and families. Table 4.1 givesaclasiiation as hardware and software inlerrupts rom several suces. Natal the given types of sources inthe able may be present or enabled ina given system. Further, there ay be some other special types of Sources provided inthe system. Hardwore interrupts Related to Interna! Devices ‘Thee ae numberof hardware interrupt sources which can trrupt an ongoing program. These ae processor or microcontroller or internal device hardware geet An expe atardwarerelted interpt is timer overflow interrupt generated by the micocodtoller trate. Row 1 of Table 4. lists common internal devices imerapt ses. Hordwore Interrupts Related to External Devices - 1 There can be extemal hardwace iterupt source for interrupting an ongoing programm that also provides the ISR address or vector address (Section 44.1) or iaterupt-type information through the data bus. Row 2 of Table 4.1 lists these interop sources External hardware interrupts with [SR addresses information sent bythe devices themselves ‘Section 44.1) and are device hardware-specitc Example 4.7 An example of extemal hardvareelated interrupt with device sending the interrupt om INTR pin isthe ‘0x86 processor When INTR pin activates on an interrupt from the extemal devie, the processor issues two ees of acknowledgement in two clock cycles through the INTA interrupt acknowledgement) During the second cycle of acknowledgement, the external device sends the type of interrupt “ifoetion on data bus. Information i for one byte n. 80x86 internally signals instruction INT a, which means that itexecuesntemupt of typo, whese can he between O and 255. INT n causes the processor vecorng to adress Ox0000M x n, [SWI in 80x86 is denoted by INT] ove Devers an traps Senie Mechanism (a1) Hardware interrupts Related to External Devices ~2 Exel hace interrupts with tei ISR vector address (Section 44.1) are processor or miztoconller speci iniemints of an ongoing program, Exel interrupting source Joes not send interrupt or ISR addeew-relted information, An example of external hardware-eied intrrpt in which the interrupt information internally generates an ierTop on [NMI on: maskable inte pi in the B0n86 processor. Row 3 of Table 4.1 ts these ntrup soures. Table 4.1 Classification and Scurces of Interrupts! Sores Evanpler “Internal hardware device sources |, Piel pont 2 UART sil eciver po ~ [Noise Oeren Frame, IDLE, RDRFin SECII) 3 Synchroncuseciverbylecompleon 4 UART serial ansnit porransmisson complete fe TORE (ransmiter data register Emp) 5. Synchronous transmission of byte completed 6 ADC ‘tan of conversion: 7. ADC end of conversion: B.Pulse-accumlator overtiow: 9 Realtime clock ime-outs (Section 18) 10, Watchdog tier eet (Seeion 3.2), U- Timers overiows on time-out (Seton 3.6; 12. Tamer comparison with outpet compare resist 13. Timer expe ot input (Sexton 36) | INR in 8085 na 8086 Eternal hardware devices providing the ISR address or eolr addres ar type exenaly? Era ores deve with” 1. Noosa in [Min ER an E8652 Wii ee hk | lneral vector adiesegnetaion cycles lable gin trues pnb cherie askable | IRQ lin BHC 3 Mashable pin nes equ pi) NTR a NTL ‘8051. Qin 6SHCHIT Software errrrelaed sources, (exces! or SWeraps) | hin aman oy a:2 Ow byhaa: | 5. Undeow by hardware 4 ep oped by barre Software intructon-rtated sources Programmer deine excepins of tps for haning exception rine | (exception SMe SWpnl)codaansor engraving ISR wand eer | tions or pls rm een driver futon "paces enamplen in ae 2gxample 47 exp hs Ste proceso incmly generale a tp o exception, An example iin hy erin EO. Example 48 explains "he second type of exception the wer prgrn-fined exception, Example 4 expined ths. Sigal i em sometines aed in high feet peor for ofwareiteuptlsttion in Sey lange, For ex8 9 0 ‘VaWorks RTOS, [Refer Sesion 9. Signa o exception i a erat on he Sting of cern candies OF 08 ring en esis rl die rogaine sone son. The conn errs ae sure ete ber operant conputon rein in ales gee than 10% ran 10 cue ef Software Error-Related Hardware interrupts There can be the sotware-eor related iterups generated by processor hardware Each processor his a speifc instruction set. tis designed for that set only ‘An iifepal code (instruction in the software) is an instcuetion, which does not correspond i) 202) Embedded Systems CY to any instruction in this set, Whenever the processor fetches illegal code, a intereup oacurs i erin processors. The eror-elated interupts are also called hardvare-generated sfnswre sraps tr sofware fetceptions) Axoltware eco called trap or exception may generte i the processor hardwave fon illelor ‘ot-mplemented opcode found during execution, The examples are as follows: () There isan lle apcede trap in 68HCI. This error causes an interrupt to a vector address (Section 4.1) (i) Non-implememtable ‘opcode eo causes an interrupt to a vector ules in 80196. Software err exception or trap-related sources cause the interrupt ofan ongoing program computation in cztan processors. Examples ae the division by zero also known a ype O interupt is also generated by a software inerupt instruction IVT On 80x86) and overflow also known as type 2 interrupts itis sho generated by ne 2 instruction) in 80x86. These two inerupts, types O and 2 are generated by the hardware within the ALU ‘ofthe processor. Row 4of Table 4. iss thes interrupt sources. Example 48 explains asoftwaretelated ap or ‘exception, which san inerupt generated by Ue processor hardware on division by 0 Example 4.8 ‘Assume that division by 2ero occurs during execution of a certain instsuction ofa program. An ISR is needed which must execute whenever the division by zero cecurs. This ISR could bo splay A division by zero erat..." on the sercen and then terminate or pase the ongoing progr ‘A user program under execution curedy by the proestor does nt know when its ALU wil sue thisintemal esr flag a hardware signal). The service oun executes by sing un interupt mechanism which is meant for service ona zrt-division erorsignal.Onseting of the signal an intept of ‘the ongoing program happens jst after completing the eurent instution thas being execued and then the ISR executes for postero division task afer reseting the Nag Executing software ertor-clated processor interrupts are ceded to respond 10 errors such as division by 220 or illegal opcode, which is detected bythe processor hardware, These are called taps and sone time also called exceptions. These are essential for handling runtime erors detected by the system hardware. Software instruction-Related interrupts Sources program analso hile spec computational errors or runtime conditions o signalling some condition. For instance, Example 46 showed the handling of negative number square root SWI, whichis handled by SWI instruction inthe instruction set ofa processor. Processors provide for software irstruction() related to the aps, signa or exceptions 1 There ae certain software insructions for interrupting and then diverting tothe ISR also called the signal handler. These ae used for signalling (r switching) to another routine from an ongoing routine ‘or task or thread (Section 7.10). Figure 4.4(0) showed the signal generated by SW and sinal handling. 2, Software instructions are also used for tapping some run-time ertor conditions (called throwing ‘exceptions) and executing exceptional handlers on catching the exceptions (Example 46) Anexample of software interrupt isthe interrupt generated by a software instruction INT n inthe 80x86 processor or SWI in ARMT. Row 5 of Table 4.1 lists these interrupt sources, SWI instruction differs fom a function call instruction as follows. 1 Software interrupt in 68H is caused by insirution, SWI 2. There is ssingl mye instaction INTO in 80x86. It generates type O interrupt, which means thatthe interrupt should be generated withthe corresponding vector address 0x00000, Instead ofthe type O ierrupt that £086 and $0186 hardware may also generate ona division by zero, the instruction INTO oes exactly that. Device Drivers and interupis Service Mechanism 203 | 4. There is aber single byte SONG and AOXx66 instruction TYPES (corresponding vector addres (>< O9COHD. This generates a interrupt 3, called break point interrupt. This imsruction is ike 2 PAUSE instruction. PAUSE is temporary Mtoppage of running program. Itenahles program ‘do some housekoeping, and rtura the instruction after the break point by pressing any key. 4. There are another 80x86 1wo-byle instruction INT a, where a represents the type and is the sovond byt. Thismeans "generate type n interrupt and processor hardware ge the ISR ads by computing by the vector address 04004 x 0, When n = 1, ropresets single step tap in 8086 and Sis 5. There isanother 80x86 insrotion, which uses flag called tap and is denoted by TF This lg is athe FLAG regisior and EFLAG register of 8086 and 80x86, respectively, Tis means when TF ses (tien 1), automatically afer every inaction, the processor action cases an interupt of typeI repeatedly. The proceso fetches each time the ISR address from the vector address OOD (sane ype | interspt adr), INT | softwazeinstuction wil also cause type | interrupt ence but the TF Ta st instruction ation is identical to the action caused a he end of each insrution after type | intern 6, Theteinsruetion in 80196 call Trap. I enables debugging of instructions. Til the next instruction aller the Tra is executed no inert source can interrupt the process and cause diversion t IR. ‘SWeelated ets in the struction set help in programming the program diversion o {SR on exception, ‘The exceptional condition if occurs (ss) during execution, causes a diversion tothe ISR called exception haaler or signal handler using te software instruction for inerupt in the set ‘A programmer can program or the exception on a queue (a memory ule similar toa print hulfer geting {all This an exceptional eurtime contion should cause the diversion to routine called exception Mane function that nts the appropiate action. Exceptions are important routines foc handling the run-time em. Software imcucton-selted o¢ soliware-defined voodition-rlated software inteupts ate used in the ‘nied system. They ae essential ta design ISRs like ear-handing ISR, sofware imer-dnving ISR and signalling note routines to can, These interrupts ae als ealled traps or exceptions oF sal "4.4 INTERRUPT SERVICING (HANDLING) MECHANISM Each system has an iterupt servicing (handling) mechanism. The OS also provides for mechanism for imeruphanding Seton 8.7). 4.4.1 Interrupt Vector Inverupt veto is 4 memory address to which the processor vectors. The processor transfer the program counter tothe inlerupt vector new alress en an interrupt. Using this address, the processor services that iterupt by executing coresponding ISR, The memory adresses for vectoring by the processor are proceson- ‘or microvontzoller specific, Vectoring iss pr the provisions in intrrup-handling mechanism. The various mechanisms ie s follows Processor Vectoring to the ISR_ VECTADDR On an interug, a processor vectors toa new adress, ISR_VECTADDR.ttmeans thatthe PC program counter), which has the instruction address of next instruction, saves that address on stack oF in some CPU register, called link register and the processor loads ths ISR_VECTADDR into the PC. The stack pointer register of CPU provides the saved address to enable fetuin from the TSR using the stack, When the PC saves at th link regis it spat ofthe CPU register set, Section 4.6 will explain the mechanism for saving the CPU registers in detail The ISR last instruction i Rl (eta From interap) insirction (es Embeds Systems 204 A provides f In Following ways of using the ISR_VECTADDR-used ares processor provides for ene o he folle snechanism, ears caer the chip timer and A/D converter. In a given microcontroller, * Chnel vce merapt sauces seg sept BR VECIADDM als th Sonepat VECTADOR A cage Fe.) ISICVECTADR ras ert es Asi el nt 0 eer specif merce cr peceor wih hinds An inert n he Indes cer acts osltae tcl, frp IN explo dines he © pectin be pene eISR_VECTADER fie oR VECTADINS sh deen vcr ness ordre erp yes Tis mech esa he a mus of ection ing suns or SR omer pe (ER WEEROORT [~fromavoder TSRCVECTADDR 2[~ asec itn VECTADDR 3 | rset ora mo rer acnabet | fenton | ISRLVECHRODRS [io rng A | LISR.VECTADOR 6 JT Staring adaress ee Doves vector areoes of arapis | from ho hardware imp souces | a” a (inte |” Processor nds he SA wactor address | [SR_VECTADDAn | we eee eee st one Ts esa hander vector | == TF cmon vesor ats be So nqage Sheree ose ‘rade se wel a hanger paper aE ee ere, [Lacan || Seaton core ree ee 0 with diferent FB (0 R_WtHoDR horas erg oe) A YECHOOR th eet sector adres for dferntinterupt types sng INT ninstrton () The SR, rent with common vector sateses fr diferent exceptions, aps and signa sng iterrptintraction SM ” cn SWI des expt defi of In ARM prsesor act, thts incon SW * fei er ig eel oa te on VEC Cicurn optcts sgS ttn, IR tcc a eg interrupt Yector Table System software designer must provide for spec TBR THA IADDR adds. Th yes ae frit ISR short cde [Figite 40 or jugp istecnanteae ISR Fist insti Fetching the bytes fo finding the ISR aden Device Orvers and iterupts Service Mechanism |205 Tepe th exci caus ths pn ina ediver the program, Sacha mecha in raieepee antiecrerewtt npn ir heii une o ecpon anog win coe al ving the cn irra vader adds. Figures) shows he Sie Ve rAG with common veto ales fe et, sas al eal sealing om Sl A group of interrupt Sources having Common Vector Address &muce poupia te hardware may hve the sume ISR_VECTADDR Example 4.9 Fn any rata em and RI cer inerp) a he sources inte same group having iendeal ISR_VECTADDE 11 buler register for sats lain the dvi fg ester eal i the ISR that rus after vctoring, ISR_VECTADDR, TERME prcewor, which use II_VECTADDR diet a Sales and the pacer {ete he ISK suction fo th. for example, ARM or MSI ‘The ARM penal eee, eee ane an th ju othe EK inane forthe inemupt servicing). Figur yet he Ae OUISR, VECTADDR in ARM forth jmp to de mine for the iteeuph service, The gang rattler pons the we of sat SR of uv es fr the intemal devine, Te Fe yeh cal iscwction tll acta tine Figure 416) an shown the The, VECTADDA in 805 incase of shack and tng cide ISR apc (eens um ous which se ISK_VECTADDR indicts 1 airs ad the poser Free it ISK wires rom the byes seve at the ISR_VECTADDR, for came Soete, Ce {tay son th seo R_ VECTADDR aes in HG, Pose of into es Fares Ox > od etches 16 bits for sending int TP nstucton panes ete ‘tel aware 16 bis for sending inw CS (coe segment register) The ISR fi inlrop wll eence From addres Ox 110000 x CS + 1D. fying the bytes at each ur 4.70} or ESR strove with call othe Flea ofthe ISR [azure 476) or foe 4. NU5L Je le faites the service ofthe mute interaping soc foreach intemal device. ach row of Lables an (SR_VECTADDR andthe byte ae saved al each SR_VECTADDR. Veco ble ocaien de Bae neo Me pees: Ii eae the higher memery adress, URFPCD to USEF fe } Embedded Systems feos) mboded Sy [An extemal device may sso send tothe provssor the ISR. VECTADDR through the data bus (ow 2 sed ian, which asus & pes The neg vectors an npr pr one eve nea pov set Cae oe ese CPU orien en nave ssi Per auras peves ie TS or I ses o he peor oan ier sou os Ho tes cr er be gen inert ye The ep tre bsg pet f hepa seme sean, wissen be ye rvesonng othe spe erp sures a Sure rps ast [SR Si 1-1 Fon sve F-{ snr war }~Y Fr te commen ven etre || sess «anos sia bocce ae “sa | | Frmteepoyampows to | | verte twa x hn itt | |arenecomorwaot | | purseauradses scone sspwanes || Stns io at Shes —— Syston | Fomaveas c =o | Eire | riven trae Son Grecia a | pm a aces ST rarer ae two (65) byes at x€0004, andor toe Fig. 47 (a) Use of iSR_VECTADDR in ARM for the jump to the routine‘for ti interrupt servicing (b) Use of ISR VECTADDR in 8051 in case of short-code interrupt service routine (ISR) (6) Use of ISR_ VECTADDR in 8051 in case of long:code ISR (d) Use of ISR_ VECTADDR address in 80x86 processors i Device Divers and Interupis Service Mechanism eI abe TSR 1 addese TISA-VESTAOOR int ay TBR VECTADOA a2 esa nhardere ana sefivarentrpt Lookup tbl form adresses of ands er excapions. aps, and dovieIepts Fig. 4.8 Vector table in memory incase of multiple interrupt sources or source groups 4.4.2 Classification of All Interrupts as Non-Maskable and Maskable Interrupts “Maskable sources of interrupts provide for masking (diversion) and unmasking the interrup services {ehversion othe I8Rs). Execution of ISR for each device intereuptsoure or source group can be masked or snmasked. An extemal interrup request can also be make Execution ofa otareinterrup (rap eacepion Or signal ean aso be mesked. Most interrupt sources are maskable. A few specifi imerupts cannot be asked. A few specific interrupts can be declared non-mashable within few clock cycles of the processor ele thats mashable. There are three types uf inteerp sources ia sytem |. Nowmaskable: Examples are RAM patty error in a PC and error interrupts like division by 2r0 “These must be sevice, ‘Maskable: Maskable interrupts are those for which the service may be temporarily disabled to let high priory ISRS be execs frst uninerrptedly 8 Nommaskable ony when defined wo within few elockevelesaier ees Cerin processes tke 68HCUT ‘ths provision Fo example. external itetup pin, XIRQ interp. in GBHCT. XIRQ intemupt 's nom-naskable only when defined so within few clock cycles after GBH is ese, 4.4.3 Enabling (Unmasking) and Disabling (Masking) in Case of Maskable Interrupt Sources ‘There canbe imerrup conto bis in devices. There may be one bit EA (enable all), locale the primary-evel bis for enabling or disabling the complete interrupt system. When a routine or ISR is executed by the codes ina entical section, an instruction DI (asable interups) executed at the beginning of the ect section and ‘another instruction El (enable interrupts) is executed atthe end ofthe rial section. DI instretion ests the EA (enable al) bit amd ET insrction sets primary level bit denoted by EA (enable al). An example of cial section coe isa follows. Assume that an ISR transfers data tothe printer buf, which is common to dhe ‘multiple ISRs and fonetions. No other ISR of the function should transfer the daa tothe print buffer, else the bytes atthe bute will be rom malipl sources. Data shared by several ISR and routines nec tobe generated oF used by protecting its modiieaon by another ISR or routine. ‘There may be multiple bis denoted by Ey... Cfo source group of interrupts in ease of mile devices, These bits are called mask bits and are also called secondry-level bits for enabling ot eisabling specific soures or source-groupsin the system. By appropriate instrctions in he use software a writ the Drienary enable bit and secondary level enable bits (rth opposite of it, mask bis either al ot par ofthe ‘otal maskableiterupt sources are disabled, 208 Embedded Systems Example 4.10 Genser system i which there are two timers and eah ine has an interrupt cont bit, Timer iterupt ‘ont bits are ETO and ETI. Consider a system in which there san St device and interrupt contol bit 1S common serial ransmission and sei reception. Thee sao EA ito inter cant for disabling ainterups {When EA = 0. no imerupt is recognized sad timers as well 35 SI itereups service i disabled. When EA =, E11 =0, ETI = [and ES =, iterupts rom timer | and Stare enabled and timer (inert is sable (asked). 4.44 Status Register or Interrupt Pending Register A ilentification of & previously occurred interrupt from a soure is performed by one ofthe follwing: 1. A local-evel flag (bit) n'a status register. which can hak one o¢ ore sats Taps forthe one oF several th inesraptsoeres or grup of sures, 2. A pessor-interrupt serve pending fla ¢hoolean variable) in an intrupl pending regiter (IPR), that ses by the source (Sting by hardware and autoresets immediately by the intemal hardware ‘when a ater instant, the eoresponding source service sats diversion 1 te eoresponding ISR. sxample 4.14 i Sts bit TPO and TE. Conse a ‘Censer at system in which tere ate two timers aod each times has system in which teres St device there are he sits bts TSEMAPTY nel RsReay fo svi onpot snd roeiver data ready. Tins ISR_T? comtesponding to timer 1 deve reals he stains hl TFL = [in the status regi to Find thar timor 1 has eesflowe a soon the bi seal the TF resets 10 2. The [SR TO coresponding to iner device rea the stats bit TP =O inthe stu register to Find that timer has overTowea8 son as he bi sad vo TE ests 0, 1. The ISR corresponding (0 the SI device is common For te ansmiter ad the neiver. The ISR reads the status bits TXEMPTY and RxReady in the status ester to find whether a now byte isto e sett te ast ber or whthe he byl sw he read rom the ceiver bier AS sia athe bytes red the Rely resets ad ds Soon as the byt is writen nt the SI for transmission, TXEMPTY reset Same processor hardware provide for use of sau register Bits sind some IPR bit. The IPR and status registers dfler a6 follows. The satus register is readonly (i) A stats register Bi (an ietificaion fag) is ‘ead ondy ad eleared (autores) ring the red. An TPR bit eter cles (aue-resets an the service af the erresponding ISR or clear only by awrite nstuesion For resting the eomresponding it (i) An TPR bit can ke set by a waite instruction af well as by an inerupe occurence that waits forthe serve. A status register bit is set by the interuring source hardware oa. il) An IPR bit can eorespond to a pending Jntenupt from a group of iterupt sources, but identification Flags (bit) are separate Fr each source among the mutple interop. Properties ofthe interupt fags ae a follows, A separate Ng for every idenitication ofan occurrence Fromeach of the interrupt sources must exist The fig sets on occurrence of inerupt: i e's present ether in the iatral hardware circuit of processor or inthe IPR of iv the satus register (i ICs used fr a rad by Device Divers and items Serves Mectaisn {208} process oF stration tera wt by the intereypting sours hands. iy Herts Chom native as ‘wu itis rd. This is atest characteristic provided in most hanwatedesins in ord wo enable thi flag t cae the next settee fom same int rupt source (iv) H settee des not movessaiy mean ‘hat it will be rexgnized and serviced Iter using an ISK. Whe a mask hit comesponding to that iteript set even ifthe Hag es the processor may ignore unless the mask (ar enable) bit mois later This makes it pensble Wo preven an unsanted interupt fom beng sevice. Example 4.12 Consider a touch sereen 1 generates an interrupt when a seen positon is touched. A statu bit b, i ako set ft activates & intersupt request (IRQ), Foon the tas bit, which Set the imteruptng sours is ecwanized among the sources grup trlile sources of interupts Fear same devi un Ucviges. The ISR VECTOR ug an SR jy are common forall he inerupts IRQ. - a IRQ results in processor vectorng to an ISR_VECTOR jg, Using ISR_VECTOR gq when the ISR, sag: Using SR ag when the ISR stots, ISR instruction reads the staus register and discovers tut bit a set, I cals for service funetion (se tovc_pesition) which eas regis, or touched screen poston iakmation. This sction of rang ako ests tb ifthe wuch seen controller processing clement provides for ‘autoresting of This enables next IRQ inerupt and thus eading next position on next touch, 4.5 MULTIPLE INTERRUPTS 4.5.1 Multiple interrupt Calis si oy heats exer anc Seon Po na aes ISR is to lower priority pending ISR, a Leta nein wo proosor erupt eve mechani fe the ceo i 1 Catan pesos do nox pois ben une ent ay ps nd prea mesons of roy pcan pen as rg ee ithe ea fhe, gue 8a) shoe cern highs ply ent nada Epes nee Cerio proce eit tetwcn rine Seon lighr pry inert, Figure 446) sows fe sos sh pensar Tse perso poe ron sen inbetween a thanimas lon: Tee peng farang ames fe sone level it These proceso provision sekctve dvenion by povning fo muting he acme scvke sect by sonia vel ia Salon 4) 4.5.2 Hardware Assigned Priorities ‘Thi is signe priority order by hardware. ARMT provides fortwo types of exemal interrupt sources request) IRQs and F1Qs (fast interupt requests). 8051 provides for rity order inorder of inter vctor adresses, Lower address has highest and higher has te lower privity. Inerups i 80386 are asigned priority onder sccording to nteopttypes.Interrpt of type O fas highest priory and 255 hes lowest assigned prio Emoodded Systems 210 Shanes tinea ‘Stas actin 2+ oly i i (SA should be a || * | er Sane Processor | ISAs to get attention tas. ~SFieres aoe gh ony tort ove "e (tur at ater Sioned ata ‘Stas ater ties + cen sen wre | I |e | eae IGE get atenon fst. Pies at tire Resuros atte ® fig49_()Dversontohiherpxtinerpsath ne 7 ‘only (b) In-between routine diversion to higher priority interrupts unless all interrupt: aaa ony reer thn te present mening rou ae masked the multiple devices the processor harbwate asisns 10 i: level or pel. Let ws op Lt be number mt was ta ere pers re Ser ae A cceorexpending othe IRs can oly be dane in a eran ce of pin, Tere is Seer fet oceans pe Mero “haho® Sore pts erp Scr 4 wip in ‘Consider the example of the 80x86 famiy processor. Consider its sx interupt sources: sony 0. ia a eran noir se) ek yr vel pit Sn ep, Gon asa i ND nnd epee The ae Senet yon Ty nen nn aa pene wave o teak pm he end af each inanuton whenever 2 debwesing ier bes of te ee len nr eon. 4 ‘eater be bes pay Which isthe Interrupt to be Serviced First among those Pending? Some Way of Polling Resolves this Question. The 8086 has a ‘Vectored Purity Polling Method’ A process intemupt mechanism may intealy rovie for the numberof vectors, [SR_VECTADDRs. The vectored riony” method means thatthe interrupt mechanism assigns th SR_VECTADDR as well Pu- There 68 DDovice Drivers and itorupts Servce Mechanism au call a the end ofeach nsiucton eet oe he tur roman ISR) Fo ahighest peor sous tenable and pending. Veco pigs in MOK are a per the «FE (2255) lowest privity spe Pe O Rh! PO AM! Py ‘When there are mole device crivers, traps exceptions and signals a a result of hardware and oftware interspts the assignment of prions for each sausce vr source group is required 80 thatthe [SRS of smaller deadline execute ear by assigning them higher priorities, Handware-defined pois ane used 8 defaul. Software assigned priones overide these priorities, for example. in 805 “4.6 CONTEXT AND THE PERIODS FOR CONTEXT SWITCHING, INTERRUPT LATENCY AND DEADLINE Getting a ares (pointer foo where the He Function begins, loading tha address oto the PC and then executing the called function's insicions will change a running function a the CPU to another Betore ‘execuing new insrutons ofthe ne Funetio the processor or dhe OS also saves the Curent progran' satis word, registers and program contexts aot done automatically by the processor or the OS. then the new Funetions instruction shoul do hat, This is because these (stats Word and registers) muy be nceed bythe newly called fonction, CPU regiversiaclading processor sats word, register. sack poimer al pragrany ‘ure ales ne PC clefine a faetons context Figure 410) shows a curent program eootext. What Should exactly constitute the context? It depends on the processor athe operating system supervising the program. “The content must save’ Fenction proyran oc oun ei eartier hast un again Fm the sate which was left. When there isi cl a lunetion (alld eine in assembly language fncian ia Cand C+ meted in Sava also called task wr prowess or thei when it uns under stpersison ofthe OS}. the funtion or ISR or xceprion-SuanlingFantion executes by three main steps. 1. Saving all he CPU resisters inlaing processor las Word, risers neti’ cet ads {or next mst in the PC. Sang the addres ofthe PC ont a sack is roguied if thee sm Fink reaisier to pitt the PC ofl iasiuetion of eater fuetion. Saving facilitates the retam fy the nw Function 4 the previous state 2, Lindl now omen 0 itch oa nee futon. 3. Readjust the contents of stack pointer and execute the new function. ‘These three actions are Known 3s sale? suiching. Figure 410(6) show a curent program’ context sitching to the new contest “The last instruction faction) of any routine o function i always a en. Te following steps ovcur during return fo the elle inet, 1. Before ret, retrieve the previously saved stats word, registers and other context parameters 2. Reiove into the PC he saved PC adres) from the stack o ink register and ood other part of saved {gotext fom sack and readjust the contents of stack pointer. 3. Execute the remaining art of the function, which clled the new function. These thre uctions ee also known as content switching. ‘Wecan say that on interrupt o funtion call and retum ie context switches and anew program is executed whenever the nes corat loads into the processor CPU registers. Figure 4.10(2) and () shows context, ‘Switching for new routine nd another context switch on return or on in-between call another routine [Nesting means one function calling the second which in tur calls the third and s0 on andthe setura tothe calling functions wil be in the reverse order. In case of function calls there is resting and inthe case of ‘mukiple ISRs because ofthe presence of multiple inerupts there may or may not no nesting Gs —— [caer PC Progen coueerh Context [8 kp / Seong (CPU regis 1 Save current function oF ISA context an stack | Pree stas rege | Gratcadnoe tetencrSA cowed o a —, (7 Sern awasing for ow ine Bepsonamairatrrew eure] ‘Swiding 1 Savane sion cack nd nai coe 2 eonierw areas = ‘ra save vow ouine coron ad Sich or Re pov 3} toute by retin fe sivedcotet Eat a e serine Storsaterinet+tweer's 7 Sate atarime + ware cortex sich tr qe swine ere tc For Lf Higher progam | rent 158 7eranceg ts conta Sein 21 @ recutes with the new context ofthe Fig-410 (0) Curent prouram context (2) New program execs He * called function or routine {c} Context switching for new routine and another ste taavatrs ton routine a) Content sthing for new routine and another svitch on fet rin between the alto another routine jpted routine (or Futon) and then werieving OF net switching mans saving the content ofthe ine een le shows how the context switching takes place in Jeang the new context ofthe caled routine. Example 4 the ARM processor Example 4.13 Comes svtching a fllows inthe ARM rcssor o 5 call () The iota mask (ble) Mags re SaMbaanl pry inept) (i) Nes suction PCs aed a ink rege ii Care progr “Soi (CPST) copes it te seed rogras seiter(SPSR) and CPSR ies te esas ‘Erngse nteons G) gete ve vale aspera sous fn he vor [Str comex swig no the evo cont fl () PC reve lo {Spc i) The corespnding SPSR copies bck inthe CPSR i) The inept mask (se) epareexet (Embeogain the care ded low pity inerps) One Den evi (xs “The time taken ia vontext switching. Ty hs ho be incl Ty. Example 4.14 shows how to eae the camer siitci calealating the interrupt latency (Seton 4.5.11 in. pio ealed nev ene pt tin Lime peril. which is 1 be eve Example 4.14 |. ARM7 processor contest switching’ minimum: period equals wo clack eyeles plus 0-20 clock {eyeles for finishing an ongoing instreton plas0-3 cycles for aborting the data, The Ocyce when in Ioterrupe occurs ust before the end and 3-20 when during an inswuction. Longest time taken for an ‘ARM insiueton is 20 cycles. 2. During context switching for new routine cal for rea. CPSR copies ita SPSR on switching from a routine. CPSK means current program status register and SPSR. means saved program status reise, 3 cycles ae taken in switching the CPSR 4. Two clock eycles are needed for the start oF the execution stage of switched routine’s first Abontng the processor data means CPSR nat cpg ino an SPSR, Then sep 2 thee cycles are taken up. |. Minimum pesiod is thus Four (2 +2 foc dat abort interrupt. [Steps land 2 above] 2. Maximum is 27 clock eycles (2420 +3-+2)forthe than data abort iaterup. Maximum is when the interrupt occurs just atthe stat ol exceution of the longest tine taking instruction in the proces. [Sten 1,2 and 3 shove ‘Tins for any latency period calculation. 27 clock cycle periods 3s context switching time ae ‘akeo ilo account wien estimating latency in an ARMbased system, Each rning program has a contest ata instant. Comtex fleets CPU sate (PC, sick pointer registers and proga state (variables that shoul ao be modified by anode routine). Context swing on the call of another ISR ce ask oreo 4.6.1 Interrupt Latency ‘When an inerrptexcurs the sevie of th ones swing The tral ween the acu of nip sk of exec called inert latency 1, When he ntrtupt service started on coe itching he inert ey Ta the contest swiching period. When isan pros take Wale lok ees aia Teck eels fran isteton ae taken ino acu fo clelting the ene Figure 4.1) sw Iateney in ease the itemap seve stars imei. 2, Wh the intrap service dacs st ine hut conte swibing start ar he ESR comtesponding the hiser prot iterups complet the execution. het of ie interval for completing the bighor priority ISRS uals Pg the iment leney e338 Tay 4 Fle Fur 411() shows latency in expe he inept servic stats afer presen ISR o ihe pity imerpt completes the execution oa 2. Weedisablethe inemupt system whet routine eter acral econ and enable the neaps Wh the routine exits the eral ston des. rote of faction or ISR may consist of codes fr etal ‘esion istrtins an bef thera scan codes the inerrps ar abled and enabled bythe ay Hot Sia nmedately by ofthe ISR is lau) Embedded Systems ins) ewer x appre ‘ors cme ney sum Oe pono Tony BT aT auc when the som s Tor the iaterupts an When the interrupts ofthe highest priotity. For latency computations, worst eve is taken ino acount Stasi tr nl where's costes switch eve 5 FF trp atncy 21 oy wheres Content st tne fr ann he Processor isa iterpt at ‘unnng program cto an [inemuptat w} |__| Sadi he rw route contest @ Stas ater vere e+ ¢0 Stated at imo te whe scot se ine { “| ML ntesrupt latency = t= tg + U where = eee Seo eral Loony ant ot Phat ‘ets at ater > 4 r 7] rete Tas» Tse Te | saving th nrg earam content and {Gad the nom outs cote Tj isa ET honeaseten | | tetten tn emanea Setia ‘ea ime Init pt rd a te fens Taso) | terhigh ploy rou exec @ Fig. 4.11 (a) Latency incase the interrupt service starts immediately (6 Latency incase the interrupt service starts only aftr the interrupt service routine presently running completes execution {chinterrupt latency 2s sum ofthe periods for Typ PTaec 394 Tate When the presently ‘unning low priority routine to be interrupted is having rtical section codes Example 4.15 £30196 microcontroller has an St device which has FIBO (first in first on) Effer and the ST reads the tytes and pus it in the buffer St generates thre imerups: RI on one byte reception, FIFO_4*Entry ‘terug when FIFO shal land FIFO_Fllitecrpt when the FIFOs full Assume that mierocontoler fas two devices: SI similar to 80196 and Gime T. ST}as a serial input buffer of8 bytes (a FIFO of 8 bytes Davie rer ad erupts Seve Mectarsm {ass} (0-1, Assume tht a serial input at the SI reads a byte from a network and generates tree types of Interrupts, T generates time-overflow and tmer-captureincrupts, called TF and TCAPTURE interop ‘Worst-case interrupt latencies are 2 follows: 1. When the seventh byte is received the controler generate inlerupt FIFO_FULL anda FIFO_FULL Nag sets in 0. Assume that it isthe top priory sera interrupt nd the ISR execution time is Tr (FIPO_FULL), For the FIFO_FULL interrupt, the interrupt tency is Tac, + Tune Because ito top priority ISR, 2. When the zeroth byte i received, the SI generates am interrupt RI and an RI flag, esi the stats register SO. Assume RI as the lowest priority sal interrupt and RE ISR execution time is Try (RI, Fr the RE interrupt, the interupt Tatency iS Trajey + Tong (TCAPTURE) + Tye CTF) + Thus because it has the lowes privity than the timer interrupts 3. When the third byt is received, the St generates an interupeFIFO_4*€Entry and FIFO _Hal ag sets in SO. Assume that she middle riot serial interrupt snd has prioites ower than the TCAPTURE imerroptbut higher than the timer overtiow. Assume that Ue ISR execution imei, FIFO. al For FIFO_4°E try interrupt, he interrupt aty is Tyg Toye (TCAPTURE) + Tro, because ithas higher priority han timer overfiw but thas lower pronty tht TCAPTURE. The To. (Ri) isnot taken into account because if RI is nt responded then only FIFO. Half interupe ‘occurs. Both interups Rand FIFO. Half belong othe same SI device, Each running program when itrrpts, the interrpting source service routine akes some tine before tating the servicing codes. That ie interval is called interrupt latency. [tthe sum ofthe crecuion time of higher privity interupes and the context switching pio, IF an nterraped routine is having criti setion ‘interrupts dsabled), the iter tency increases by period equa othe intemupts dab pei. 4.6.2 Interrupt Service Deadline Forevery source, the service ofits ISR instuetions an be kept pending up toa aximum perio. This psiod Uefines the deadline Juring which the service must be completed. It should nct be less thn the worttexe interrupt latency, Figure 4.12(a) shows iterupt lateney peri and deedline for an iterupt ‘A 16-bit timer device on overflow rises TF interrupt on transition of counts from Ox FFF to Ox0000. It has tobe responded by execating an ISR for TF before te neat overflow ofthe imer occur ese the counting petiod between 030000 alter overflow and Ox0000 after the next-to-next overflow will nt be accounted. The ‘imer coun increment every 1s; the interrupt service dealin is 65536. Video frames in video conferencing reach after every 1 +158, The device on getting the frame interes the system and the interrupt service deadline is I 15x ele the next fare wil be missed Example 4.15 FIFO_Full interrupt must be exeeued fast as thas shorter deadline compared with RI and the fourth entyinterupt IF1SR for FIFO. Ful imesrupt does ot execute before the next character athe SI device, the character will be missed. 1 1SR for FIFO_4* entry interrupt does not execute fast it does ot ‘matter, because eventually theresa cushion of SI raising the FIPO Full interup,IFISR for RI inept does ot execute fast, it does nt mater, because eventually there i cushion ofS aging FzEO_ 4° entry imterpt 8s well as FIFO_Ful interrupt, FIFO_ Full inerrupt is sui to havea service inept service dealing I ‘device is receiving characters a 64 kbps and in 1!-bt UART format, he FIFO_Fll interop service deadline is 171.9 ts, FIFO_R1inerupt serve deadline is 171s Sl device doesnot have the buffer and provisions for FIFO_Half and FIFO (ul iterups Embedded Syatens 26 en eh eg er es one Zea ine claware [| ee, | eran imeem A t fusion atte . @ ‘ames sich ive Comet sch be Coron sw ie r ror toy «shat Now, [becca dado 8 ow sre eel Pant meseeT Must staat tine +g, 442 (a) interrupt latency period and deadtine for an interrupt (6) Short interrupt service routines (ISR) and functions, which run at later instances so that the other ISR deadlines are not missed the ISI as short as ose A gona solar design principle For multiple interrupt sounces is 10 be Wig? Mis is service the in-between pending iterupts and eave the Fanetonsthat canbe executed afterwards fir later time. When this principle is not adhered to, a specific inlerupting source may not be serviced vith the deadline (maxinuim permissible pending tie). Section 4.2.3 deseribed use of inkenuptserview iecaal, hich re te second-level interaphalers Figure 12h) shows short IS and Tanetons, which oa ater nstances so thatthe other ISR deadlines ae Wot missed ‘Thesysem horetee has to meet the deadlines se for service o eueh sytem device. Ths ean he understod by the Following examples. Consider the example of vdeo system. When the system i uning. evo devi Ariver ISRS also run. One divers for the woe dove athe other for the image deviee. The ISRS and the ther sytem soltwane design for these wo devi drivers ve to ntin synchronization else the next se ‘nf mages andthe nex se of woiee signals wil be missed. “Therline, the system sole designer designs the appropriate ISRs for muliple deve iaepts so that all device interop calls are serviced within the stipulated deadlines of each terse. The design shout ‘provide optimum latencies and set appropiate dlines For eet service routine and fanctions, Each SR may have ntemupt sevice deadline when itrrups. An SR with deadline must have interupt lateny fess than the deadline 4.6.3 Sofeware Over-riding of Haraware Priorities to Nieet Service Deadlines Which source or source group bas higher priority with respect wo the others that i fst decided among ine ISRs that have been assigned higher priority in the user software, I wsersssigned prioites ave equal then the highest priority is that.whiciis preassigned atthe pracessor internal hardware. The 8051 internal interupt mechanism is as follows, There isthe interupt priority (IP) ceyister at 8051 in which there ae five priority bits for the five interupt sources in 8051. Also there are the five interuptenable bits in the HE register. These are secondary-level enable bits of the processor's serve of ISR. When a Device Drivers and Inerupts Senvce Mechanism Prot it a HP et the corresponding interrupt source ges high privity. and if reset. Priority The 8HS1 fit sees by poling among the high pity acing to the its at TP ve here ss nee for averring the privity order by assigning priwties. The ad oF teassigning priorities lore hardware pesigned priorities eam be undersea ft te Following exarple Exampie 4.16 Assume that there are ta soures of nterupts: serial pod input and A/D conversion. A/D conversion time 200 ps und SI deve wit no data buffer eeiving inputs 64 kbs with minim sepration between the ‘character uals 1719 us. The A/D conversion should therefore hve the lower priority than Rt intempo Sl, When the system hardware has the intemal devies, it assigns lower prioity to the A/D end of the ‘conversion itera. Suppose thatthe SI device i used to receive input at 16 kp and assume thi the LUARCT mods has 11 bits pereharter When the AID conversion is neded euninuousy ep, when ECG sigs ur inpud, the sltware should sign the higher priority 1 A/D, boca St receives character every 11/16 ms = 687 ys and AJD every 200 ps, arate Faster than the SI Software-assigned priorities can be used to over-ride the hardware priorities. OS provides the Funston, hich assign the software priorities co each ISR, IST and task ofthe real-time sytem, 4.7 “CLASSIFICATION OF PROCESSORS INTERRUPT SERVICE MECHANISM FROM CONTEXT-SAVING ANGLE 1. The S051 interrupt service macnn is such that on occurrence of an inert service the processor pants the proces registers PCH (program counter higher byte) and PCL pmgram eounter lower tytel oro the memory sack. The IST fail processors dom sve he context of the program her thao te absoetely essen PC) and a votes cn sive only by using the ype se onsets in {he called rote. For example, using push insrutons. speed ip the start o IR. an vera fom ISK ut ot a et. Te om of eontat saving othe programme in ae the conten (SP and CPU feginors ether thn PCL and PCH) isto be mdified on service oon funtion alls during exection of the remaining IR insvetons, 2. The éXHCHT interrupt me iy such that procesor registers save onto the slack whencver un imerup sevice occurs. These rin the order of PCL, PCH, TY, IVH.IXL. KH. ACCA, ACC. and CCR. The 68HCH thus does automatically save the processor context of the program without being so instructed in the wer program. As context saving ies prcessr time, It slows aie {he tart of SR ed rerum rom thei Buta the great atvantage thatthe nus of context saving isnot en the programmer and thesis mo skin ease he context modifi on service or funtion cll 3. Certain processor proves for fast context switching two stack rams with each tack frame consisting of the same number of resisters, for example, 16 of 32 registers. The PC. sack-poiner and link-tegivter define one stack frame. When context switches from one routine to another only the pointer to the stack frame changes. The IS sack frame tat f aed has the curent program context und the inernpted program context becomes the saved program context. ARM? provides such 2 mechanism. Certain processor provide for moce tan wo stack frames with each stacking a context ‘The OS program also provides for memory blocks, which are used as multiple stack frames forthe tasks (oroceses or treads). Ths enables mul shveading and aitsking Embedded Systems ‘Cena processors provide for saving only the PC, Certain processors provid for saving wy the PC and tther CPU registers belore calling the ISR and context switching, Certain proceswrs provide fo fas. context stitching by providing itenal register frames fr the stack or proving sets of cal Cntemal Sick forthe contexts, Fast context switching reduces the interrupt latencies and enables the mecting of ach fiction of routine dealin fr service, The operating system provides Tur multiple stack raves to tenable muliisking and context switching using the mubple tack frames ~ 4.8 “DIRECT MEMORY ACCESS: ‘Assume that the data transfer i o occur beeen hard disk system memory. The DMA is used in that cae ‘When the /0s are need for large amount data from a peripheral device tothe memory kes in the system or large amon of datas tobe transferred by the VOs, the interupt based mechanism is not suitable "A DMA facilites mult-byte dataset ora burst of data or a block of data transfer heen the external device and syste or between two systems. A device tha facilites DMA transfer has a processing element (single purpose processor). The device is called DMAC (DMA Controller). Data transfer occurs etfvintly between he VO devices and system memory with the least processor intervention when using DMAC. The system address data buses become unavailable o processor andavaiable othe 10 device that interconnects thing DMAC during the data transfer. Figure 4.13 shows the intereonnectoas using the PMAC. Ital shows the buses and contol signals between the processor, meme, DMAC and data-transering UO device PROCESSOR From decoder OW for OMA pean biac DAA east Adnowicige 1 From Decoder Por Set System uses no sccese by processor inmates ad data buses curing ckrowodge active Fig. 4.13 The buses and control signals betweensshe processor, memory, DMA controller and OSsoftware is required for using any device in a simple or sophisticated application(s). > Certain software instructions are required according to the given processor, memory and device hardware and as per the system interrupt servicing mechanism. Programming is the most essential part of any embedded system design. Except for certain processor and memory- sensitive instructions where program codes may be, ittxn in assembly, most of the codes are written in a high level- language. Qos Gm ea Fw nade earning of the programming language, a eer sould refer ute sandant reibonks and da required practice exercises; We will learn basic of prngraming the factions methods) and concep of objeteniemed progranoning with reference building sefrcare forthe embedded ystems. OS cineeps, we wil earn later The fltosing are the topes tha will Be deussed inthe chapner 1. Programming in the assembly langue vs, high-level lange and the powerfal ures of for embedded seems, 2. Program elements: Preprocessor directives an the header les, acute les td sonrce files that ave sed in progr for an application Program elements; Macros and functions and thee axer ma C pram 4. Prograim elements: Datatypes. pointers. deta siructunes.arrens. queues stacks, tists ad res, malifiers, conditional staterens and lop 5. Program elements: Function calls, matole functions, function pointers, finan quetes and service-ratine quenes, 6. Object-oriented Programming concepts embedded programming in CIC. use el PME Program mols for building the sofware wil be deat within Chapter 6, Conc fof the processes. ess, tveads and the concepts of interpecesssanclinoiaton i Je covered Chaper 7 and ef RTOSes in Cher 8, Peynor RTOS ere deseribed jn Chapters Yad 10, 5.1. SOFTWARE PROGRAMM 5.1.3 Assembly Language Programming Axserbiy langue eading of an application has he flowing advaitages 1. The assembly codes are sentive tothe proceso, menvr. ports and devies hardware. 1 gives a prevse commal of the processor internal devices and complete use of the processor-specifi features in its instrcton set sds audressing modes, tachine codes are campac,provestr- and miemory-sensitive, This is because the codes for declaring the conditions, rules and dat type do nat exist The system thus needs smaller memory. Excess memory needed docs ‘not depend on the programmer datatype selection and rule declarations, The ‘program is also not compiler specific and libry functions dependent. 3. Device driver codes may need only few asembyinstracton Fo example, considera small embedded syxem. a ier device in a microwave oven or f automatic washing machine or an automate choclate-vending machine, Assembly code fr these can be compact and preci. ars conveniently witen, 4. We use hotiom-grdesign approach Is am approach in which programming fist done for the sub ‘nodules of the specific and dinint sets of ations. Aa example of the modules for specific sets of sctions isa progrum fora software timer, RTCSWT: run inel-tine clock software tine function ‘ru. Programs for dla. counting, Finding tine intervals and many applications can be writen, Then {he final program is designed. The apprach to this way oF designing & program is to fist code the basie functional madutes ad then ue hese to build a bigger med. 0 Java 237 Programming Goncepis and Embedkied Programming in, Co 3. High-level program faiuaes "ye checking’ making the program less prone ero. For example 'ype cecking does oc permit subractian, muhiplication and vison on the car datatypes. Hye ‘plus operator tobe use for concatenation when using char datatypes ad lets the ‘lus: operator bbewse for arithmetic addition when using in snsigned int, shart and long type of dats Cancanat ‘operation cin be understood is follows: the micro pls controller concaentes int the mucocele ‘where micro isan aray of char values and controle is another amy of car values) 4. High level program facittatesuse of contol sructares (2, while, dr-eile, beck and for) and conten Statements (eI else, esa switch eae) specity the program flow by simple slatemext. 5. High-level program has portability of non-pucessor specifi codes. Tetefoe. when the hardware changes ony the modules forthe ISRS of device drivers and device manageiment inilizatin snc 5.1.2 High-level Language Programming High evel language coding of source files in C or C++ oF Java has grea advantages and therefore most ‘programming + in high-level language. Basie advantages areas follows: program-lcator modules and intl boot-up record data need modifications ‘Aditiona advantages of Casa high-eve! languages are as follows. isa language between lowassemhls and high-level languages. Inserting the asembly language codes in-between is called inline assembly. A ect hardware control i tus also feasible by in-line assembly, and the complex par ofthe progr can be 1. High-level program developmen excl is short even far complex systems because ofthe followings: Use of routines (called functions in C/C++ and methods in Java), standard library functions. wse of ‘modular programming approach, top-down design or object-oriented design approach. Application Programs are structed (0 ensure thatthe software i based on sound software engineering principles and programmed with te given OS ile systems, device and etwork driven (@) A function defines a method of operation. and sets of statements and commands are run when that Faction is call (b) Library function are stnderd functions, which are readily available to a programmer and the codes for them are not defined by programmer For example, square root method of operation, The use ofthe standard brary fswrion, square roo (), saves the programmer tne fr eosin, New set of libary funetions exis ina enbedled system-speifie Cor C+4 compiler Exemplary "ibrar fumedins are delay «wait (and sleep ¢, luxntcal devices such assera-ine device (UART) are usedinanunber of embedded systems, Directly Progamming Hse func in each system will mean the repetie andesdanelat exlng for each evi Its beter to wse the device rivers ia high-level language, which we the unctions specified in {he OS. The programme simpy specifies device 1D nd some uf the function argumnenis passed tthe tevice diver function when needed and ue iat aot instance ofthe dvi ‘Modular programing anpeceh san sppeoach in which the building blocks are usable oftware ‘component. A module is built by sofware components, The components art built by a set of functions Considan analogy tan IC (ntegratedincuit) ust asan IC has several circuits inegated ita one. similarly a module buiding block may call several fonctions and library fancions. A ‘module is then well ese fora well-defined goal an forthe well defined data input and outputs. I should have only one cating method. Thre should be one eetum point rom it It should not fet any daa other than the one operates this means that tre shouldbe dats encapsulation, fe must rolur (report) err conditions encountered during its execution, Tope design is another programing approach in which the main program is fst designed, then its modules, submodule, a finaly, the functions 2. High-level program aciiaes daa pe declarations Daa type declarations provide programming ease For example, there are four types of ints. int, unsigned int, short and Tong. When dealing with positive only vals, we declare a variable as unsigned in, For example, numTicks (numberof iks toa ‘lock has to be unsigned. We need signed integer, nr (32 bis) in arithmetical calculations, An inieger can also be declared as datatype. sho (16 bis) on (64 bs). To manipulate the text and strings fora character, another datatype is char. Each date type isan absriction forthe methods, which are per- ‘mined for using, manipudaing, representing and for defeing ast of permissible peraons on tet data ic cl © in high-level language High-level Language programming makes the program development cycle short enables use ofthe nodular programming approach and allows us to follow sound software engineering prinipes. It facilitates the [rogram development with top-down design approaches. Embedded system programmers have since ln refered C forthe following reasons: it The Feature of embedding assembly ees using inline assembly Ci) Readily available modules in C compiles forthe embedded system and ibrry ees that can diet Por into the system-programmer codes ~ 5.2 “CPROGRAM ELEMENTS: HEADER AND SOURCE FILES ‘AND PREPROCESSOR DIRECTIVES AC program has following structural elements |. Preprocessor declarations. defintons and saterents 2. Main function, 3. Functions. exceptions and ISR. AC program has the following preprocessor structural element 1 Include directive fo he file inclusion, 2. Definitions for preprocessor global variables (global means throughout the program mou) 3. Definition of const 44. Declarations for global dats type, type declaration and data structures, macros an functions ‘The program elements, header and source files and preprocessor directives are explained i the following subsections 5.2.1. Include Directive for the Inclusion of Files “Any C program firs ncudes the ead ad sure files that rere valle, A case study of sending 2 stam bytes hough a network diver cal sing a TCPRP protocols given in Example 113. ts program stats withthe codes given in Example 5. The purpose ofeach included files mentioned inthe comments within he and "symbol as per the practice in C. 238) Embedded Systems Example 5.1 ' ' + include *VxHlorks.h* /* tnchads VeWorks faetions'/ Include *semLib.h /* clude Semaphore functions Library *% include “taskLib.h* (Include mulitaking functions Library *7 include “megQLip.h* Include Messize Queve Functions Library *7 include “fiobib.h* /* Inlude File-DeviceInput-Oulput functions Library */ include “sysbib.c* Include stem Hisar for sytem functions */ include “netDrvConfig. txt” (* Include a text file that provides the ‘Network Driver Configuration’ It proves the frame format protocol (SLIP or PPP or themed) description, card escrption/make, address atthe system, IP address (s) of the node (5) that drive the card for ‘eansmiting or ceiving Iror the network. include “pretiMandlers.c* / Include ile forthe codes for handing and actions as per the network layer-protocols used for diving steams othe network. */ cde i «preprocessor directive to include the contents (codes or data) ofa fle. The files that can be Joded are given next, Inclusion of al files and specific header Files as to be as per the requirements Including code filer: These ste the fies tor the codes slcady available. For example, # include ‘pears. Including constant dat ils: These ar the fies for the codes and may have the extension “const Including strings data files. These are Ue les fr the strings and may have the extension “stings oF Ste" or xt, For example # include ‘nerDrvConfigat 44. deluding iit de files: There are ies for the intial default data for the shadow ROM of the ‘embedded system. The boot-up prograt copied ler into the RAM and may have the extension ‘nit’. On the other hand, RAM data files have the extension, “data 5. Including basic variable ies: These are the ies fo the local or sloba static variables that ae stored inthe RAM beccuse they 40 ot possess the inal (elt) values, The static mans that there is 2 ‘common not moe than oneinstance otha variable address and it has state memory allocation, For ‘example. system has i nly one realtime clock. nd therefore ony there is one instance of addresses fof the clock variables, Thebasie variables ofthe clock are stored inthe file with the extension bss Including header files Isa preprocessor diretve, whieh includes the contents (coves or data) of & sot of source Files. These are the fils ofa specific module. A header file has the extensio “h Exainples areas follows. The string manipulation functions ae needed ina program using strings. ‘These become available once a header ile called “rang is included. The mathematical fonctions Square rvs, co% tan, stan and so 09 are needed in program using mathematical expressions. These become availble byincluding a beader fie called “mar The preprocessor directives will be “Winelude " and include " for including standard library functions for the strings and mathematical operations in the program Also included ate the header fks forthe codes assembly, and for the VO operations (cons), fo the 6 2S tunctionsand RTOS functions include VxWorks his tectve othe compiler, which includes ViWorks are Wo (OS functions. ne Cera compiles provide for cna. in place of sia. Tiss when embesied systems do not need the file functions for openisg closing, read and write operations on the Keyboard and video monitor. So when including sia, will make the code roo big, ‘What isthe difference between clusion ofa header ile, and text file or datafile or constant Mle? Consider he inclusion of merDrvConfig txt and mah) The header files are well-tested and debugged modules, Pann Ces rbd Papannginc Coo fas} 2) 5.2.2 Source Files Source filev are program files forthe Functions application saftware. The sue files need the compiled A source file will also possess the preprocessor ditccives ofthe application and ave the i fantom Jat Ishere the processing wll stort This function is called mui function. Is ees stat with wid ui (). The ‘main calls other fnetion. A source file holds the een 5.2.3 Configuration Files Configuration files are the les for ontiguaton of the system. Device configuration codes can be put in.a file of basic variables and included when needed. IF these codes are inthe file “seriaLine.clgih" then # include “sera/Lne_ cfg wil be he preprocessor directive. Consider another example, “# incre". cf hs this will inclde ox header file 5.2.4 Preprocessor Directives Preprocessor constants, variables and inclusion of configuration files txt les Reade files an ibrary functions are used im embedded C programs. A preprocessor directive stats with a sharp cash) sig, These commands ate fr the flowing directives a the compiler Foe processing Preprocessor global variables: For example, ia 8 program the InteDisabe. InrPortA Enable InPorDisable, STAF and STAL may be the slobal variables for disabling interrupts. enabling po ‘A. disabling port A. satus fla. status Ma for interrupt, espetively, Now “define volte boolean Inuable isa preprocessor dirctive.lrmeansitadivetve belo procsssing to coi IntEn 2 plbal variable of boolean datatype ands woaile (Volatile directive to the compile nw uke {his variable into account while compacting tod optimizing the eae.) Pueprocessr constants “t defne fale 0 ia preprocessor directive in an example, Ht mean its iectve before processing to assume “false as 0. The directive “define” fr ailing pointer values in the program. Consider #detine porta (volatile unsigned har *) Ox 1000 and # tine PIOC (olaite unsigned char *) Ox1001. 0x1000 and Ox000 are the addresses fixed for prt A poet A fein and PLOC (pt npn contol er ae the constants ie the AHCI Strings can also be defined. Stings are the constants, fo example, those wed for an initial display othe screen ina mobile system. For example. # define wercume "Welcome To ABC Telecom ~ 5.3 “PROGRAM ELEMENTS: MACROS AND FUNCTIONS “Table 5.1 lists these ements and gives ther uses. Preprocessor Macros: A macro is collection of codes thats defined in aC program by a name. tif fom a function in the sense that once a macro is defined by a name, the compiler puts the coresponding ccoues for it at every place where that macro name appears. For example, consider the macros. “enable Maskable_Intr()' and ‘disable Maskabl, Inu (The par of brackets in the macro is optional. I 240) Embedded Systems. is present, it improves readability as it distinguishes 1 macro rom a constant) Whenever the mame ‘nable_Maskable_Inte appears, the compiler places the ends designe fri Table 5.1. Uses of the Various Sets of Instructions as the Program Elements Fass of [rnevon ee Sire cnn on ek ene ‘cfr ic artand meng on : reves em ours ii ahr Mocro Exes a aed sal ateton of codes No Nove Fmcton Excite ed so es with aes pase by ws Yexcancal the caling progam trogh ts argument. ko sna uncon ‘cums =a det hen i ot dare av "conse itt te coment ving ad retieving vet. veinercd | Moin Deca of fnctons and dt ype. type end No one non eter (eee aman af coder cal of i functions adel cathe eps the SR or Gino OS Ree i | ssn Refer Sections 546 Ye Yevomaer aston =, | crag Destin offen nd at types. pte and xs ToIsRof | erace | excoes a amd tof ees Must besos tha ihe rey i nine er sous feu ae io eed within the mie “rst deadlines Must be reennt route Na alowed ‘oes {eal for intrpecss meng: orapor or i mas or gueue mesg) allowed the Ireroces mesage fre IST os | Prcess or Refer Sections 71-73. Must ie ea enam ve None | Motor tn or mst ave sata the hr te | | tread ‘problem cursive A funtion hat cals ite must be arena Yes ves ition anetion also. Mos often suse i avoided in embeded systems duet memory consis (Gtack grows afr each rere cal ant my clot the memory space aailbily) ‘Macros, celled test macros or tst vector are also designed during programming and are used for debugging, How does a macra differ from a funtion? 1, The codes for a function are compiled once only On calling that Function, the sytem has to save the context and on return restore the context Further, a function may return nothing (vid declaration case) of return a Boolean value, or an integer o any primitive or reference type of data Primitive ‘means similar to an integer or character. Reference type meas similar to an array or structure.) For ‘example, the enable PortA_Inr () and disable PortA_Iatr() are the function calls, (The brackets are ‘now not optional.) Programming Concopis and Embedded Programing nC, C++ and Java (ea } 2, The cos for macro are compiled in every function wherever thit mer name is ase the compiler before complation. puts the codes atthe places wherever the mais wel On using the mace, the proceso des mot have fo save the content. and doesnt have to restr he cones tete sno et, 3. Macros are used for short codes only, Tiss becatse, ia function calls used inctad ofa macro, the ‘overheads (context saving and new context reeving, and other actions on function call and yet) will tuke atime, Tapes tha isthe same order of magnitude th ite. Ty. fr execution of short codes within a function. We use a function for codes When the Tyan 2e Tors and 8 mac for ees Whe Tat = OF> Teg Mseros and functions are used in C programs. Functions are used when the requirement is that the codes shouldbe compiled once only. However on calling a function, the processor hast save the context. and on ‘elu, restore the context. A function may also return either nothing (void declaration ease) or return ‘Boolean value. or an integer or any primitive o reference ype of data, Macros are used when short functional ‘odes are o be inserted in a number of paces or Functions. ~ 5.4 “PROGRAM ELEMENTS: DATA TYPES, DATA STRUCTURES, MODIFIERS, STATEMENTS, LOOPS AND POINTERS 5.4.1 Use of Data Types Whenever data is named. it will have the adresses) allocate atthe metmory. The number of addresses allocated depend onthe datatype. For example. a datatype Fong is decid For munTicks {number of ik), ‘Then mumTicks will need four memory atest, allows the following primitive data types. The chur (8 bits) for characters ye (8 bis). wnsigned short (16 bits), short (16 bits) ansigned nt 22 bts, it (32 bits). fone dnble (64 bts. None (32 ils and double (64 bits). (Certain compilers donot tke the “byte a a dota type deinition. The “char” x then sed instead of ‘byte’. Most C compilers dono! take a Boolean variable as data ype. Ta rpedefs used to eves 4 Boolean type variable inthe C program.) ‘A. datatype propriate forte hardware is used. For exampe, a 16-bit timer can have only the unsigned short data type, and its range ean be from Oto 65535 only ‘The typedef is also used. Ii made clear by the following example. A compiler version may not process ‘he declration as an unsigned bye. The ‘unsigned character” can then Be wie asa datatype. Icon then be declared a follows typedef unsigned character portadsta tdefine poyte portadata OxFL 5.4.2 Use of Pointers and Null Pointers Pointers are powerful tools when used emetly and according to certain base princpls. Pinter reference ‘oa starting mennory adatess. A pointer can refer oa variable data structure ot function. Before a pointe, in C language symbol. used. For example, unsigned char “Ox1ODmea: ma caracer of bits at address Ox 100. ‘A NULL pointer declares as following: “Adefine NULL (void) Ox0OOU. (We can assign any addess instead of 0x0000 tats notin use ina given hardware) Exemplary uses ar a follows & Embedded Systems Example 5.2 1. Consider ‘unsigned short timer". Pinter rimer! will point to wo bytes. andthe compiler will reverse two memory adresses forthe content of mer CConsider two statements “unsigned short timerl;” anc "timerl +4. The second statement ads (0x0002 in the addiess of timer. Why? ln C.its iva variable, then x 4+ means increment ofthe value of x by 1. Irp isa pointer. then p +++ mens incement ofthe vale of tothe next sees. imerl ++ means pinto the next address, and unsigned short declaration alloted two addresses for timert (ier! +; oF ier +21 or timer = timer +; will have identical actions.) Therefore the next adress is 0x0002 more than the adress of mer! tha was originally dened, Had the declaration ben ‘unsigned int timerl and "timer+4:" (in ease of 32-bit ime. the second statement would hhave incremented the adress by Ox0004, 2. Leta byte each be sored at a memory address. Let a pow A ina system have a buffer register that stores a byte. Now a program using a pointer declares th: byte at pot A a follows: unsigned byte * porta’ The * means “the contents. Ths declaration means that there isa pointer and an unsigned byte for port A. The compiler wil reserve one memory zddress for that byt. 43, Consider declarations as fellows: void “portAdats the vid isthe undefined datatype for portAdata, ‘The compiler will allcae adress fr the #porvAdata wehout any type check. A.A pointer can be assigned a constant fixed addces. Two preprocessor directives: “# define portA (volatile unsigned byte ®) Ox1000" and “¥ define PIOC (volatile unsigned byte *) Ox1001 ‘Alternatively, the addresses ina function ean be sssignedas follows: "volatile unsigned byte * om unsigned byte *) 0x 1000" and “volatile unsigned byte ®PIOC = (unsigned byte) Ox1001". An Jnstruetion, ‘por +42" will make the oA painter poi othe next address und which is PIOC. 5. Consider unsigned byte porAdata unsigned byte *portA = &portAdata. The ist statement cnects the compiler to allocate one memory address for gurtAdata because there is a byte each atanaddress. The & (apersand sign) means “atthe adress of This declaration means the positive numberof & bts (bye) pointed by porA is replaced by the bye atthe address of pow Adata. The Fight side of the expression evaluates the contained byte fom the address. and the left ide puts ‘tha byte a the pointed addres. As the right-side variable of por data isnot. declared pointer. ‘the ampersand sign is kept point ots adress so hat the right-side pointe gets the contents (bits) from that adress. (Mate: The equality signin program statement means "is eplaced by) 5.9.3 Use of Data Structures: Queues, Stacks, Lists and Trees ‘A data structure is 9 way of organizing several data elements of same types or different types together at consecutive memory addresses. A data element in a data strvturecan then be identified and accessed with the help of afew pointers andor indice andor funetious. Maks (or grades) ofa student inthe diferent subjects studied in a semester ae pu in proper table. The table in the mark sheet shows them in an organized way. Similarly, when thee is a large amount of data it must be organized properly. Aaa structure isan important element of any program. Few impocant data structures include: sack. ome= dimensional array, queue, circular queue pipe, able (wo-dimensional say) lookup table hashtable and ist, Following describes different data structures and how its pt inthe memory blocks in an organized way. ‘Any data structure element can be retieved using the pointer. Programing Coss ans Enteded Prareningin C++ andra 23] ‘Stack A data sirvture. called sack isa special program element. A stack means an ated memory block ata from which data element is ead in 4 LIFO (last first out) way and am elements app o pushed from am address pointed hy pointer called SP (stack pointer) ar Sq and SP changes on cath push pop such that it pints a the tp of sack. Various stack structures miay be wrested during processing. For handling each tc. one pointer, which points tothe stack tps needed, Figure 5.1 shows the various stack structures hat are teated during execution ofthe embedded software |All can te made for another routine during running ofa outne. In order that on completion ofthe called routine the processor returns only othe one calling, the instruction adress for return must be shed on the tack, Pushing means svg onthe stack top und inerementing tack to point othe next ‘op. Popping means retrieving the saved adress fram the stack top and decremening the slack to Point othe previous top. There can also be nested cals and returns. Nesting means one routine call !mothe. which ells another and rum from the called routines always tothe cling routine, Therefore atthe memory ablock of memory aes isallocateto the tack tha saves the ped ren adreses ofthe nested calls. Its shown in Figur 5 (a). Two bytes of address are acquired inthe PC from stack ‘on retuen frm 2 call 02 routine (uneton). Assume 10 ested ell represent in the system or other funetions. Assine that PC addres is of 4 B. Memory allocation required for tack stvctre for Pushing the retum instruction addresses i 40 B. 2. ‘There may bea he beginning ofan input data, for example, received call numbers ina phone, which is saved onto a stack at RAM in order to be retrieved later in the LIFO mode. Its shown in Figure 5b), Consider fer example, on each push the following ae saved on a tack. i) Fou pointers (adresses each of 4 bytes: (i) four integers (each of 4 bytes) and (i) fur floating point nambers {each of 4 bytes). Memory allocation required fora sack stuctre for pushing the function parameters Saad ed edd = 8B, 3. Am application may aso erate the runtime stack sutures. Thee ean be lite date stacks atthe ifferen meinory block, each having separate ponte address. There can he multiple stacks shown ay Stock 1. Suck N in Figure Se. 4, Each tsk or thread in a muli-tasking or multiaheeadng sofware design (Sections 7.1-7.3) should have its own stack where its content (Section 46) i saved, The coment is saved onthe processor on Svviteing to nother ask orthiead. The cones includes the return adres forthe PC for retieval on ‘witching back ithe task, There canbe maple stacks shown 38 saved contests ofthe threads the sacks shown in Figore 5.1) at dhe memory forthe diferent task context atthe diferent memory blocks. exch having a separate pointe addeess. Threads of application prograns and supervisory (08) programs have separate sacks at separate memory blocks Each procesvor has atleast ane stack pointer register thar the instruction stack eam be pated and calling of the routines canbe fected Some advanced processors have multiple stack pointes. There are four pointers s follows 1 RIP (cetur instruction pointes: RIP is for saving the return addeess ofthe PC when a routine calls another coutine of TSR, RIP is called link register (LR) i ARM processor, 2, SP (stack pointer SP i pointer to « mermey block dedicated to Saving the content on content switch to another ISR oc routine. There sa sack point in 8031, 68HC11 and $0196 3. FP data frame pointer): FP is pointer to a memory block dedicated wo saving the data and local ‘variable yalues of presently running program (rune). ae 4. PEP (previous program frame pointes): PFP is pointer to a memory block dedicated to saved he rogram dat fame, ‘Motorola M8010 processor provides USP (user stack pointer) and SSP (supervisory sack pointer Program runs in tw modes: user mode and supervisory mode. In supervisory mode the OS functions execute [2aa) Enbodded Systoms ‘Theres switch from the user ma othe supervisory mode aftr every tick of the system clock Section ¥ 12 will give the details). MC64O40 provides Tor USP, SSP, MSP (memory stack fates pointers). [SP and Gnsevation stack pointer Stack 20m | Hang Return ‘actos hal PC | Adsestes on Pequres ested cae Co @ AMamory Bock ) sae hone waiting td mention [ ft ae estar ep L__terey ] Stacks |, Bang ona Retin Set Conan 7) see Comowts sek Nea sith rade J eng Rettvabe etn — | Sitesiene 2 Gon c : @ 5.1 {0} A stack due to nested function calls and pushing of program counters (b) Stack of pointers and parameters pushed onto the stack before the context switch (c)N stacks each having a separate pointer (d) Mutiple stacks of contexts for the multiple threads shen a processor has only one SP. the OS allocates the memory addresses that are used asthe pointers for the suaipl instructions and data stacks, {A recess has at leat one SP. Each process should havea separate top of SP and separate block at its allocated memory forthe nested function calls. stack es also bea special data structure atthe memory. Teta pointer address that always points to the tap of stack. A value from the stack is retrieved from the ‘mesma in LIFO mode, while a rw of data ora data ina table ara dat inthe queve is accessed in a FIFO (Ges in first out) mode. As there are multiple processes in an embedded system, each having separate coment, there are multiple stacks, Array A data structure, array isan imporant programming element. An array has muhiple data elements, ‘each idemtiiable by an index r by ast of indices and indices ae unsigned integers. An n-dimensional aay is special data structure atthe memory. Ithas a poiner address that always point othe frst element ofthe aa. For handling an n-dimensional aay, on pointer, which points tothe fist element and n indices ate needed. ‘Assume one-dimension array. From the fst clement pointer and an index of that element, an address i con structed from which the processor can aszessci ofthe array elements, Indexisan integer tha stars fom 040 (array: length-I) in a given dimension, Data word canbe retrieved from any element adress in the block tat is aloe stedtothe aay. A processorregistermay slsobe used for string the index and another register oraraybase point. Following examples clarify the concept of aray. Programming Concepts and Embedsed Programming nC, C++ and Java | 245 Example 5.3 1. Considerthat unsigned int {1 phone_nummeans an array of phone numbers, phone num 0} refers that est phone number, prone_aum [1] refers to the second phone number, and 50 on ‘The phone_num itself points tothe fst element. 2, Consider unsigned char { | name which means an aray of characters forthe name. name (0) refers othe Fint character, name [1] refers to the second character snd soon. The nare without index pois tothe first xray element 3. Consider the results of a test ina class with 30 students with roll numbers 1-30, Let bean index used instead ofa roll umber. Let marks in the test of oll number | be inthe scalar integer variable [M(O}, Lec M{O}, MU... M[28| and M|29] be the variables fr the marks of roll numbers 1,2, 29,30, respectively, Thre it pointer that points to the first scalar value M(0}.A register called index register may point e M\0}. The index register could then be incremented fom 0 to 29 by an instraction within «lop wo point to the marks of students of succeeding roll, ‘numbers, Figure 5.2(a) shows an array inthe memory block with the pointers for base and index that oily point 10 its clement marks (i) Vector (One Omens en TT ho LLL lil j a == ais ateiny Beck == un” Ostet atPoner kext Peter Fomrstoruase aes ns ojana Sat Ont rote Tal pier Bhs it Pl ‘noe Owe ‘Aawession itcoes) er Aes) éeiirg tom forerrg « One Stee Fer Citrus wn back te rn twesoned back berger ent at SE ES Maron eis —— FSG Sat ones Fata Tane? SanatTask: end Foie tom” (Ppests)(Ppesouce) Poe Pipe FronPomer —GrekPamer ‘eesewing tring to tom poe Pee cy Fig. 5.2. (a) An array at memory block with one pointer for its base, frst element with index = 0. ata word can be retrieved from any element by defining the pointer and index (b) A queue at a memory block between *Q.4q aNd *Qjn With two pointers "hag and *g toppointtoits two elements at the queue front and back. A data word retrieves inthe FIFO. mode from a queve (c) A circular queue at a memory block with two pointers to point to its two elements at the front and back. A pointer on reaching a limit ofthe block returns to the start ofthe block (d) Memory blocks at source and sink for a pipe («| Embedded Systems Example 5.4 ‘Take another example. An expression, ¥, = Eta, has coefficient, These are stored as an ray. pt 232k stores as anoer array and ouput y 3% et anotee aay. Hee i and ke the integers each varying fom -N to N-1, where Nis er the mis. Tree rays y [1.8 [| and x [Lae used foe caleulating 20 filtered ouput sequences by the expesin, y= 3a). Memey allocations ‘equired forthe each aay strture = 20.8 = 160 B, [Assume each element as double precession floating pointer numberof 8 8 (64-its IEEE 754 forma) | Example 5.5 ‘When the index increments by 1 incase ofan ara. the ponte othe previous element actually increments by 4, and thus the address will increment by Gx0004 in case of an array of integers. [An integer stores a8 4-byte namber] For aay datatype, * is never put before the identifier name, but an index is put within a pair of square brackets after the identifier. Consider a declaration, “unsigned char PowtA MessapeStrng (80). The port A message isa string. which isan aray of 80 characters. Now, PomtA MessageStrng is itself @ pointer to an address without the star sgn before it. [Note: Atay is therefore known a a reference datatype | However, *porAMessageSting will nw refer to al the ‘80 charaersin the string. pomaMessage String [20] wil efr tothe twentieth element (character) inthe sting Queue A dats structure, called queue is another imponant programming eloment. Incase of atay the ‘eating i withthe help of indices and first element address. So sny element can be fead or writen a a instance. In queue, cach element is read from an adiess nex tothe address from where the queue lenient was last read. This reading i called eferion. In queue its writen to an adress next to the adress tom hese the queue element was fst written. This writing sce iserion. A queue mens an lloted memory block from which a data element is etrieved in the FIEO mode, Using the queue, the Byles are sent onto 2 memory bufer or network or printer. For handling the queue. evo pointes are needed and a memory bitfr is allocated between bul adress pointed by °Q,, and buffer-end pitted by “Qe One pointer °C, pointing oan adres in 4 memory block where an element can be inserted (added on writing). Fora ueve of integer. int “Qa "jus declared. °Q,y initially equals °Q, and it should increment on each iseion a que back oti pointer. Te other “Oye (ueUE head pointe) ivtlly equals “Quy and is Fr pointing 10 an addres in ‘iemeory block from where an element can be deleted (reniove on ean). This pointer sheuld increment on cach deletion. Both pointers "Qu and “Qe point a the Beginning t0 “Quy the stating tnemony bale adress a the block. Insertions into a queue are usally faster than deletions. For exanple, in que atthe printer the sytem inser the values faster than the ate at which values re pinted, The diference in adresses At the two pointers at an instance isthe present queue length, ‘There isa possibility thatthe al pointer may increment beyond a timitst for the queve end ses in the ‘memory block. An exception (an error indication) is usualy thrown whenever the pointer increments Beyond the block end boundary. Else, on farther increments’ ai iifusion into other block may occur. Figure 5.2(0) shows a memory block between “Qu and *Qyr ith the two pointers °Quy a *Q, needed or deletions and insertion Programming Concepts and Embedded Programming nC. Crs and Java 247 A queue is a data structure with an allowed memory Nock (bute from which a data element i ereved ‘nthe FIFO mode. I has 1wo pointers, ne For its hes! andthe eter forts tail. Any deletion is made fom the head address and any insertion is made atthe til addess, An exception (an error indication) must be lnown whenever the pointer increments beyond the black end boundary so tha appropriate action can be taken, Circular Queue A yueve isealed circular queue when a pointer on reaching a limit °Qua fetus its Mating value "Quy (A cireular queue means @ bounded memory block allated to a queue such that its pointer on ineremeating never exces the st limit and turns to start on increment beyond the limit.) From ‘civular queue also the dat element i retieved in the FIFO mode but no exception is thrown on exceeding the limit of the memory block allocated. Figure 2.4) shows a memory block wth a circular queue with is wo pointers needed for insertions aed deletions. A cireular queue is a queve in which tail and ead pointers cannot increment beyond the memory block {hufler and reset othe starting value on insertion beyond the boundary. Pipe A pipe isa device. which ues device driver functions and in which insertions ar fron the soure end snd deletions are at snk-end. The deletions are atthe destination end and ae like in the queue. The insertion source has an identity distinct feom a destination (snk entity whece deletions are made and source and destination are connected by some function pipe_connect J. Figure 5.2(d) shows memory blocks fra pipe. A pipe isu device with insertions and deletions at distintty defined source and destination Table A raleisa two-dimensional sructure (oasis) and is an innpotant dataset that isaloested a memory block. Mere is always a base pointer fora table. It points to its Fist element tthe frst column and fist ro TMheve are tw indies. one for glum athe wie for sro. Figure 5.) sbowsa memory hick with the Pointers for table. Like an array. any element can be retrieved from three addresses forthe table hase. ‘column index and row index. Instead ofa colama or ow poet. a vale is wed in am insiruction which is called the displacement. Displacement canbe used fra colurin or 10 2 Jookup ube isa vodimensional structure (mtx) and i a important data set Ut bas only rows and sch row hus a key and on reading the key. the adresse dita is triced. tables dataset allocated witha memory block, Thee pointers, table base, column index and destination index pointers (orto pointers and one displacement can etieve any element of the table. Lackup table {sa bl of keys (pointers) and from reading a Key the addressed dat is retived, ‘Hash Table 4 tush table isa dataset that ia collection of pais of hey and comesponding value. A hash "able as a key or name in one column. The corresponding value or objet a the second con. The keys may be at non-consecutive memory adresses. Figure 53() shows a memory Block with the pointers fora hash ‘A bash table is a dataset allocated with a memory block for Key and value pir 248 Embedded Systems ‘Aono Block Exons tom Base Pinter owas Tobi fo Ma: Element (0) omnes stein eo tsuneo | fase wipes pe at Base Register A eee use depacenet Y[[ for'edex Ph Rie yf sess mn “ aninsruction (Te corsage) Ai ere = Golerns et o : gotten oferta ie Sone a Apne ana ano mong at aregot Ro orin meron) hese ° scons tony uate os oor 77 2 EB WI Nevey Bus! MemeySac.? Neron 2083 Heed Et EB owtopromer ig "EBL = ay fearon oe oa Cet ar een on (tafe Ea an ee " (sce Fig, 5. (a) Amemory bloc wth the pointers fora table (b) A memory block for hashtable with the pairs of key and value ina hash (c) The memory blocks in system memory with the pointers fr alist St Alia isa data stuuetre with a number of memory blocks, one foreach element, A ist has top (head) pointer forthe memory address from wher it sts. Each ls element atthe memory also sores the pointer to ‘the next element. The last element poins to nul A ists for non-consecuively located objects atthe menor, Figure 5.3(c) shows the memory blocks with the pointers fra ist. Example 5.6 ‘Assume on a realtime clock tick, the ISR increments the counts in number of RTCSWTS (else cick imemuptsstiggered software timers) Assume tha there is alist of RTCSWT timers tht are active ata instant, The top of thelist canbe pointed as “*RTCSWT_List.top’ using the poiner. RTCSWT_Listiop s Programming Concepts and Embedded Progamming nC. Crs and.Java 243| no the poimter othe 1p ofthe conten in & memory fur 4 ist of the ative RTCSWTS, Consider the statement ‘RTCSWT_Listtop +4” Itincrements tis pointer i 8 top. I wil nox pint othe nex top of ‘smother object inthe it (anther RTCSWT) but wo some address that depends om the memory sddrecsoe allocated toate in the RTCSWT List. Let LisiNow be a pointer within the memory black of the ist top element. A statement "*RTCSWT_List ListNow = *RTCSWT-Listtop:” will do the following RTCSWT_List poimeris now repluced by RTCSWT ist tp pointer and now points to the next ist element (object (Note: RTCSWT_Lis.top++ fr pointer tothe next Hist object can only be used when RTCSWT. List elements are placed in an uray. This is because an ary is analogous to consecutively lvated elements of the list at the menor). Consider a statement: ‘while (* RTCSWT_List ListNow -> state ‘= NULL) (numRunning +41; ‘When a pointe to ListNow ina list of software timers that are running at preset isnot NUL, then only execute the set of statements inthe given pair of opening and closing curly braces. One of the important uss ofthe NULL pointer i in the lst element ofthe ist opin othe end of ist {o 00 more coments in a queue or empty stack, queve or lis. A list sa daa structure in which each element (objet or dot structure) also stores a pointer to the next ferment atthe lst It Nas one memory block alloted to each element. The list op pote poms to fast. element ante list element points to NULL. Table 5.2 summarizes the exemplary uses of queues slacks, arrays, lists and tees. Table 5.2. Uses of the Various Date Structures in a Program Element Dats Sr Defi ad whe se i) Prin buler. Each characteris | lobe nal inthe FIFO mode, | {iFrames on aenwerk (Each | Fee also haa queue sceam | of yes Each byte hast eset Foc eveiving eo FIFO. Ouene leicaumsare wih a sere of elements with a header lene wn or fel operation, ld eetion ‘pera. An operation can be done nl inthe ist a frat st (FIFO) mode i ued whe clement sa toe accessible by ay ine ar oie dc bu ‘nly ough the FIFO. aa eeeat can be inet nly {teed the res oF eenents wating ara operation, i Image frames ina sequence | Thee ate tw pores oe or Jeleting afer the operation (hese hate tobe rose av wating fran operation. An opeaio ean be done ony in coat on tent reall She st inst ot (LIPO) node is wed wena element sother futon fh) Rete iag isto be accesible by any inex poate diel, But popping the pushed Jt rom ‘only tong the LIFD. An cement canbe pushed (inserted) Sock, ony athe tp inthe seis elements sil waking fran ‘operation. Thee i only ne pote wed fr pop eleting) alt th operations wel for push iserting, Pointers Increment or deen after sn operation It depends on insertion or deletion, | Stuck ‘tis a structure with u sexes of elements with is tas element (i) Pushing of variables and ___| (Cond) Da Sire Aras tone {= 12°: Talay. 12 ‘dinensional aces by eter mare and index. Hs element can be ies he ist mem sector ‘red and operated easly, Is ted when cach element of mark sigh [|= mare weigh the arctr is tobe given a istic dey by an index [0 wig of marks in she abject for easy operation. Index stars ftom Oand is postive with inde 4 sign he sme Imeser inthe sujet wi nds Mat: luisa strcture with series of elements each having Handing marx or ena, dimensional apatersubseres of elements Each clement s accesible Conse ie nun image frame. Comier Quince image piel in 1 178 8 inage rae eal Scton 127) pie (108 $8 wil rose Bie! tthe 108th wil om find the ch ve! clara "See the llowins el ‘A steno nhs which ar tive Eau ink te pine of the nex tusk: Arak example is era the pois ta submen aray by the denier mame and two or more indies Kis used ‘hen every element ofthe site be gven a dtinct ‘Gentiyby two oc mar ines for easy operation. The imension ofan aay equals the aumber of nics that are needed osc identify an aay element. Indices start om 0 and sre postive meses. is Each clement has apes toits eat element. Only the fir clement is detiible and he est top pow (eae) does it No ther element entifiable and ence sR accessed. By going though theft element. and then consecutively trough ll be snecteing element ‘element in be red rea apd deleted orca be aed 10 !eiahbouring elmo or replaced by another element | Am example sa direst thas Tee ‘There is aot clement Is two ce mae branches ech umber file folder. Eich Hie taving» angler lemene, Fach daohter clement hs 0 frmore daigher elements. Te last one does ot have foe; han fh He “laughter Only the oa element ise and itis —_folersand soon Inthe end 9 one by te ect pone thee). No other elem iste ‘enible an hee isnot accessible dry BY traversing fom the oot element. then proceeding continuously though al he soceeing daghers 0 tee lement a be real cr ead ad deleted oan beaded ‘o anther ugh ot replaced by another element. A tre has daa elements aanged as anche. The as tug called lea nde is no farther augers. A binary woes woe wih maim of todas (branches) in each element and noe 3 ef kre "poet. epee pie tthe Feces tp an pl, 75] epee tha a he it nr pel 140K {s}isapitel as cen inate dnarsonal ayo reps pne te sane sin 0X38) ete Fra, ‘The reader may ef toa standart textbook forthe C and C++ data stuctve algeria 5.4.4 Use of Modifiers The actions of modifiers areas follows Case (i): Modifier “axa” or no modifier means that there is ROM allocation forthe variable by locator if {is initialized in the program. RAM is allocated by the locator, if tis not initialized in the program | | | Programming Concepts and Embedded Programming in C, C++ and Java 251 Case (i: Mosier “nnigned isa maf fur a shor or ine ve lng data type. Hi. dvetive to permit only the positive ves of 16.32 oF 64 bis respectively. Case i): Moir sur” eclaratio vise function block, Sac declaration sa dective tothe compiler ‘hat the variable should he accesible outside se function block alo, and there is to ew eserv memory space Far it Ithen des no save on i vl parameter sick, When several tasks are execute in cospeaton. the laration stare heps. Const an exemplary declaration, private: static vod interupt ISR_RTHC The sae ecaration ere sor he irectve to te compiler that the [SR_RT (function codes iit the memory lock for SR_RTI (function. The private declaration here means tat there ate noah insane of ha tad in ny ther objet thea does net save onthe stack. There is ROM allocation bythe lector iit is iniialzed nthe program, There is RAM allocation by the lector iit is not inialized inthe progr Case (i: Modifier stutic declaration is ouside a function block, Iti not usable wiside the class or ‘modle m which tis declared. There is ROM allocation by the lcator forthe Function ces Case (i): Modifier cons declaration is outside a unetion block. 1 must be iiilized bya program. For ‘example, fMefine cont Welcome Message "Thee i ail for you". These is ROM allocation by the foto. Case (i). Modifier reser declaration is inside a funtion block It must be initslized by a program. For ‘example eguter CX". A CPU register temporaily allocated when needed. Theres ao ROM or RAM allocation, Case i: Modis imereut Ives the compiler ta save al processor registers on enty tothe function codes and restresthemon thet urn fom the function (thio isprefised by an undeseore, interrupt in cenuin compile. Case (vil: Modifier extern: I directs the compiler to look for he datatype dectration or the Faction in 1 module other than tbe one curently in use. Cave (x): Moe volaie ouside a Tunetion block isa warring 1 the compile that an even can change its value or tha its change represents an event. An event oxample isan interrupt event, hardware event or imer-tisk communication event. Forexample. considera declaration solarile Boolean IntEnable: It changes tofalse atthe stat of service hy a service oie, if tv previously, The compiler doesnot perform optimization fora volaite variable. Let variable be snsigned.c=0. Later. its asigned c= 1. The compiler will ignore the ‘statement c = 0 during code opimization and will take €= 1. But ie isan eve variable it should not he ‘optimized. lntiEnable = isa the beginning of sevice routine in ease an incerrup-ebed variable is used for disabling any interrupt dung the perio of execution of ISR, IniEaable = | is executed before ret from the ISR. This enables fe intecrups at the system. Declaration of InEnable a voll diets the compiles not to optimize two assiznment statements inthe sane function. There ino ROM or RAM allocation by the locator. Case (a): Modifier volatile sare declaration is inside a uveton block. Examples ste’ (a) ‘voli ati boolean RTIEnable = te": (b) “vane steric boolean RTISWTEnable und (c) “volte sti boolean IRTCSWT_F. The static declaration is for dirctive to compiler that he vaviable shouldbe accessible outside ‘he Mietion block als. an there iso beareserved memory space frit. Te volatile sa diretive that cannot ‘optimize as an event can modify then doesnot save onto the local parameter stack ofthe funtion, When several tasks are executed in cooperation, the declaration static helps, The compiler does not optimize the ‘ode because of declration volatile. There is no ROM or RAM allocation by the lear, 5.4.5 Use of Loops, Infinite Loops and Conditions Sometimes a set of statements is epeated in a lop. Generally, in ease of aay, the index changes ad the Same set is repeated for another element of the aay. Loops are used when eXecuting a set of statements repeatedly. A Toop starts fom an intial value or contin and executes il the liming contin is ald “There can be ceton parameter, which changes each ime fronts inital condition p+ iting condition, 252) Embedded Systems Forexample. consider the following. for (i = 0; i < = 200; a++1 [/Paserof statements which repeatedly execute */ . The nts conditions assigned a5 = O and he lst condition For the loop to execute Ail is ess or equal to 104, The sto sateen in the Bracket executes trom start to end and before return 0 Start the | increments by I. The for statement allows sot of statements to repeatedly exectte 101 tines with values of 0,1. 99,100 Foranother example, consider the lowing { = 0; white (i < = 100} {/*asetol statements which repeatedly execute * J: i+) Thema condition is asigned asi =0 nd is set before the while loop, Te while Toop executes lj emai sor equal 0 190. i reremens before the run totes the lle condition, Te ‘hl aement lows the st of statement to repeatedly exocut wih values of i= 0,1.» 9, 100 1 a condition remains true. then while loop will execute infinitely. For example. while (1)| (/* a set of statements which execute repeatedly execute * The loop will execute infinitely because | is always tm, Infinit loops are never desired in usual programming. Why? The function or task wil never end and never exitor proceed further othe codes afer the loop Infinite lap isa feature in embeded stem prgramming? ‘The system software inthe telephone has (0 be always in a waiting lop that Finds the ring online. An exit ‘rom te loop will make te system hardware redundant. ‘Example 57 gives a C program design in which the program starts executing from the main () Function, ‘There are calls tothe funtion and calls on interupts in-between, Ithas to return tothe start. The sytem main Program is never ina halt tate. Therefore the main (in an infinite loop within the strand end Example 5.7 4 define false 0 4 define true | pereseeon ‘oid main (void) ( 1 The Declarations here and initialization here *7 eessenseeseensarssessoeenennee] Infinite white lop follows. Since the condition set for the while Joop is always tue, the statements within the curly braces continue to execute * while (ue) [ 1 Codes that repsatedly execute */ I ‘Cxample 5.8 gives an example for se of polling for an event or message in a progr. Assume that the funtion mat has awaiting loop and simply pases the contol to an RTOS. Each task contoled by the RTOS will also fave codes in an infinite loop. Example 5.9 demonstrates the infinite loops within coc tsk Example 5.8 1 define false 0 # define tue 1 Jomrennensenencesuiwengananatasentscannen soseeeceneowesnseneennes] | | Programming Concopts and Embedoed Programming in C, C++ and Java 253 void main (vod) ( Call RTOS eun here */ rosin ( while (0 { ‘1 Infinite while loops follows in each task So never there is tum from the RTOS, #/ 1 1 Jeveennes void task (..) > Declarations #7 eeseesenennecssersesnsesece] while (ave) { 1* Codes that repeatedly execute */ 1 Codes that execute onan event * if ag {5}; Mag! P* Codes that execute for sending messige to the kemel #/ smessagel ();, 1 i poreeaseneentennarsentonsconsuntouteeastageeoneennatnostenessssstesvey void task2(.) 1 Declarations *7 while (rue) (| 1 Codes that repeatedly execute #1 1 Codes that exccute on an event */ if (flag2) (i) lag? = 1 Codes that execute fr sending message tthe kemel 4 message? (); h 1 [rhaescenonneesnasnasterssaensonnsennsctstesteenentvennsssaceanses eeeeeeescenseuestertatesssssusensentey Void task (.) Declarations #7 | 254) Embedded Systems while (rs) ( 1 Codes that repeatedly execute *! 1 Codes that execute onan evert*/ if ag) (ik Mag = * Codes that execute for sending message to the kernel %/ message’ ()5 i , “There can be more than one infinite loops. The cade inside infinite oop waits for an imter-process- ‘communication (IPC) message or event Nag or ast of events through the OS. “The cade inside the loop ofthe running tak generates a message that transfers to the Kemel. The (0S kere, which posses ote waiting task message, detects tand when that task starts the OS pre cemps the previously running task Letan event be setting ofa fag, and the Mag stig isto trggeé the running ofa task whenever the Kernel passes ito the waiting task. Te instuetion SWI enecutes to Send the message tothe another task Function for ‘Conditional statements ae used vey often. Ia defined condition(s) is fulfilled, the statements within the curly braves ater the condition (ora Statement without the braces) ae executed. otherwise the program proceeds othe next slatement orto the next set of statements "A set of statements cle sith-case, A program switches to a case as per the result of switch expression sesult Por example, Switch () means switch a6 per the case forthe value of Example 5 9shows an aplication Of infinie lop and switch ease statement for programming For GUI in mobile phones (Example 1.5.) Example 5.9 Consider smart motile phone (Example 15.4. Assume thatthe seren sae js between O and K, smong 0, 1.2... ork —1 posible states (st of menus). A interupt is iggered fram a ouch sereen GUI and an TSR. poss an event message m=0, 1, 2,....0€ NI as pr the selected the menu choice 1,2... N= 1 when there are N menu choices fora mobile phone use o selec from a screen in sate j The m will depend on the sereen postion atthe touched postion. Figure 5.4 shows the use ofa programming model here, which facilitates execution of one ofthe muktple possible funtion calls; a function executes ate poling fr sereen sate j and fora message m from an ISR 2s per the user choice define tue 1 4 define false 0 poveesseecenereeenennensentesssneenteenennsnrensnequvestenssenstent/ ‘oid main (void) { 1 declarations */ ‘while (rue )[/° Execute infinite loop * poll_Sereen_State (i); Calla function to pol sreen state. A stte means a st of choices of mens displayed on the touch screen */ Programming Concepts and Embedded Programming in C, C++ and Java 255 _ onsets oieselston Foran a po anced: Interrupt | Case screen siate = 30. menu selected - md}. sabncton (50.0 Co eee ae So momoncn’smorsasnon select | Ot Meda [emmes]l ¢ [onmes] S = ‘wnetion (69) [natn os | Ea Sona ) Fig. 54. Programming model use here, which feciltates execution of one ofthe multiple possible function callsand the function executes ater polling for screen state and for amessage 1m from an interrupt service routine as per the user choice 1 1 sseseenuasnnsoscesoesnnennersnetsnsstaneasonesanennecennenonennets] void poll Sereen_Siat () 1 Let number j identify a sereen state */ Switch () [ (Case 0: poll menv0 (ext () Case I: poll_menul (): ext) Case j poll_menul () exit) (Case K: poll menu ();exit() ’ 1 cententeneensssnsenneqnseensennennnpeonesscesvogneggaseesssststsy/ ‘oid poll, menu0 [/% Code fr paling for eoicejxom menu 0 fr scren state 07 } An TSR sends message m a per the choice selected by the use from the menu in screen state j*/ Switch (m) {| Case 0: Code, which executes when the choice is menu 0 Screen state O*/; exit (3) 256) Embedded Systems (Case I: (/*Code, which executes when the choice is menu 1 Sereen state 07 ¥/ exit ():), (Case NI: {/*Code, which executes when the choice is menu N ~ 1 Sereen state OF exit) ’ , ptsseneensenngneseresnasnscnsesneseseasesesssesasaneensearentanesteey 1 Codes for Sereen state 1,2, "7 1 An ISR sends message m as per the choice selected by the user fom the menu in sreen sate ‘id poll_menul {/* Code for palling for choice from ment for sreen state J*/ 1 ANISR sends message m as per the choice selected by the user frm the men ‘Switch (mf Case 0: {/*Code, which executes when the choice is menu 0 Sereen state 2: exit (Jz) (Case I: Code, which executes when the choice is menu I Scren sate j* *: exits) screen state j */ aie N~ 1: (Code, which executes when the choice is menu N =I Screen state j* exit ()s 1 Hl fr eneaneeneuusenonnnsuasntsenesscanscaseneegsennennesnecesesseesees/ Codes for Screen state j+ 1,2... K=1 4 w ‘oid poll_menuK {/* Code for poling for choice From menu m for sreen state K 1 1 [rvonesannseunsensstesesssssssersneseonscenesenaseenssassecsonsouesee/ fable 5.1 gave the meanings of the various sets of instructions inthe C program. There are special functions ‘or stating the execution of «program, “void main (voi)’. Given next are the steps tobe followed when ‘sing function inthe rogram, 1. Declaring a function: Just as each variable has to have declaration, each function most be declared, ampie 5. 1. Dectate a function as follows: int rum (int index RTCSWT, unsigned int maxLength, unsigned int ‘numTicks, SWT_Type swType, SWT_Action swtAction, boolean loadEnable);’ The run isthe function name, Flere int specifies the returned datatype. There ae argument inside the brackets. Datatype of tach argument i also declared. A modifier is needed to specity the datatype ofthe retumed elemert variable or object) from any function Here, the datatype is specified as an integer, (A modifier for sgcitying the retumed element may also be static, volatile, verry and exter.) 2. Consider a device diver function open (i, options, device_paramete). The called function name is “open’. ses the device configuation. When he function iscalledby statement, open (4, O_RDWR, 9600) First, second snd thi arguments that re passed, ae 4, 0_RDWR and 9600. Fist argument Programming Concepts and Embedded Programming nC, Ces and Java [257 is forthe device deseriptor and passes the value f4 = 4, The descriptor i an identity, which san integer number. The second argument describes the device option seting a read and write deve, ‘Te third argument describes the device parameter, baud rate. the rate by which the sei line, pNext: return *this:) boolean int. aM (ava doesnot support operator overloading, ‘well sting concatenation ) ‘There sneer tat binds allthe member Functions together in C. Buta C++ clas has objet features team be extended and child clases can be derived from it A number of child clases can be derived from ramon class. This feature iealled polymorphism. A class canbe declared as public or private. The data and methods! access are restricted when clas is declared private. Sruct doesnot have these features. const (return (ListNow != NULL) doredList & operator | ( ) except forthe “plus operator which is used for summation as 5.6.2. Disadvantages of C++ Program codes become lengthy, particu when elowing features of the standard C++ are se 1. Template. 264 Embedded Systems Multiple inheritance (deriving a class from many parents). Exceptional handing Virtual base clases, Classes for 10 steams. (Two library functions ae cin (for character(s in) and cout (For character(s) ‘out),| The VO steam cas library provides forthe input and output steams of characters (bytes). I Supports pipes, sockets and file management features. 5.3 Optimization of Codes in Embedded C++ Programs to Eliminate the Disadvantages Embedded system codes can be optimized when using an OOP language by the following 1. Declare private as many classes as possible. It help in optimizing the generated codes. 2, Use char, int and boolean (scalar datatypes) in place ofthe object (reference dia types) as arguments and use local variables as muchas feasible. 3. Recover memory already used once by changing the reference to an object to NULL A special compiler for an embedded system can filitate the disabling of specific features provided in C+». Embedded C+ is aversion of C++ ha provides fora selective disabling ofthe aforementioned features so that there is a fess run-time overhead and ess run-time library. The solutions for the library fusctions are available and ported in C directly. The 1O stream library functions in an embeded C++ comple ae also re- enitant. Hence using embedded C++ compilers or the Special compilers make the C++ a sigaificanlly more ov erful coding language than C for embedded systems. GNU CiC++ compilers (called gcc) find extensive use in C++ environment in embedded software ‘evelopment. Embedded C++ isa new programming tool with a compiler that provides a smal eun-time library: It satisfies small run-time RAM needs by selectively de-configuring features like template, multiple inheritance, viral base class and so on, when there i @ less run-time overhead and when theless run-time library-using solutions ae available. Selectively removed (de-confgured) features could be template, run lime type identification, mokipe inheritance, exceptional handling, virual base classes, IO steams and Foundation classes (Examples of foundation classes are GUIs (graph user interfaces) Exemplary GUIs are batons, checkboxes or radios.) ‘sn embedded system C++ compiler (ther than gcc is Diab compiler from Diab Data. It also provides the target (embedded syslem processor) with specific optimization ofthe codes. The run-time analysis vols check the expected runtime errand give a profile tat is visual interactive. Embedded system programmers use C++ due to the OOP features of software reusability, extendibily, polymorphism, function over-riding and overloading along with the portability withthe C codes and in- Tine assembly codes. Ci also provides for overloading of operators. Embedded C+ is a C++ version, Which maies lage program development simpler by providing OOP features of using an object, which binds state and behaviour and which is defined by an instance of a class, We use objecs in a way that minimizes memory needs and ranstime overbeads in the system, “5,7 “EMBEDDED PROGAAM MING IN Ja 5.7.4. Java Programming Basi Java programming starts from coding for the clases, A class has members. A field is like a variable or struc {C-A method defines the operations onthe fields, similar to function in C. Table 5.3 summarizes the basic Programming Goneupts and Embedded Programming in C, G++ and Java uses an the exemplary uses Clas instance ean instance methods ae the members, whose new instances are aso eretedas when the object ar created from the elas. Class isa named sto codes that has a number of members ~ fel (variables. methods Functions). and so an, s that the objet canbe created from it “The operations ae performed onthe objects by passing the messages to objects in OOP Each class is logical _2roup with deity. sate and bebaviou specifications. Fran in-depth learning of he programming language, 1 reader should refer tothe standard textbooks and do the required practice exercises Table 5.3 Various Elements in a Java Program ve Program Evans) ofits use teres (or (int i= 07 im {Local variable A variable within ablock of codes is defined inside the ‘ury braces and has mie scope. fotalotiarks = 0; 105; ise) (eotalotvarks + = subjectMarks(i);}; | return totlaofkarks:} Here 1s the local variable, The 7 | does aot have any scope ouside | | | the freon Invonce Blocks of Java ces, which given a mame, a all findtotalmarks (1 (4) method (Goveation) is made by other Jva coves that can also pass The metho id Tolar () wil also be created in objee ceated fom the cas, (ari the needed erence to he ves, parants, ado An ideitie witha mame ad sing that me» String tele_nunber: Here, \decraton is made ia Java cls. tors have adelt_—tele_number san instance field of ‘lead thee is aso presen inthe objects which re he cee and wil aoe crete in Instone of the cles. ‘he object creed rm that elas Instance fed public class salaries 1 | public float monthly | Salary, totalSalery: Chas Achaia basic srctra unit in a Java progam. A class consists fata ils a methods that operate on the Feds A cass defines a group of objet sim anibues apd common behaviou and elation: publi= Coat Ships A cas is used torent objects as its inanees. “FindTotalSelary { ) (1: Teas insance and tte el and methods , ‘va clas inherits members when Java cass enended from a pazeat las ale ager cas. The ined insane fields and metas can be overiden by i i public class | ‘edefving them in extended clas using same name, | Aecountbetaits extends | BankDetails (-};- Thecss AccounDet wil inherit. ‘members of clas BankDetis Imerinnce ‘evens and agumenypes Metods canbe ‘overloaded by redefining em fr diferent numb or ‘ype of argumens. Ieee bs oat the abr metodo the public class | cenesponding ated ils and the hos dbaet_—RccountDotails extends inlaveingleneation ine mete AJoa css wich is Barkbetaiis implements | imefaced to an interface implements the abstract methods InterestComputations(.). | speed steiner | j266 [fe Precon Eplaarion Tian of Elen _ _ _ : fc sot byte. porta; i pon Data pes ava clas es ptive data pes Byte (. ye pores 0p Ereen 5.7.2 Java has advantages for embedded programming 2 follows 2 3 4 Embedded Systems (Cosi, int 32-4 ong (6D, Neat. double unicode ‘hu (16s) Sava cise ses reference ta typ. A reference can be fo he classtype in which ther are groups ff elas and metbds to operate onthe Fils. A reference fan be wo the aay type in which there ae groups of objets say elements out dala? int mum Tick 13248 aumero lock ick 7 hai fa 7 scout Nonke and al ID 2 Sing cls os *7 Java. Lang.arzayindexourot ‘poundexeaptions: 0 at adincrayt.. This hows on exception javal ling puckuge fas an Obj jens Throwable ‘We en kn deine expos in ry [catch (Exception el) | Fnaly {1 (Geanple 6, tom Java has builtin exception classes. The eccuneaces of “exceptional eodion ave handled wen exception ‘tow, Its abo pestle to deficeexcetioa conditions ‘ng peogram so ht exceptions are own fom iy Back cedev and caught by eateh exception method (Sesion 422) Java Programming Advantages Tava is completely an OOP langage Java program stats wth clases Applicaton program consis of clases ebjes and interfaces. " ‘There a ge clas rary on he network that makes program development ick java hs exter . Sere ‘has in-built spon for creating multiple threads, It obviates the need for an OS-based scheduler or banding heads i irae cs hes crn oe YM vi aie) sa View! machine ale he Java Bye soe nth pt nd nso tegen ptm (ese: Syne an OS {Vieul mache (Vn enbeded yaems ir sore ROM Then. Ceses can host on diverse patos. Pon independence in hating the compiled cols pst va Tor network applications - Pratfom independence gives porabiiy wih respec ote processor and OS we Jvaiscomidered ts wite one and nun anywhere. : :. Tovaisthe language for mos Web applications and llows machines diferent sp to conical am the Web 7 oe iscsi toler by a Co programe. Sava does nt ei poe anplaion nstos, Sos obusn he ses tht mer aks and memory ated eros do nt occur A memory leak occurs, for example. when alempting 1 Ariat the end of bounded aa. aa Ia does prt wy fe npn by ae sa ere Tee at ot tum. typedef and nin, Java doesnt permit maliple bere. Jv doesnt permit opetor tneroning except forthe ‘ps sgn usd for sing concatenation, 5.7.2. Disadvantages of Java ‘ava has following disadvantages for embedded progeamming 2s follows Programming Coreeps and Embedded Progamming nO, Cas and Java 267 1 As vases artistic hy the VM, iteuns comparatively slowly. This disadvan ean be vec fll yt es an be converted to naive mane codes or as cng ning Justntine UIT) campilation A Java accelerator (coprocessor can be use in the system for lane coder, 2 Juve byt codes tata generate need lager memory. Anembeied Java system ny aed minimum 0512 KB ROM and 512.48 RAM because ofthe need first install JVM snd rn he apication 5.7.4 J2ME Us of J2ME (Java 2 Micro Et) ur Java Card or Embedded Java helps in reducing the cae size 10 8B For the usual application ike smart ca How? The following are the mothe {+ Use core classes oly Classes fr tn rtm environment form the VM ina nt deny the programmer's new Java classes ae tin internal forma, 2 Provide fr configuring the uti cnirnmen, Examples of conigring ae deleting the een handling classes, user-defined clas loaders, ile classes, AWT classes smehuaniced threads: treed runs at-timensonalarrass and long and floating dana types. Other con ing examples are andtng the specific cases-—datagrams. input, ouput and strain for comectins to tee odnn needed, 3. Create ne object a atime wen cuaing the multiple tc 4 Reuse the objects instead of using a lager numberof objects 5. Use scalar pes only as long as feasible avaCard, Embededava and JME are thse versions of lava that generate 2 reduced ode size 2ME Provides the optimized runsime envionment Instead ofthe we of packages. 2ME provides fr she ces forthe core elses only. These wes se sored tthe ROM ofthe embed syste W rove tot erative configurations, canned device configuration (COC) and connected limited deviceeentioweehe: {CLOC!. COC ines tow lasses fm packages for net seer refket. secure tat etree tl. jar and ip. CLD doesnot rove forthe apples wt. Beans, mith ne. mises andl so packages in jv. lang, There is & serrate jovacmircoedition ja package in CLDC eunfiguuaion, Pe {personal digital assistant) o mobi phone uses CDC or CLDC. ‘There i scaleable OS feature in IME. Thee isnew viral machine. KVM san emitive to JVM When using the KVM. the sytem nee a 64 KB instead of 512 KB rune enviroment. KVM features ane Fallows |. Use of Following dats types is opionsl.() Mul-dimensionalazrays,(b) long 64-it integer and () eating points 2 Errors are handed by the program classes, which inherit only afew needed etrorsandingelanses From the java UO package forthe exception. 3. Use ofa separate set of APs (application program interfaces instead of JINI,JINL is ponable. Buin the embedded system. the KOM hus the application already po andthe user doesnt changeit 4: There is no verification of the clases. KVM presumes th lasses as already validated 5. There isn objet finalization, The garbage cello does othave to perform ime-cnsuming changes in the object fr Sinaliqtion, {5 The class foaderis not available to the user rogram. The KVM provides the loader. 7. Thread groups ae nt available 8 There is no use of javalangretion. Thus, here are no interfaces that do the objet serialization, debugging aed profiting, 28! Embeded Systems rhe JVM lint the chs, The eonfiaion can Becta IME nea noe nssreted hy profiler eases, For example, MDP vate init devise prilers sa gle els Ta ns devices, profile defines the supe of stove iy, The prolif isa layerhetweem dhe applic and the configuration, For example, MIDP i between CLOC and applivation, Between the device sl ‘ntiguration there i 4 OS, which iy specifi othe dice ned ‘voile ifoamatien dove hs the oie ing ‘8 touch sercon a keypa 2 nina of 6 54 piel wolour vr raemneteame display Wireless networking. A minimum of 32 KB RAM, 8 KE EEPROM oe Mah fo 5. MIDP uscd as in PDAS. rile phones and pars, MIDP classes describe the displaying tet It describes the network connectivity Fr Iniernet Hyper Test Troster Proto. I prosides syppent fr small databases sone in EEPROM o¥ Mash ‘nemory. I Schedles te aplicatkons an supp the time ‘An RMI remole imehed invocation wot isa exemplary profiler for use in dsibuted envio and 128 kB ROM, 7.5 lavaCard and Embedded fava 1 smart earl (Section 10-4 is ekoete circuit with a memory and CPL new svothesved VII cre Ihispacked like an ATMeand. For sina cas thee i fas cr tehnology- (Refer tat wa ja sun cd rohit vaca) Tema formats or the ur-tine environments are availabe mainly forthe fe lasses in Ja ead technology. Only one applet an ea and each applet is stateless. Java clases for connection Alga. inp. ouput and steams evi aod ery ‘onvzonmet “Thee isrestcted rntime evn. A srt cn ingle pean usesa Suva The Jvaaanate ‘platform independence an Byte aks isan asst, The smavt cae cannoets to remote server. The ea Stoves the user acount pst lance an see tas forthe ven server infoevaton nam enery peed ea er ienlying a eotfying the ose, The Ie deciphers and communicates vo the seve intensive wade for the comple appcation ra tthe Serer For Eibeddedliva fer hr htpafas a, ssneunvembedalaes. Ie prides an embed eta and rte bv s optional covvieanmem and a closed exclusive stem, Every ‘ava objects bin the sate an behaviour and are iastanees ofa Java class. Emibeddedava iva ava version, ‘which wakes large program development sinapler by providing complete OOP features in Java. SVM is configured to minimize memory neces and run-time overheads in the system. Embedded system programmersuseJavaina lrge number of readily available eases forthe TO stream, network an ec Java programs possess the ability to ran under rextited permissions. JavaCard isa technology fr the smart cards and is bast on Java Programming in thensembiy language pies he inpatat hens af pres cunt ofthe processors. neal devices and comple use of proesespevifcFesuesin its instcton stand adesing mes Pann Corea and Entei PopunninghO, Ce doa (os + rosum in igh! neg i hip Ros su deena aspen and portability to system hardware mexlitications. I easily makes larger program development fesse, ” lage spp wo insne ats dagen ck sy pvt oe a The C program ss fri ston sar, pyeecut Oven merece ma te snes adhe es al font ¢ fgg met ate ed gp as Iodine eens um toca mcs etn iu ea sew + Ivint oping sgt we etn it egp tk se a a kon stenever ed mor sig + The Cfocton pumas athe ale ts lps ler te fats. pr, NULL poke and ction po + Greve san inp da sie a pt, T sit sce nis ona weer n ene iain one om and een oes gine PPD ttc. Quests ay tr ns ete onan clo ee enna en + Queuing of pint theft tpn ol encores a he qc es {ppc greening oi spans sof eae ie BR + Uo sac swe fee fr svi ssn eo ape tonal Sti et ns jv: unscting avscsking sn slon0 opsnemelenen oman ean ae + The i ard pony we ede tw esting eno em nding sn ln to i ating let a kl -ess he InOne exon please Astle cc insti wie inn Maat he ey ae eee moti tsks + Ces provides ll he adeages of Cals OOF Is wee canbe etd ty ining te ented det lows a Desig pate ny hss spose 0 Ug. on etre al da tye) np of be ete est gen se este nec ee {rRccoveing memory onset by caging rence oa ae to MULL. Wr Sey ceaiing enn Crt os Hoe rene read an ain iy nr Sees ‘movin te resection ake ea bane ies 10 stuns nd clas » Ja piste nonessential alan inks J2ME vs? Mu ts hog: an raf rth ral Svs fou od Era aan ne sat dal on ve Hepwords and Hel Refit A named et fcodes hh sunbe f ems = variables nto that he objects canbe rated fom it.The apeation are dane othe bcs by posing the messes wo the objets ia OOP. Each cls dling rvp with ony sa nd behave seston. (Class rari Cus fora numberof appicatons like exp, neyption, smi. may ‘bs provide after thorough debugging and testing for using these inthe equicnents Use of ass irae spe up gropram developer cek Date structure [A uli-lement satu tht canbe fret by a common mame identi) Daa ype ‘Type of daa fora variable, for example an integer, ad on which ona dened set of operations cane pestered, 1270, Development exele ‘Exception handing Foundation eases Fonction quewe Header fle High-level language Inline acsembly {clude fe Infinite top tO area ist Local variable ‘Memory optimisation Modularity ‘Muipe inheritence uu Object oriented programming ‘Ordered Bist Passing he reference Embedded Systems if ini ln er of ye a el Seely msc yin embeds ROM Tres erate htm tendo cet of oe exe Meee runner ay ir be: Aeon Sa mn nd ves re hts i seccanci oma eo Cia nears Gc, bn cme AOR) fet pane ete tons og cession er Finn os tony sin on fr ewe Fr exe Be eae ee ental ine Prvenay ungelesen cfs Gon ite ety saamag al ch ano gts the ingratfeeis of shot devel ent a en Se nanny xnck poy inca mlsance Trapt a aunty gg in hel guage ha ge ets nec eee es rc nla aog ahd wer me cde fot conininby meant ‘cay To he porn tame exe 00 err on tng i ey corm emling oan pnt men Sar ranean nop ‘ey ale seed yen eyesore meu 8 Se Sc tnlaeontsrrokad sapien see Se ect inieoing ts pne Mawes once ‘Senso te pens ane ety ered en tee i aber iO mak Eaccnon bs pie ch aa there cen atest Uncle pst MULL Tepe ps ome arm etre wins hcl nctnea ene sr ye ga nce he me fr ny go cere Se tema ws ey a ete he ay Crap cats teal oe ene wyutsuc aif meaei ty alot apns ‘as ots a nei went mr a ne a Asap poms t NULL east ee sore oe nema. Ximena oeped y an elcmen or et or ta car can Bed By pane oie NUUL ° ‘Corning mete sich ised pnt on a pe Struc eb an uc vias te operons ae Sne on the Spear cares abn liga ech i hc ts ny elt certo en ad Sr acy tise seehly see fone From ecu noes th mute pl Fo eel Feiner essing se cling eto Teele Programming Concepts and Embed Programa nC, Cr+ and Java len) Passing the value Plsform independence Portable Preprocessor deceives Private Qnene Reference data ppes Robusiness anne library Resetine overhead Seal data pes ‘Stack Source cade engineering tol Temple Viel Bese cloes ‘hoxton argiment becuse when operated nd he fanction may sta direst argument valve Fac ter en nhs nem The une ‘ale des ot sve on he stk when hat pases y seen From a foction, a values wan ate fiction ut he sae vale is reasigned othe engl rion fer rtm ra th cll foetion. Bore sng the agumen ales aes onthe sack an retiees back eum From the funtion ‘code that ean prc ieren nahin sd Ss. ‘cote hat cn be pon anther program by suitable configuration changes. ‘Program statement etves for ch ome before the mn fnction to inches and define global variable lool mero (section of coe new dz ype ae plobal certs. A varie belonging 1a pei ls apd ot wale case that lass. ‘Ata srt ito which teen can be segue ised ad delet in FIFO mode. neds t0 pointers. oe forthe qo (ac) fr insertion and ‘he ate or queve hea (ron or deletion rad ad point ext ele). Array and rings ae examples of retreat, ‘A programissidtoberobusi cea inetion without ers ike stack ovetiow an ovtof memory errs. Avoiding ponte angulation nttons, eau, Teeinghe memory faa needed ae and waingencenions mae ede rou Aiba furtin that inks eam thera tine. Rani nksncease ‘untie overeads and ou of memory ert an sie Use of RAM for ds and stack calles runsime overbead Thecturace.ieger. unsigned integer ting pei amber longa double ae calle sel dita ype Uke aay daa costo one single element A datasractr in which eens can pushed for svg in etn memory boeks nd cane open LIPO mode sed ne pin for the stack heat ‘op Fer poping (eat and poi to ea element) a5 wel pshing [A power tol ro engineer souree cies a als belp in debussing and efomance analysis ofthe codes in bighlevelangusgoe A tet of clases sing which new cise te bail A special typeof class proved in C4, iB Review Questions sys? ‘What ae the criteria by which an appropriate programing langue is chosen for embeded software of given 2 What sth mot psn feature a Cat aes i ap high eel ngage fron embeded ys? ‘What isthe mos imporan feature in Java that makes Nighy sel evel eguagntvr an embeded sysem ia mary vetoes applietions? ‘nati me aotanage of porphin, when posing wsing C++? Why do you beaks pogram inc hee es. congas files modules a anton? Design tablet give he features of tp down design snd bastnupdeign of rogram. Embodded Systems 2 apa he pte of th along detain: tic. wien wat abl C Hoa wh ane the fling we nao tn ths tsp! mal oe) psn te 2. Wha ae th anges sing focware, GNU COC empile 10 Why sea veda eens 1. Why aa sao nin op embothlsster svane? 2) Wha ar he asanloges of r-mt anetow cnt st 5. Wht at the ara sing sh ae te vases of building 1 guts? Wht ae the avarages of ving short ISR ht Bui the oncom usta oe re es ne fo net? ip func cals in yc ore min? 1s ow arth 7. Wi do the feature in C+ make the ode Kathy hen asing template, swipe mbeitance (ving las Fro say pres. estonia il as ls sel 10 sirsahs? Tale the reasons fi AKiteu device driver frst COM sera ine port in Cc nine ave cas 1 What ae te mn inmonly ase prepsso dienes? Give four xa of ech {6H des the eo nae die a Tenton? Esplin wth esc) ek 31 Wha pgm C cone or fo for suming TO neers with ud indi nls ach inter 32 Bits. Now wy the hg and write C cade ae, Compare the ae gt in al es processed Wh descr il Be es sit or eng he aps Cnt ot Ppp Ciauash Binet eo to ing xanthan 5. Give ta pe throu 1 Sack i fe odd 1 ira Program Modeling Concepts . Procedure-oriented langu |. Two models for programming languages are procedure and object oriented programming (OOP). ge examples are ALP and C. The C language provides for funetions and main C function defines the first function that executesand the other functions are called from the main. A n be funetion can call another function. There nesting of funetion-calls. There can also be mul funetion ¢3 C are preprocessor s, modifiers, conditional statements and loops. pointers, function calls, multiple functions, function pointers, function queuesand ISRs, Program tes data of various typesand with various structures: arrays, queues, tacks, lists and trees. |. OOP language examples are C++ and Java. C+ sup- port object-oriented as well as provedure- codes. Java is purely object-oriented, Obj reusable software unit and using these units the reusable software components are built. Large com- plex software can be easily built using the software components, eA 2eseu an ~ QO REL EO aS A standard design practice adopted by engineers is 10 use a model when solutions 0 problems are tobe found. Te event poling based programming. oncarent cesses pregvennning. sequential programming and OOP are the presvaming monde mes fen ase. The objective of his chapter is ola the iprtan concepts of progea 1 The following concepts of program mudeling ave explain! 1. Dataflow model using dataflow graph and control daa fw graph 2. State machine model 4 powerfal madeling language is UML bese an object oriented design. UML fails the need fora unified language, which cnt mardel many tps of processes lasses. objects aetvtes, designs and development process appro, 1tshauld tls be understood. An objective ofthis chopter is to fear the falls. 1. UMI. basic elements. 2. UML diagram. Example of nae of UML is modeling a software plementation, Embedded ssiems may be considered in concurrent processing mole as sstems with concurrently unning processes dnd the processes may rire real-time Constraints. Concurrent process malel and interprocess communication will be described in Chapter 7. 6.1 PROGRAM MODELS 1. Polling for events model Section $4. explained this model by Example 39 tnd Figure 54. There s poling in eycie lop for he exerts, sate variables messages, and signal using the swich-case Statements Sequential program model: Example 5.12, Section 547 gave an example of sequential programming model n wich here ae sequetiamike eton calls withina fanction. Section $49 gave another example of Sequestial node! in which the [SRs provided short period deviations from the sequence for exceusing short ces a sent function pointers as message inserted into the queue and then the Fuetions executed in FIFO ont Example 6.1 Figure 6.1 shows a sequential program model for ACVM (Section 1.5.2). The following Functions run i Sequence 1. Ran function gel_user_inpt (for obtaining input forthe choice of chocolate from the child 2. Run function read_coins () for reading the coins inseied into the ACVM. fo the east of chocolate: "= {3 Run function deliver. chocolate ( ) for deivering the chocolate. 4 Run Function display-thanks () for eisplaying ‘Collect the nce chocolate Visit again” Program Modeling Concepts 275) + tan pts Lo iments i Seven : —— | fontan en [oT teeters] | eset | ince sete. en: ou J ‘ead _coins | ote choot | sseerenis i Eee) Fig. 6.1. Sequential programming model of an ACVM 4. Dataflow muadel: Bata Ro graphs, abbreviated as DFGs and contol data flow graphs, abbreviated as CCDFGs are used for modeling the datapaths and program Nows of software. A program is medeled as handling the input data steams and creating output data steams. The models based on data Now ‘model concept will be dessied in Section 62, 4, Siare machine model: A propane mode! is that there are diferent tate and the model considers ‘system as a machine, which is producing the sates. Example 59 considered cifferent states, which have different displayed! menus and the program action depended on the stat. Programa sequentially polled forthe screen state and meny choice selected by the ser. Example 36 sicwed how a key ‘marked $ can prviuce on pressing dierent state (, 5), (1, 5). Uni vu. Te tation of a key jeeurs its pressed again within an sneral. The state ofthe Key undergoes in a eyelic lashion as (1.5). j) 9 C-k) (1-1) 9 51 (0). The models based on state machine concept wil be heseibad in Section 6. 5. Cancinrom poceses en inerpnces cramaniceion male: A prrannning nels that here are severl ‘cactent tisks (or aceses or tnedk) ad ich task his the sequen cede in infinite loop. A tisk sends 1 message oe sign for sche sk Ash, Which aes a message or signal. un ad the reining tasks remain in te blacked se, Example gave the esemplar codes, Example 62 gives the coeurent process model based pregran for de sequenl program nde in Example 6.1. The mode of concurrent process, tasks ar thread: and interproces eormmunication between the concurrent processes wl be (eseribed in detail in Chapter 7 Example 6.2 Figure 6.2 shovis a program model based on concurrent running of the processes in ACVM. (Gecton 1.102). Assume thatthe program consists of following processes, which ean run coneutenly. 1, Process get_usez_input_ (for obtaining input forthe choice of chocolate from the child and signalling to process read_coins star. 2, Process read_coins () wait for signal get_usex_input () and sar reading on signal from for reading the coins inserted inthe ACVM fr the cost of choclate. Post signal to process deliver chocolat to stat and also posta signal o process di splay_wait () 0 stat 276, Emboded Systems [ISR GUL inerupt () f+] process get_userinput oe remaeeras a Been | |e aie [iscsi ee — | ‘eate process ‘process ead coins() _|__.[ process delve_chocoiae ()] erate, | [eaten Sees : (aac Se aoe i | Serre, | Seen stionge fcenan tae — | i Sate) eee peat | eres meee Cronintwpca’ |Rereaie. [| eee Foor a eee anaes Bienen | [eens Sana Sésply thats |_| Sion Saepay wat Fig, 6.2 Concurrent processing program model of ACVM Example 6.3 Thisexampl gives an objec-sed model ited ofthe ACVM sequential program mode! and concur process-based model ven in Examples 6. 62, respectively ure 3 shows cles and ober rogram Modeing Concepts andl bused on the ACVM (Section 1.102). The sind inheritance and inertia features in pg foliowing can be the cssses and objets 1 Class GUE for graphicuser imeraciu, H fas Wo methods display mens () and get_user_input |) and for ebvaiing spt forthe ebuiee of chocolat Fa the cil. his method Set _choice { to set the cite wlevted 2. Class Read Coins ( for eal de wns inete: I hist method ead, to rene. tw ad {ve rupee coin rom thee poms sa etd suo) oe sumsning the ttl coi 3. Class Deliver_chocolate.lhssmethuds, get_choice (jlogetthechoicoand deliver (0 fordelvering the chocolate 4. Class MsgDisplay. Ithus methids @splay wait ()and display thanks () for spaying wait ad thank mesa Class GUT isused to create GUI abjxs sx mule instances of GUL Class MagDisplay isuscl tw-reate message display abjects as mips instance af wait and thanks messages. lass MagOisplay ‘ean be interfaced 1 interaze sexeen_ei ze (7. which hasan absact method screen eize “The abstract method sereen_size (is implemented in clas MsgDispay Extending class MsgPisplay cin yucilyy new class MogTime Display, Exended class Megtine_Display inheis all auibwes aol meted of Class. MsgDisplay. Extended class have another method display. tine.date( for displaying time ad dat also with each message. Extended lass can intertacew interfe set_disolayy per iad MsgTime_Display will now implement the nnethod set_display_period (10st display peved of 1 oF 2 minus For thanks and wai messages In the objected-viented approach. ther s reusability of defined objects fom GUL and a set of objects that are common within program or Besse the many applications af created. Also we have abst ethos. sereen_size (1 ail set_isplay_pericd which are defined in the itera bat ‘emplemeted inthe inerfacing classes. Thor inerance inthe New objets. which ane ceatel by 4 extending th class MsgDi spay. Ther: is eteapulation of medous and atributes in the class fan objets LUM. is modeling linguige fase onthe ohjscorinted model. Section 65 wil desihe the UML 4. Data Flow Graph {A data flowy means that a program flow sa il ram execution steps ve determined speciilly ont by the data, The softvare designer predetermine the dts inputs and designs the programming ps 0 gener ‘the dat out. For example program for finding a average oF the ards in various subjects wil have the ata inpts ofthe grades ana data output oF the average. The program exerwis 3 Tunction @ generate the appropriate output. The DFG nde! is apprmprist to model the program forthe average How does dts How in 2 program? Data that is input ater th operations nthe program becomes data tha is ouput aftera date Mow. A diagram called the DFG represents this graphically. A DFG does not have any conditions within it o that the program hus cme dat entry point znd one data output poet. Thee is only one independent path forthe program flow when the program is executed. circle represents each proces: in DFG. An arrow directed towed the circle represents the data input (oF ‘se of inputs) and an arrow enginating from te circle represents a data output (rast of eu). Dats pat 278| Embedded Systems j278) Syst sng an input edge is considered as token, An input edge has at Hest one token. The circle represen the rua, The nde is said to be fred bythe tokens om all np edges. The outputs considered by the autzoing tokens, which are produced hy the node on ing [saws ee) [emmy] petit ros costes | |_te Sega Seo omit gers asim | | Sam fect, srm, case Sion, Bilin Senet rescind sae ert so seston, Seer * Soe Seetaagde - Cortera lass. 1 keer cower | | seta een sn) octet | | tbat see ae _entarClck (J: sani ‘Sepay Thanks: MsgDipay ‘depy Wa: MegDplay Gass GUI ass GULACa] {Gass AC Oar (eevee J 14.63. asss, objets, inbertance and interface eatresn OOP model based ACUM program ‘When there i only one set of values of each othe inputs and only one st of wales of the outputs Foc the given input, @ DFG is also known as the ADFG, (acrylic data low graph). All inputs ae instantaneously available in APDEG. Examples of non-acrlic data input are a follows: (i) an event (i) a status lag setting in adevice and (i) input as per output condition ofthe previous process. Example 64 gives a DFG during a DSP algorithm, Example 6.4 Figure 6.4 shows @ DFG ofthe Fllowing expression for an output sequence Jf fnte impulse response (FIR) filter’. An nh filtered outpu sequence, yj (%q.) where the SUM 8 made for i= 0, 1,2, «y 1N-1] Figue 6.4 shows the DFG fora process forthe sath FIR squence and Figure 6.4) shows the DRG for a set of processes of the same sequence. Following are the points notable forthe process of caoulating yop Xet ys +p Ke485.X44 8% + dy Hay Program Modeling Goneepts 279 |. There is one input point to the press represented by the cick Fr caulting yy 2 There sone output point for 9 Theres only one memory address and vaiable for each eeticient and each iter input. There is ony one value ofeach of the six inputs for and ther is only one value of each ofthe coeticients, 3. (DFG is therefore also the ADFG.) ‘The onder in which inputs are obtained and the summation i done is so immaterial Fig. 6.4 (0) Dataflow graph (OF) fra process forthe sixth finite impulse response (FIR) sequence (0) DFG fora set of processes of the same sequence for an FiR filter with 6 inputs and 6 coefficients Ie must te noted from Example 64 that theres no complexity in she proces or yy, DPC models help in a simple code design, simple code design ean be defnal as that in which the program mostly breaks into DEG. A DFG models a fundamental program element having an independent path, Wt gives that wnit of sem, wich has ab conroeonitions and thas single eth Fr the program ow. A unit gives the program Context and helps i analysing & peograre in terms of complexity. A more complex program would have Tower aunier of DEG proceses than a sinple program. igure 6-3 shows.a DFG model for the program fer saving a pitare in Sigal camera aka are 7 ceva Sihsand sa sca ok Stray ous Seon per sk Selon = incipnas —+ Moe Senaetmergond — stetare sfonsi tse Siow a8 inane Sapo Soprcner t sassPe6 " [Abc seamed dn | eomprcesn Fig. 6.5 DFG model for program for saving a picture in a digital camera 280 Embedded Systems ul executes aya single pces yur nual prugrn, A program ot tmessage or event ve Set A ese tnd the fnpot determin the aup DEC anol po execute in pr the Sofie implementation bocomes greatly simpliied when using te DC heen the DPG model there 'Sasigle dain point aa single dat-out pi. wth proses et of pes that are presente by ‘ses Programming tasks at simplified by representing the cle fr cach process by eee using the ‘ata input rn incoming anow(s) and generating dara expt ny vatging arts. When the asignment ‘a mpati fise in a DFG. itis aso called ADE. Progrunminy conyplesty mininized by madeling ‘rege in gem oF as any DFG8 as possible ad the we of sy nay ADPC as posse 6.2.2 Control DFG Model ‘com Toy ans Yk specifically only the program determin ll pron eecation steps and te Nove ‘Fepengram, Te software designer programs aa eeeerines tex stepm How ds one design a proces that "gps sto for taking decisions during the da operations ow ino apna A proces ay Fre the stems that contol the inputs or outputs Kay ae hag or endtion etrnin-betoen re * tion $43), Daa thats input generate the dts ea fierce lta Me ap the conan condor, gaat) dgpends on the canal ements for various dens in pruas” A CDIEG is a diagram, which apically represents the coitons andthe pram aw along evnaerdepnen path. "he CDFG lagram also represents dhe eflet of eves sn he pagesnes and sows Which pracerses 1 etivated am eich specific event. Here a variable value hanging above limit or below a init o falling ‘within a range is aso tke an event tht activates a cetsin proces A circle also epresentscach process (called nod ina CDFG. &wivected ar towards the civ represents the data input corset of inputs) and a diseetd sre rom the inte represents dala Mp (a set OF ‘pats. hos tyquare or rectangle witht diguna aes vinta verte ah may resent a eons, Foevample in Figure 6 61a, Aematively. a conlion cam be marke orcad at the Sarto the ite or ar. reed amu from the box ora marked staring sonst determines the ton te Be then en the condition i ee, sxampie 6.8 igure 6 6a) shows the controlling inpat (decision) muds bythe text comition ypviying Bowes. a the inpotstoa CDFG for on FIR filter wit IO inputsand IO coeticients recall Example 4 for menigs of various terms in the nth filtered output sequence. y= Zia, white the wm sate fr i=. 1.2 9, Following ace the points notable for the process of calla y, Thee is one input point the Process represented by the crc for calculating |. There is one outpat point ory, Ther is only one memory des and variable for each eoetcient and cach filter snpat, These ae the variables, i, sand e, which take multiple values during the program flow. 2. The order in which inputs are obtained and summation is done does mater Figure 66(0) shows the controling input in the {n_A. Out_B program of Examples 4.1 and 4.2. Here, instead of boxes, the condition is marked at the start the are ‘Ther is ineeasedprogramcomplexity inthe process for, The CDFG model elps in tnderstanding all conditions and in determining the number of paths program may tak. It So shows us that the Sofivare mast be tested for each path starting from a decision neve, and helps in analyzing the program in tems of complexity. Program Modeling Concepts 281} ran. cana eso sy ant ete tcc proses na ve set of eNUMs deter. whih proses seve ain in Lance CDG sal aspartic mess or te ‘ig. £.5 {0} Data inputs and controling input (decision) rodes shown by test bores in a Control ata flow graph for a finite impulse response fit with 10 inputs and 10 coefficients (6) Controlling input conditions marked in the in_A_Out_B programs in Examples 4.3 and 4.2 (instead of a box, the condition is marked at the start of an arc) Sofie implementation becomes simplified when using the spesifcations ofthe conditions and decison nae inthe CDEGs that cpresent the eon decision a he des. athe program paths (DEG) are trversed eanseqienly fiom the nods fer the decisions. conwhs tes Hew Graph SDFG} Model ‘When here are numer of token (ints required fo compattion fo generat more tokens (op) ina single Firing. the dataflow is ssid 10 be synehronous. The SDFG mode is as follows. [Refer E. A. Lee nd D.G.Messerschmit Stic scheduling of ynchronous daa flow’, IEEE Trnsactons on Computers Feb. 1987.) Lean ane represent hater in physica memory. Thea can contin one o more Okens with the delays ‘woken doesnot re the computations at vertex tilt isreceivedat the vertex, Vetices ctl inthis raph are called the actors. Actors do the computations. An ator ao represents a complete DFG within itself. An edge tewtween de vertices ares witha aro Fore dition represents aqueve of output values fromvone vertex and ‘a quede of input values to another verter Eiges Cry the values from one actor another. {Let X and Y be 1wo sets of instructions that once fired (started), do not need any further inputs fom ‘my souree during the computations. Let X generate the output vals (ohensdata) a, b and c, Let Y get ‘the input values (tokens). a. and j and et have a delay, The numberof inpus to Y need no equal Embedded Systems the number of ourpers from X. ¥ gets additional inputs and does not nee! sll dhe wutpurs Feom X, “These computations aml dst ate now” madelled hy 8 dvectes DFG that exis fons X40 Y Tks number of ‘uipus and inputs ae Tall near the ae origina arc end,Figue 6.7 shows aes venies which does the computation on fring! ad arcs in drete graph Between X and Y. The figure sss the ouput, Band © and inputs ac ian), The 8 with clay (40), The do onan are represents the inal wakens) ivan SDFG ‘model. Then inital token oy also represent ace thats shown hy dot on the (1,5) > Cj) (1,8) (1, D> 5) (1, Fist state, variables = O represen iil key inactive state. When iis I it epesents the ative sate. Second-state variables, = 5 or jr kor repens the final character, which is accepted as output after I-second delay. A transition occurs wien essed again within a pri es than | second. The timer has coun ester, compare eit and flags—TR (imerrunning) and TF (ime compare ouput lags Stat aston occurs when key ip interupt flag KP is equal to set or TF = 1. The tation on Trees the key. Te ine tar on Key inte and ‘when timers in ON state timer-rn fag TR equals 1. When te timer if oimer ime oats, TR =0, When count =, tier lag TF equal false before imeout. Timeout occurs when count x equals compa ester loaded for I second Afer I second the TF equals. Tere are 12 finite numer of states ofthe key and the timer together. Examples 68 and 69. give the ste table and state machine program, |286| Embedded Systems 1 eeyitegtiag — 1 ATR ARTF = 0) than 6 ~1 agit (R20 TF = 1) thonG~0: 7 TR 1 means ume eraving ales fey ine, TF! means ier testo outsneae Fig. 6.10. The states, state transitions and finite number of state transitions in 2 key’S‘in mobile phone 19 keypad Example 6.8 “Make site table for FSM in Example 67, Table 6.1 gives the state table forthe Key °S* in T9 keypad. Table 6.1 State Table for the key Text Se ‘unt Prevent Sate ‘Action Event Key TR TF _KF KP Cou Key TR TF__KF 5) geen Oat gees wor ete tme cee (183) eel nen ONE OB Tc I) eee fet) ete ewan eee te cy le 0 te C0) ee ines oe D1 80 Wit kL OO Timer est fetches fe ects Gots kee ete ees eee ee 00) ee Tic ea an 10) 0 Wik 8) LO Tier eva fay 0b 8 = 0 Tine reset op o 1 0 0 0 ap 0 0 0 Teer ree ay 0 1 8 0 0 Lk 0 OO Tioer vee ape to O06 Gh) OOO Tinervews te: Coun ial cust eter valve, =x mans cous rater thanx ad ks ana compsre fegier value efor I sco tne ct TR =O ean tier Gop TR =! meas ime ning afer Toning vale in compare reper fer apne tine ot af | econ TF =I means ine compte time out KF = {hey pres event, KF = Omens Ley tr eslve Example 6.9. ‘The C codes from Table 6.1 can be written as follows 4 efine tet 4 define false 0 Program Maden Concepts | 1 define iniilStte "05000" 1 define satel °15100" 4 define stated “100° 4 define sateS “1K100" 4 define stated *11100" 4 define stteS“15010" 1 deine states “010° define stateT “1KO10" # define sate8 “1010 4 dafine stated 15000" # define sate10 “000° 1 dofne state 14000" 1 doinestatet2 “11000 void KeySesM () { char [} state: initialstate = 05900" while (true) (/* An infinite lop * & pare eee ey 7 ancion play (x) sows character & 0 he Screen ad fantion cursor ext () moves the cursor positon next when keying in an SMS text mesag. SWI is software itt inction*/ Switch Sat} | inate: if (KF = 1) && Count==0) ( SW mers: /° Execute Inept atin to tt the timer * display 5°): Sate break Stal: if (KE ‘SW! timerRestar; * Exzcut Inter outne to restart the timer */ Aisplay C9"); State = State2:} break: preseneceseveseeensssnesnsenesen Stae2: if (RF = 1) && Count == x) ( SSW timerRestart; /* Execute Interrupt routine to restart the timer */ display °K") State = Sta} sassnosonseensenesssnseunteansenseanennecanee/ break; pessueenusevessuesuscusceneessenenecnsestestineeseseseeseacennennesnnaganeenseste, Stae3: if (KP = 1) && Count == x) | ‘SW timerRestat; * Execute Interrupt routine to restart the timer */ splay ("State = Sure) break Jovesesentennecareesecsusunsenvssgunsansenssenssenscisteesateeeseenesstessstesteey 288 Embedded Systems SSW vimerResurt;/* Execute loterupt routine to este the timer */ ispay (1); State = State; breaks povestictnecenvbeteetesssncesenecennesiasuesancenseqasnasastsneessesenenatsneeeet] eS: iF (KF = 0) 8& Count = 0) ( ‘SWI timerReset /* Excole Interrupt routinet reset and stop the timer */ splay (°5);cusor_peat () State = Sates) State: (KF == 0) &8 Count = 0) ( SWLtimerReset/* Execute Inerupt routine to reset and stop the timer *7 Sisplay CY curse. next (); State = Statel0:) exit sreeesesensenanensssseatetentessesasenteanetastnssententstestesty] praveenenenennen State; if (KF == 0) 8 Count = 0) { ‘SWI timerReset; /* Execute Interrupt routine to reset isp (7°); cursor pent (State = State) tnd stop the timer exit() sc aneoranseeneteeeresteeateetstssrssentensesstessateetenteetesy] povene States if (KF-= 0) && Count = 0) [ SSW timerReset; * Execute Interrupe routine 1 reset and stop the timer #7 ipl ("TY cusor-next (State = State!2:) ext): craceanneconsensssenssteseneesesnatenteatesnansentensensnenenso/ p—__________£5 of Switen-case 1 Bnd of While infinite loop */ | 6 Bnd of KeySSM */ “ FSM model assumes the finite number of states and reduces the programming tasks to the following: 4) coding foreach state transition function and each output function: (i) knowing the ime periods taken by the proces at ech state transition function and between each state, when programming for real tine. “The FSM made is appropriate for ane process at a time, forthe sequential flows From ane sat oth next becomes very handy while coding for state machine. 3.4 “EICRTDING OF MOMTIOROCESSOR SySTEMS — £.4.1 Multiprocessor Systems uae A large complex program can be paritiond into the tasks or sets of instructions (or processes or threads) and the ISRs. The tasks and I5Rs can un concurrently on diferent processors and by some mechanism the tasks can communicate with ach other. tte and forthe controled flow ofthe progrem. When using the FSM mode, a state table representation Progr Mang Coca {209| J Example 6.10 1. Assume a farge programy has four tasks: task I task 2 ask 3 and task 4, I has four ISRs: ISR_A, ISR_B, ISR_C and ISR_D. Assume a processor PA is statically schedled to run task 2. ask A, SR_B and [SR_D. Processor PB is statically scheduled to run task I. task 3, ISRLA and ISR_C- Figure 6.11 shows te scheduling 0 the processors, 2. Assume a large program has four tasks: ask 1, ask 2, atk 3 and task 4 thas 4ISRs: ISR_A, {ISR_8.ISR_Cand/SR_D. Assume aprocessor has dua core withone core statically scheduled to run the tasks ad the other the ISR. ISRs Send the messages to the asks running on the ‘ther core. Figure 6.110) shows the scheduling on a dus-core processor. ‘Signa or message ea Senator message A (ate an : Cond) Ge) <—~Cems) Spal or message Signa or message 7 aa i tena“ of taskt) (‘6.64 of Took) (] St ee ey) @ ret Imeeupt Inert tnagopt x ‘ Isa sae Isc Isa.0 Stogms seocme sate Stogma N Tek Tek? ase ase ‘Smeane spa aném meare metsape olan ine posts communication Fig. 6.12 (a) Static scheduling of tasks and interrupt service routines an two processors (b) Static scheduling on two processor cores “The problem ishow to partion te program into tasks or sets instructions betscen the varius processors and then how to schedule the instructions and data over the available processor times and resoures o that there is optimum performance. Should there he static scheduling for running one task on one processor? ‘Then, suppose one processor finishes computations earlier than the other. What is the performance cost? Performance cos is more if there i idle time lef from the available. What seh performance cost ifone task needs to send a message to another andthe other wait (blocks) ill the message is received? Following are the problems in meveling the processing of instructions in a multiprocessor system 1, Partioning of processes, instruction sets and insttions 2. Concurrent processing of processes on each procesor. 3. Static seheduling bythe compiler, analogous to scheduling in asuperscalar proceso. (Each superscalar processor has multiple processing units in parallel) 4. When superscalar units are preset ina processor, i means two or more pipelines of instructions are executed in parallel. Pipeline has a number of stages (3 t09) and diferent instructions are at ifeent Embedded Systems fs. Problem is then aut only of schedoling of cxmcurrent procesins instructions om ilferent processins but aly scheduling OF concument processing instructions vm cath supercar unit Md pipeline inthe pressor. 5. Hardware scheduling issue, for example, whether static scheduling of hardware (processors and memories) is feasible r not its simpler and is use depends onthe types of insrutions when it des rot affect the system performance). 6, State scheduling ise (eg. when the performance is nut fected and when the processing setions sve predictable and synehronous) 7. Synchronizing issues synchronization means the use of interproeessor Ur process communica {APCs} such that there is» definite oder (precedence) in which the computations are fired any processor ina multiprocessor system (IPC is a message oF signal to another proces OF PUES 0 that it can proceed futher. Section 7.9 will describe the IPC in detail), 8, Dynamic scheduling ses (the performance is alfected when there ar erupts and when the services to the tasks ae asynchronous. It ica relevant when there is re-enpive scheduling hat is also asynchronous). 9. Scheduling ofthe instructions, SIMDs single instruction multiple data). MIMDs (mui insevsions and mille data) and VLIWs (very large istration words within each pencess ad sched them for each processor. “There are several methods of scheding and synchronizing the execution of insieuations, SIMDs. MIMDs and VLIWs inthe system, In a mltiprocesso system, scheduling is done afer analysing the scheduling and synchronizing options forte concurrent processing and scheduling of instructions, SIMDs. MIMDs and VLIWS, Consider two processors PA and PB, interfaced with the memory in system. Case: Processors sie the ve address spueethyoxgh & common bus, called tight coupling between processor, Cuse 2: Prucesors ‘ave different autonomous adress spaces (ke in a network) as wells shared dts sets and arrays. called ‘ose coupling. Figur 6, 2(a and (O) show both the eases. Case: Processors share the menyxes in shemtive vusrchitectire,forexample,thre-dimensional mesh, rng. eri tee in plac a shared bus betwee the Fterent tightly coupled processes. Processors process eoncurenty a fellows Ty One way of concurrent processing isto schedule each task that itis exeevtedon diferent prncessors and synchronize the tasks by some inlerprocessoe communication mechanism 2. The second way is, when an SMID or MIMD or VLIW instruction hs diferent data eg. iferen ‘veicients in Example 6.5) cach ask sprocesse on diferent processors (tightly couple processing) for different data, This is analogous (othe execution of a VLIW in TMS320C6. a Texas Insiruments DSP series processor It employs two identical sets of four units and a VLIW insiruction word can be within 4 and 32 bytes. 1c has insirvetion level parallelism when a compiler schedules suet that dhe processors run the diferent insu ution elements atthe different units in parle Note: The compiler does stare schedulns for VLIW. Static scheduling is one in which a compile compiles such thatthe codes are run on different processors or processing units as per the schedule decided and this schedule remains static during the progrem cum even if a processor waits for others to Finish the scheduled processing. A 3, Analternte way is that tas instruction i executed om the same processor or eierent instructions of 1 task can be done on different processors (loosely coupled). A compiler schedules the various, instuetions ofthe tasks among te procesoes at an instance Program Modeling Concent [2a] > of p Different ¥ " Taskor vu | {___ , a Fete Ly | shored or Unshaed | seus Fig. 6.12 (a) Tightly coupled processors sharing the same address space while processing multiple tasks (b) Loosely coupled processors having separate autonomous address spaces as in a network as wel as shared address space for data sets and arrays, 6.4.2 Model of Unfolding SDFGs into Homogeneous SDFGs 'An SDFG models the delays wel asthe numberof inpots and outs (Section 6.2.9). The eds directed Toa civles ae assumed io ave a physial nomory buler and il the butler has the data. de compton do hot fire. When there is only one token ate ipa. and one athe ouput, an SDEG is alld homgenous SSDEG (HSDFG) Figure 6. ai show sling of computations by an SDEG. Figure 6.134b) shows an SDFG representation after unfolding the SDFG in Figure 6,13(a, The dot and label ever the edge show delayed wo momber input wens at vere Y. Fr example, suppose thatthe outputs from vertex X” (ast of computations) isa and input vo Y" (another sot of competitions) is also 3 An SDEG can thesefore unfold into a HSOFG. An SDF graph ean be ‘nfo ints ne or more HSDFGs. Two vertices ean be connected by to cr more edges inthe HSDF raph ‘An HSDF graph wll atraly have mire vertices and edges than an SDFG because only ome tokens perited ‘When there is an indefinitely long data sequence, SDFG-based modelling andthe consequent unfoling Jimo the HSDF graphs helps. For example. HSDFGs applied to the computations ofa fast Fourier vansform for for coding voice data, An HSDF graph can alo effectively model an IPC (imerprocesr communication) ‘raph, All computations are static scheduled in HSDEG execution at each vertex (ring elements for the computations and creating another set of output tokens). Let there be a Sequence of computations that are fired atthe verioes. Let precedence ina directed graph define the computations order by which the vertices are placed Fist, then next, and then next (o next. A sequence on one prosessr among the st of processors can be delayed tthe arc. Input rom another processor initial token) can also te delayed. A SDF ‘model program then translates into @ number of parallel concerent or sequential model programs using SDFGs, 292, Embedded Systems + Ego fora Pyszal Memory Bufo Soe apis and Provide fa ©) NS “ (a8 slay (#2, 20 \ Pe Renta tem ae “Sy nite ny Pi,A0 <0 oweantecuputron; : (\ BT An Input Port By Supersipt means toute Token ané 2 meena Second 2 seman (uiput ken that res ator 2 day wih respect othe est (Deine nt! then PF conve) o @ (a) Armodeling of computations by an SOFG. The dat and label over the edge show delayed ‘wo number input tokens at vertex ¥(b] Ahomogencous SDFG representation ater unfolding the SDFG (c)An APEG representation from an HSOFG after removing the delayed edge ig, £3 Mutiprocessor system computations and thei fring instances can be modeled. Modeling simplitis the programming, schedalingand synchronizing of the processes. HSDFG model are lke an SDFGS but have ‘he feature that there sony one token that delays along an edge (ac or arrow) because there is only one token at input, and one at output. 4.3 Model of Unfolding HSDFGs into APEGs Acrylic precedence is apeodence of vertices ina directed graph such that there ae no delaysat the aes nial tokens (slays are taken offrom an HSDF graph, an aryl precedence expansion graph (PEG) is obtained -APEGS are important for scheduling in multiprocessor systems. An APEG not only has afong the ate, stating inputs identical to the output from 3 revious vertex, but also no delaying for the token. Hence, the execution is smooth along the arc with no interpraessoe communication time. An APEG-based algorithm becomes the simplest to sdedle such thatthe precedeoce constraints inthe algorithm remain the same 2 before. Figure 6.13(c) shows a corresponding APEG that isa graph with no delay, It dives from a HDFG [Figure 6.13(b)} 0 SDFG fFigure 6,13(@)], ‘A task-level eoncurent process as well as an IPC graph can be modeled using APEGs and HSDFGs, A thread running on one processor modeled as APEG can pass a control to anothe by blocking itself or by sleeping, but the Sequence and process flow along the APEG remain inact. Example 6.1 explains this, Program Modeling Concepts 293 Example 6.11 Let V1, Vas and V4 be the computation vets assigned 1 proestoe PA. Let V. Vs. V5 be the computation vertices asgned to prcesot PB concurently processing with PA. An TPC is needed wen algorithm or set of computations) V" cannot proceed il here fa message (token) from V" LeLIPC be between V" and VTi synchronizes the processes at PA and PB trough the IPC. Figure 6.14 shows one APEC and one HSDFG with an IPC to PB fom PA. APEG models are such that there are na delays during execution a any stage in an APEG or chain of ‘APEGs. Complex problems are therefore first modelled asthe SDFGs, then SDFGs are unfolded ito HSDFOs and HISDFGs are separated into APEG Processing sas per precedence constrains between the -APEGs. APEG-base algorithms become the simplest to schedule but precedence constrains in he algorithm mong its APEGS remains the same as before, (Gree vertex or Computations at Po PS “rected arom or ne Outputs ares to = ¢ *6 vi ws. a: Processor ‘put V5 Vat i PB: Presser recov as gt aera (aay ano ton te ‘computations Sa iy. 614 A twosprocessor system with one acrylic precedence expansion graph and one homogeneous synchronous dataflow graph with an IPC to PB from PA 4.4.4 Applications of the Graphs io Multios Partitioning and Scheating F Syste ‘When there ae multiple processors in parallel, the paritioning of a program i done as follows. 1. There are minimum numberof IPCs so that the total me of IPC delays (waiting periods) minimized 2. There is toa balancing. Bach procesor has the leas waiting tine by sharin the processing load. 3. The performance cost minimizes. Peeformance cost means the execution time required (t) for ‘compatation forthe rokens and delays atthe edge (communication time), i) the computation time before fgg (computations) by a vertex (transition) and (i) context switch time. Consider Figare 6.15 verve. At each vertex computations occur such thatthe precedence constraints ‘maintain (remain intact). Te graph ofa program thus patton into the functions or tasks or threads. One of the tre following strategies can schedule a program for running, 294 Embedded Syetame 294) ye | Bach ask or Funeion i cucu on signal prices, Fach task or funtion is executed on diferent processors at diferent periods, Insactons «Tour elfercit sks are pation on tw pressor, {nstrctons of our ifrent ask are partion sd cholo two processor difeenly in diferent periods [Figures 6. 15(a 0 (] show these Four putiioning and scheduling strategies. Processor Task = 1 Prnceesor bE) O-©- © conten ee ee Fl © @® © ore a (VASO amon ee ead 2 pect ee ie ., o © His an nsctionn_V; fe taka i colon ard ow lento mai Aan ad bic wn tho Corespandng Eament 8 Procssor Ci) G2) wea. 6a) Fesvaining nstuctn of V5 Thea Tok Pe Process a + toek2 @ |g. 6.15 (a) Each task or function is executed or an assigned processor (b) Each task or function 's executed on different processors at different periods (c Instructions of four different tasks are partitioned on two processors (d) Instructions of four different tasks are Partitioned and scheduled on two protessors differently during different periods Program Moding Concepts 2. Fach st of data is pattioned in a VLIW instuction sod is executed an te diferent process ‘shich execute the same program. Cansidor a mati addition jrocess. Bach rw can be added on iilfernt mocesor when the dat ofthe ows ae patton aon he roses. Suh dita partitioning js peterted when processing a DSP-VLIW. ‘A cownbinod patitioning is done bath athe data level as well a the task fr Fanotion) level. Different functions themselves may fun concurteaty on diferent processors ut a the micro or stomic-level data is partitioned ad te instucions are run. Partitioning and scheduling of vertices can be done in a number of ways. () Each ask or Function is ‘executed ons assigned processor (i) Fach task o Function is executed on diferent processors at differen ‘periods. (ii Instructions of four different tasks are paitioned on two processors.) Instructions of four diferent tasks a parttoned and scheduled on two proceso ilferenty in diferent periods. (v) Data ‘partitioning in ease of SIMDs, MIMDs and VLIWS. ~ 6.5 UME MODELLING Recaptute Section 5.5. The concept used in object-oriented language ae also used in software designing bj rine snag ial me or ‘Object-oriented design is dove when there is a ned fr reusability ofthe defined software components 8 objector set of objects (eusable components). The new component can be abstracted from the exiting, New components and objet designs are created by the object inheritances and polymarps. Tec i information encapsulation within 3 designed eomponent or objec. ‘A signed component object salsa charateized hy is entity (a reference tit that hol its i ‘unl bch viour), hy is sae (ts designs or data, popes elds, atetbutes and algorithms) and by its behaviur (method or metus that ean manipulate the sate ofthe design) 3. New object design are created rom the instances oa designed class. Cass defines the state atibues, ‘operations and behaviour of edesign concep. has intra ase Level elds fr ita nd Bchaviou. Te defines the ways of using the designs. 44. Adesigned class can then create many component abject (designs) by copying he group and aking ‘designs functional. Each design isa functional design. Each object design can ileface with other ‘designs co proces the salsa per the defined behaviour 5. A set of classes then gives the complete sowie design fora system, UML i unified (common) modeiny language for any general system for which object-oriented analysis Ad desiga arc feasible and which canbe abstracted by models. Unification in UML means its common applicability 1o many designs o¢ processes. We can then model the following by a similar set of diagrams: (3) software visualizing, (i) data designs), (i) slgoitims desgn(), (iv) software designs), () software specications, (i) software development process, (vi) an industeal process. UML isa language for modeling. Details ofthe Language canbe learnt from a standard textbook, [For ‘example, "The Unified Modeling Language User Guide" by Grady Booch, ames Rambaugh and Ivar Jacobson, ‘Addison Wesley, 1999,] UML fea es andits applications in designing of embedded systems an be understood {rom the Following bret description. Figure 6.16(a) 0 (1) shows representations of sx haic UML elements: class, package stereotype, objet, snonymous object and tate, Table 6.2 gives als of these and their description.
  • You might also like