Embedded Systems

Dedicated to UFORIANS

Acknowledgement
         
                       I sincerely thank my friends for their continous encouragement in producing this document in electronic format. Also I kindly thank Sharda Group of Institutions, Agra for their whole hearted support.  Last but not the least I simply thank the Final CSE students of Anand Engineering College for their patience.

Embedded Systems:- (FIRST EDITION)

     Embedded systems are hardware and software components together designed to solve the specific application requirements.   Embedded systems are application specific and also part of the larger system.
      Pure hard-wired systems are not embedded systems but software component is a must.
      For example, a fan with switch and regulator alone can be considered hard-wired 
system.  Microcontroller with software algorithm to monitor and control the fan rpm in
accordance with required room temperature clarifies the use of embedded system.

Components of Embedded Systems:-

     Embedded systems are build up of
      (a)  Microprocessor or Microcontroller or Digital Signal Processor
      (b) Field Programmable gate array or Application Specific integrated circuit
      (c)  Analog-To-Digital Converter/Digital-To-Analog converter
      (d)  Application software running in ROM/FLASH
      (e)  Real-Time Operating Systems
      (f)  Stable Clock
      (g) Communication Interface

Applications of Embedded Systems:-

1	Automatic Teller Machines (ATM)
2	 Cellular telephones and telephone switches
3	 Computer network equipment including routers, timeserver and firewalls
4	 Computer printers
5	 Disk drives
6	 Engine controllers and antilock brake controllers for automobiles
7	 Home automation products like thermostats, air conditioners, sprinklers and
  security monitoring systems
1	 Hand-held calculators
2	 Household appliances including microwave ovens, washing machines, television
  sets, DVD player/recorder
1	 Inertial guidance Systems (Appolo Space Craft) flight control hardware and
   software and other integrated systems in aircraft and missiles.
1	 Medical equipments
2	 Measurement – digital storage oscilloscope, logic analyser and spectrum analyser
3	 Multifunction Wrist watches
4	 Personal digital assistants, small handheld computers
5	 Programmable Logic Controllers (PLC)
6	 Videogame consoles and hand game console
7	 Entrance security systems
8	 Unmanned Space probes
9	 Computerized traffic lights
10	 Electronic voting machines
11	 Credit card readers
12	 Intelligent air-bag systems
13	 Digital cameras

Real Time Systems:-

      Real-Time systems are sub-class of embedded system with 'timing constraints'.  In real time system missing the deadline is just as bad as a wrong answer.  Two categories of real-time systems are
    (a)  Hard Real-Time systems
    (b)  Soft  Real-Time systems
     Hard real time systems has more severe consequences of missing deadlines

Firmware:-

     Firmware is the name of software that is embedded in hardware device.
Example: BIOS (Basic Input and Output Services)

Cross-Compiler or Cross Assembler:-

     Cross compiler or cross assembler produces object code for processor different
from the proecessor in which it is executing.
     Ex: Keil 'C' cross-compiler for microcontrollers
     This compiler executes in pc and produces object code for wide variety of microcontrollers.

In-Circuit Emulator:-

     In-Circuit emulator is a hardware device consists of 'Adaptor Unit' sits between host
computer and the system to be tested.  The unit emulates the CPU such that systems point
of view it has a real processor fitted from the host computer point of view.  The system under test is full controll, allowing the developer to debug and test code directly.

Host Based Simulation:-

     Simulation enables the developer to unit test significant portions of their application
either prior to the availability of target hardware.  Some of the advantages.
•	In larger groups the need of target for each developer is avoided
•	Ensuring the stability prior to integration
•	Real-hardware is not stable

Microprogram:-

     A microprogram is a program consisting of microcode that controls the different parts of
a computer's central processing unit(CPU).  The memory in which it resides is called control store.  Microprogram  provides the bits to control CPU's conrol signal.  The fundamental
advance is that cpu control becomes a specialized form of a computer program.  In this transforms complex electronic design challenge (the control of CPU) into a less-complex  programming challenge.  
     A microsequence picked the next word of the control store.  A sequence is mostly a counter but usually also has some way to jump to a different word in the conrol store 
depending on some data.  Usually the data from the instruction register and always some part of the control store.  The simplest sequence is the register loaded from  a few bits of control store.

Characteristics of Embedded Systems:-

     Characteristics distinguishes embedded systems for better understanding.  Following are the features or attributes or properties explains the nature of embedded systems.

     a.  Application Specific
•	Embedded Systems are build for specific application which gives unique identity like 'Microoven' or 'pacemaker' or 'pager'
•	Application is known priori
•	Flexibility is provided through limited reprogrammability
  
     b.  Digital Signal Processing Functions
          All the  processing are done in digital domain to enhance the accuracy and precision 
          of processing.
          Filtering functions for low-pass, high-pass and band-pass filters
          Encoding the signal for clock synchronization and security
          Modulation | Demodulation for long-distance transmission
          DFT for signal analysis
     c.  Reactive
           Responds to the change in the external stimulus or phenomenon
           Constraints are must for the system functionality
      d.  Real-Time
           A real-time system reads inputs from the plant and sends control signals to
           the plant at times determined by plant operational considerations-not at times limited  
          by the capabilities of the computer system
          Hard Real-Time:  These are systems that must satisfy the deadlines on each and                                
          every occasion.
           Ex:  Temperature control loop of the hot-air blower system.
           Soft-Real Time:  These are systems for which an occasional failure to meet a 
           deadline does not comprise the correctness of the system.
            Ex:  An automatic teller machines the response time obtained between 12 and 2p.m. 
            On a friday is very different from that at 10 am on a sunday.
        e.  Distributed
            Distributed systems, each unit is carring out essentially similar tasks to all the other 
            units and 
             In the event of failure or overloading of a particular unit all or some of the work can 
            be transferred to other units i.e., work is not divided  by function and allocated to a 
            particular computer instead the total work is divided up and spread across several 
            computers.
            Each computer needs access to all the information in the system, high-bandwidth 
            data highways are necessary
f. Cost and power Consumptions:-
      Slow processors and small memory to minimize cost
      Not only clock speed but communication interface also. Ex: Synchronous serial interface
     Real-Time constraints with limited hardware resources ex: No disk drives, OS, Keyboard or Screen
     Flash drive replace rotating media
     Small Keypad and LCD screen may be used instead of PC's keyboard and screen

Classification of Embedded Systems:-
     Embedded systems are classified into
     a.    Microprocessor based versus Microcontroller based
            Microprocessor based system has Van Neumann Architecture where there is a
no separate program space and data space.  Microcontroller  based system has Harvard            architecture where program space is different  from data space.

            Microprocessor based system has separate timer IC communication IC and ADC & DAC IC.  Microcontroller system has timer, communication, ADC & DAC & ROM in the single IC package

      b.    Fail-Safe Versus Fail-Operational
             Anticipated faults are faults which the designer can anticipate and hence design in tolerance.
            A much more difficult and insidious problem is that of faults in the design of the system.  These are by definition 'unanticipated faults'.
            Fail-Safe system goes to the known system state when the fault occurs.  On the other hand when the system faults occurs system can be degraded gracefully and operational

        c.    Event-triggered Versus Time-triggered
          Event triggered systems where actions have to be performed not at particular times or time intervals but in response to same event.  Ex:  Turning off pump or closing a valve when 
the level of a liquid in a tank reaches predetermined value.

          Events occur at non-deterministic intervals and event-based tasks are aperiodic tasks.  Such tasks have deadlines expressed in terms of having start-time or Finish times.
  
         A process plant operates in real-time and thus we talk about the plant time constants.
Time constant is the measure of the time taken by a plant to respond to a change in input or load.  Time constants may be in hours for some chemical processes or in millliseconds for an 
aircraft system.

       For feedback control the required sampling rate will be dependent on the time constant of the process. The shorter the time constant of the process, the faster the required sampling rate.

       d.    Hard Real time  versus Soft real time 
              Occasional missed  sample would not seriously affect the performance neither would a variation in sampling interval such that the inequality 9.95 <= Ts <= 10.05 ms with a mean of Ts = 10 ms was satisfied.  The system would not be satisfactory for hard-real time.  However, if the sampling interval Ts was in the range 1 < Ts < 1000 ms with a mean of 10ms over a 24 hour period.
     For soft real time systems at busy times wait of 10 minutes, even if it is achieved with a mean response measured over a 24 hour period of 20 seconds.  A typical soft realtime systems has mean response measured over 24 hour period of 15 Seconds, with 95 % of requests being satisfied within 30 seconds and no response time greater than 60 seconds.

       Hard                           			Soft

Periodic             Aperiodic                                               Periodic               Aperiodic
(Cyclic)              (Event)                                                    (Cyclic)                (Event)

tc(i)  = ts +/- a    te(i) <=te                              1/n SUMtc(i) = ts+/-a    1/nSUM te(i) <=Tc

tc(i)  the interval between the i and i-1 cycles
te(i)  the response time to the ith occurrence of event e
ts  the desired periodic (cyclic) interval
Te  the maximum permitted response time to event e
Ta the average permitted response time to event e measured over some time interval T
n  the number of occurences of event e within the time interval 
a a small timing tolerance

e.  Safety related system versus safety Critical
     Failure of operation of safety related system leads to economic loss
     Safety critical systems failure will be catastrophic
    
f.   Guranteed response versus Best-effort
g.   Resource Adequate versus Resource inadequate

Requirements of Embedded Systems:-

     Following are the requirement of embedded system 

a.   Functional Requirements
      Data Collection – Using sensors and response time of sensors and process range of sensors.
   Direct digital control- Actuators used as final control element
   Man-machine Interaction – Control panel designe

 b.   Temporal Requirements
        Tasks deadlines
        Minimal latency
        minimal error detection
        Timing Requirements
        Human Interface  - LED can be used for display to indicate scanning and in turn healthiness of operation.
c.  Dependability Requirements:-
     Reliability – Probability that a system will provide a specified service until time t, given that the system was operational at t0.
R(t) = exp(-LAMDA*(t-t0)); LAMDA – constant failure rate

      Maintainability is the mean time to repair in terms of repair per hour
      Availability , A = MTTF/(MTTF+MTTR)
 MTTF = 1/LAMDA, MTTF -> Mean time to failure

     99.999% availabiliy is 5 hours of failure over 365 days.

     Safety – system has to be protected rom natural calamities like fire.
     Security- system locks has to be there to give authorised access at the physical.  Password and bio-informatics can be used at higher level of authentication.

      d.  Processing power in terms of 25 MIPS or 40 MIPS and register width 8 or 16 or 32 or 64 bit
     e.  Memory whether RAM/ROM/FLASH and register width of processor establishes upper limit of the amount of memory.
     f.  Development  Cost – hardware and software design processes cost (one time cost)
    g.   Durability or expected life time
    h.  Diversity to avoid common point of failure.  One system uses microprocessor and c-language, the other redundant system should use microcontroller and ADA-language.
i	Harsh environment – should be tested for lightning and EMI/EMC, seismic qualification , temperature, gravity, humidity, radiation etc.,
j.     Ergonomics – Human engineering for ease of use and also attract aesthetically.

Timing and Clocks – Embedded Systems :-

The source of time:-
      The Babylonians started the practice of dividing the day and night into 12 parts, giving us the familiar 24-hour a day.    They also had a sexagesimal fascination that begat 60-minute hours and 60-Second minutes.   The french tried and failed to rationalize timekeeping by introducing decimal time in the late 1700s, with three 10-day decades per month, two 10-hours sections per day, 100 minutes per hour and 100 seconds per minute.  France rejoined the rest of the world with Babylonian standard time keeping.
     When railroads reached continental scale, consistent, time become more than a convenience.  After all, how can anyone make the trains run on time when each station sports a different time>
      The 1884 International Meridian Conference established Greenwich Mean Time (GMT) as the world wide standard and introduced the notion of time zones.  With two exceptions, each zone occupied 15 degrees of longitude and represented one hour of the sun's travel around the earth.  The zero meridian passed through Greenwich, England, around which the conference centered the zero-th time zone within each zone, local time became equal to GMT plus or minus on offset determined by the zone's longitude relative to greenwich.  This ensured all clocks showed a consistent time throughout each zone.  The conference defined two zones at GMT +12h and GMT -12h to occupy 7.5 degrees each.  There are 25 time zones, 12 leading and 12 lagging GMT, plus the zero-th zone.    A current time zone map shows 37 time zones with time offsets ranging from -12 to +14 hours.  Nations may also define their own clock offset.
Daylight Savings Time:-
     In addition to setting their own zones, boundaries and offsets, many nations use Daylight savings time that shift more daylight into hours when most people are awake.  Generally, local time steps forward one hour in the spring and backward one hour in autumn.  The exact dates and amounts remain under national control, with the usual results.
      The radio station WWVB transmits the current coordinated universal time (UTC) in machine-readable BCD at 1 bit per second on a 60 KHZ carrier frequency.  The entire time code repeats once each minute, with 43 data, 10 unused and 7 framing bits.  The 60 KHZ carrier provides a phase reference and BCD digits give the actual time at the start of each minute. There are radio-controlled watches and clocks have adjustments for '24 time zones'

Time Concept:-

     Do we exist in time or is time part of our existence? Is time an intrinsic property of nature? Platonism time is an external phenomenon.  Thus simultaneous events happens at the same exact absolute time.  There is an underlying assumption that time is progressing, even if no changes can be observed.
     Is time a construct which is based on observable events?  Reductionism time is the observation of distinguishable events.  If the observed events are regular a useful time reference can be constructed.  If all possible observers detect one event before another one they are said to be in sequence.  If this cannot be assumed for all possible observers they are said to be simultaneous.
     Thus notion of time is reduced to notion of causality.  A mathematical notion of time, real clocks have limited resolutions and are running asynchronously.  A physical notion of time, 1676 Romer proofs the existence  of the speed of light ( and measures it).  In 1687 Newtons 'Principia Mathematica' assumes on absolute time , independent of space and independent of events.  In 1905, the concept of absolute time is destroyed first by Einstein.  In 1915 Einsteins general theory of relativity eliminates the independence of time(space) and events in time(space).  One principal consequence for measurements of time: clocks under higher gravity or in faster observation frames are slow.  Practical consequences, clocks in satellites need to be adjusted accordingly. 
      How real is the real-time? 'Real'-time – usually time as given by extenal sources.  Engineering  it is of no importance how time is defined and understood as long as an 'external reference'  is given and used as 'real-time'.
     Embodied phenomena are those that by their very nature occur in real time and real space.  Phenomenology, the phenomena of experience as the central aspects and building blocks of understanding (rather than 'Finding the truth') applied to and trying to combine aspects of  'Ontology' – about the nature of being and categories of existence and 'Epistemology' – the study of knowledge.
     Edmond Husserl, founder of phenomenological tratiditon, as a trail to establish modern science which is firmly grounded on the phenomena of experience(instead of being an abstract mathematical construct).  Phenomenology originally as a method to example the nature of intentionality, coined the terms, 'Noema' – the objects of consciousness and  'Noesis' – the mental experiences of those objects.  Husserl rejected pure abstract and formalized reasoning.
     Martin Heidegger, moved phenomenology fro a discussion about mental phenomena separated from the physical world to a discussion about connected physical and mental phenomena.  Moved the central questions from ' epistemology'  to  'ontology'.  The meaning is not in the head , but in the world. 'Dasein' – being as inseparable from the world in which it occurs'.  Being as purposeful and active.  The world as an unconscious but accessible background.  Zuhanden (ready-to-hand):   'equipment as a part of actual interaction with the world'.  'Vorhandein' (Present-at-hand') 'equipment as a conscious model'.
      Embodiment is the property of any engagement with the real world which makes this engagement meaningful.  Embodied phenomena are the essence of meaningful interaction.  Real-time and embedded systems are the technical instantiation of embodiment.  
     There is no such thing as 'intelligence', 'autonomy' or any other cognitive process,  which is independent of physical environment.  There is no such thing as a universal system or body (Mechanical design, robot, device, ...) which is operational in all physical environment.
     Meaningfully embedded systems are part of an 'ecological niche'.  The operational environment is supportive and employed by the system.  The embedded system  is constructed as a part of the operational environment and accordingly to the taste.
     The task is meaningful considering the morphology and cognitive ability of the syste as well as the response from the environment.  Embodied skills depend on a tight coupling between perception and action up to the level where the distinction between both can become difficult.  Tight coupling between perception and action means to operate under real-time constraints and to construct meaningful morphologies.

 Timing Standards:-

    Two internationally accepted standard of time are in use.  One deals with quantum aspects and other astronomical.

     (a)  International  Atomic Time (TAI)
     TAI defnes second as 9,192,631,770 periods of radiation of a specified transition of the cesium atom 133.  TAI is a chronoscopic time scale ( with no discontinuities).
    The clock stability of 'NIST-F1' maintained by National institute for standards and technology, USA is 1.7X10-5 i.e., neither gain nor lose a second in 3 million years.
     Quartz crystal oscillators are stable to about 1 second over few days.
     (b)    Universal Time Coordinated (UTC)
      Time is based on rotations of earth relative to sun.  One second is 1/86400 of a mean solar day.    It is not a chronoscopic time scale.
     UTC is regularly updated to conform to seconds (i.e.,) no of seconds in an hour to the TAI standard.  The difference between UTC and Tai is less than 0.5 second occasionaly lead seconds are inserted.
     Internationally we are following Gregorian calendar and most of the countries shifted from Julian calendar (which intoduced 365 ¼ days a year) at different periods.
    In India the calendar is based on lunisolar which takes in to account rotation of moon around earth and rotation of earth around sun.  Gregorian calendar is a solar calendar.

 Interfacing With Time:-

     Programming primitive delay alternative to 'busy-wait' and interrupt.  Delays can be absolute delays, relative delays and zero delays.   Delay time calculation is not atomic giving only relative delay.  Delaying a loop on average for 5 seconds if sporadically longer than 5s.  Zero delays allows task-switch.  Absolte, Relative delays are available in Real-Time Java, Pearl, Ada 95 and many other process-oriented languges.  Only relative-delays ae available in same 'low-level' environmet in POSIX (nano sleep). Only absolute delays are available in same 'harder' real-time environments.  Occam2, Ada95.
     Timeouts as an alternative to busy-waiting and infinite blocking.  Timeots are implemented in shared variable communications.  Semaphore, Conditional critical regions, monitors, protected objects, message passing between process, Asynchronous and Synchronous message transfers, Remote procedure calls, remote objects.  Timeout  is actions common realtime system concept.  Timeliness is  often more important than precision.

 Specifying Timing Requirements:-

    Temporal scopes can be: Deadlines (absolute, elapse or execution time) can be periodic eg., Controllers, Samplers, Monitors.  Aperiodic eg., 'periodic on average' tasks, burst requests.  Sporadic/Transient – e.g., mode changes, occasional services.  Hard – Single failure leads to severe malfunction.  Firm – results are menaningless after the deadline  only multiple or permanent failures threaten the whole system.  Soft- results may still be 'useful after the deadline' distinction is not so obvious in practical systems.
    Language support for specifying temporal scopes POSIX, ESTEREL, ADA95, Real-Time JAVA, Crl, Realtime EUCLID.

Satisfying Timing Requirements:-

     Satisfaction of timing constraints is related to the choice of the scheduling function.  Two paths towards fulllfilling real-time requirements.
     (a) Complex Systems Oriented approach
      System identification and compile-time analysis, Calculate or limit statement durations, calculate or limit iterations and recursions, analyse potential dead or life-locks, calculate schedulability.  In run-time analysis and checks follow dynamic scheduling schemes revalidate schedulability.  Check for all constraints and assertions at run-time.  Supply of fault-tolerant behaviours like error recoveries, mode .

(b) Real-time logic approach
     Reduce the problem ie.s reduce any asynchronous, analogue, dynamical, fractal, jitter, drift or failure-affected parts of the system to a fully synchronous and discrete system.  Formulate the specification on the basis of the reduced synchronous system.  Verify the reduced synchronous against the specifications.  Compile the reduced systems to an actual system the resuming actual system will be executable on a real machine and employ real devices.  Re-check the actual system (e.g., by means of a complex systems approach).

Current Timing Hardware:-
a. Crystals
          They are small block of quartz (Silicondioxide).  Quartz crystal is a type of material known as piezoelectric.  This crystal generates voltage across it when it is stressed( Compressed, Stretched, twisted).  This effect is utilized in microphones. The reverse effect is utilized in generating sound from speakers.
          Block of given size will vibrate at a given (and fixed) frequency. It can be used as an 'Oscillator' to generate sine wave which in turn can be used to generate timing signals for microprocessor.
          Crystals require drive circuit to make them go.  Most processor has internal oscillator circuit and expects external crystal alone to be added.

 b.  Clocks
          All microprocessors require clock.  A clock is an output from the oscillator that runs the processor and all system event relate to the clock.
          Two ways of getting clock input for the processor.
        Oscillator Module:-
            Four pin components provide square wave clock output at given frequency requires only power and ground.
 Crystal with Bypass Capacitor:-
       When the microprocessor is available with oscillator circuit, crystal with by pass capacitor. Bypass capacitor removes higher-order harmonics of the oscillation.

Power versus Speed
      Most of the current draw of digital system occurs during transitions of state, in other words during the clock edges more frequent clock edges more current is drawn up.
      A processor with minimum clock speed of zero  is said to have static operation of processor. Processor can have its clock stopped and still be able to resume operation at later time wit no ill effect.
      In Laptop systems, 30 seconds idle clock slowed to  KHZ range; Minutes of idle clock slowed to HZ range.
     In Palm computers 'event-driven' approach is followed in between event the clock is slowed variable speed modes of clock are supported with SLEEP and HALT  in some processors and in others SLEEP, NAP, DOZE, SNOOZE for different sleep state.
      PC s  currently use four system timers for different tasks, each with its own distinct set of attributes that make working with all of the timers confusing .  The timers currently in use are as follows:

    8254 Programmable Interval Timer (PIT)
            8254 PIT was introduced in the IBM PC in 1981.  It has a resolution of 1 millisecond and supports both periodic and aperiodic modes.  However, because reads from and writes to this hardware require communication through on IO port, programming it takes sevaral cycles which is prohibitively expensive for the OS.  Because of this the aperiodic functionality is not used in practice for this reason, this timer is only used in periodic to provide the periodic clock interrupt on uni-processor systems.
    Real-time Clock(RTC)
         In 1984, the IBM-AT shipped with the first real-time clock(RTC) in addition to the 8254like the 8254, the RTC has a maximum resolution of 1ms and supports periodic and aperiodic modes as with the 8254, communication with this hardware ocurs through an IO port and is therfore prohibitively expensie.  The high cost of communicating with this clock precludes the use of its aperiodc functionality.  In addition to these limitations, the RTC was designed to generate.  Advanced configuration and power interface (ACPI) interrupts on ACPI capable systems, which degrades the system performance.  The RTC used in periodic mode to provide the system profiling interrupt on uniprocessor systems and the clock interrupt on multi-processor systems.
      Advanced Programmable Interrupt Controller (APIC)
          APIC timer has many of the capabilities of the real-time clock and was designed to be used to synchronize multiple processors, but it has poor resolution and the clocks silicon is sometmes very buggy.  Because many of todays systems still do not have an APIC timer, it is not used by default.  More importantly however, this timer is subject to pausing during processor powe management in some implementatons, making it useless for keeping reliable time on modern systems.  For this reasons the timer is seldom used.
PM clock:
     The ACPI timer, also known as the PM clock, was added to the system architecture to provide reliable timestamps  independently of the processors speed.  Because this was the single goal of this timer, it was designed to provide a time stamp in a single clock cycle, but it does not provide any other functionality.

The 8284 Clock generators:-
       The clock generator supplies the multiphase clock signals that are needed to drive the microprocessor and the peripherals. Its base frequency is 14.3128 MHZ.  The other chips generally divide the base frequency by a constant to obtain the frequency they need to accomplish their tasks.  The standard PC family's 8088 is driven at 4.77 MHZ, One-third of the base frequency.  The internal bus and the 8253 programmable timer use a frequency of 1.193 MHZ, running at a quarter of the 8088 rate and one-twelfth of the base rate.

Reasons for a New Timer:-
     Systems today need aperiodic functionality and higher precision.  Without these two features, systems will be unable to met the requirements for future multimedia applications and other time-sensitive applications.  The new timer that provides this functionality will replace the 83254 timer, the RTC, the PM clock, and the APIC timer and will enable removal of some of the legacy and redundant hardware in chipsets.
Aperiodic Functionality:-
     Microsoft windows XP uses a periodic clock interrupt to keep track of time, trigger timer objects and decrement  thread  quantum. When windows XP boots, the typical default clock interrupt period is 10 ms , although a period of 15 ms is used on some systems.  That means that every 10 ms, the operatig system receives an interrupt from the system timer hardware.
       When the clock interrupt fires, windows performs two main actions, it updates the timer tick count if a full tick has elapsed, and checks to see if a sheduled timer object has expired.  A timer ick is an abstract notion of elapsed time that windows uses to track the time of day and thread quantum times consistently on most systems, a timer tick repreents 10 ms but some systems use 15 ms as the timer tick period.  By default the clock interrupt and timer tick are the same, but the OS or applications can change the clock interrupt period, while the timer tick period never changes.  So a timer tick always represents a constant period, regardless of the period of the clock underneath.
       In addition to maintainng timer ticks, when a clock interrupt is fired the system also checks to see if a timer object has expired. A timer tick is an sbstract notion of elapsed time that windows uses to track the time of day and thread quantum times consistently on most systems, a timer tick representas 10 ms but some systems use 15 ms as the timer tick period.  By default the clock interupt and timer tick are the same, but the os or applications can change the clock interrupt period, while the timer tick period never changes.  So a timer tick always represents a constant period, regardless of the period of the clock underneath.
     In a addition to maintaining timer ticks, when a clock interrupt is fired the sytem also checks to see if a timer object has expired, and schedules a timer deferred procedure call(DPC) if one is found. Timer objects are used by the sstem to track deadlines and to signal applications when a deadline is reached.  For example a multimedia application that is playing sysnchronized audio and video may request that some code(for example, playing a sound) be executed in 233 ms. Windows keep track of this request by creating a timer object.  It then checks for the expired timer objects when a clock interrupt is generated.
With a 10 ms clock interrup period, the OS will play the sound 7 ms late.  The granularity of clock interupt is too great and end users perceive audio/videl synchronization problems.  Smaller clock interrupt period will degrade the system performance by the subtle efffect on the increased interrupt frequency on cache consistency and power management may be desired.
      If clock interrupt period was lowered to 1 ms resulted in 10 interrupts being generated between the times 230 ms and 240 ms while one interrupt was actually needed.  Soltion is schedule on aperiodic timer interrupt. In addition to performance benefits, a periodic functionality will also positively contribute to the achievable battery life of mobile platforms.
     Current timers theoretically have maximum resolutin of 1 ms and acheiwvable resolution of 2 ms with possibility of 1 ms late which gives dependable resolution to 3 ms.  Multimedia appliations however require an accuracy of atleast 1 ms. So current times are theoretically adequate for taodays multimedia applications, they are unable to meet.  This minimum requirement in reality.
     Embedded solutions and high speed soft devices such as soft DSL both require microsecond granularity.
 
The High Precision Event Timer:-
      HPET was developed jointly by intel and microsoft to meet the timing requirements of multimedia and other time.  Sensitive applications originally the HPET was called the multimedia timer (MM Timer).

Setup Time and Hold Time:-

    Set-up time is the time before whic data should be placed on the data bus to latch the data.  This time is mesured with respect to control signal.  
    Hold-time is the minimum time data should be placed on the data bus to latch the data to memory.  This is also a property of a control signal.

Granularity:-
     Minimum interval given by a clock is called granularity of  clock.  A clock with 10^15 microticks per second has the granularity of 1 Femtosecond using this clock cannot measure events at any smaller intervals ( in this case 1 femtosecond).

Clock Drift:-
     Clock synchronization is vital to the correct oepration of real-time systems such activities as voting and synchronized roll back assume that the clocks are synchronized fairly highly.
Mathematically speaking clock is a mapping 
      Ci: real time -> clock timers
      That is , at real time t, ci(t) is the time told by clock ci. The inverse function Ci(T) is the real time at which clock Ci tells time T.  Where it is important to distinguish between  real and clock times,  We will use the profixes "r" and "c" respectively.
      We seek from the clock of comuter essentially what we seek from a wristwatch-accuracy.  That is clock should not ain or lose time at too high a rate.  To put it more formally, it is necessary that the drift rate of a clock Ci

      P = Max[t,Delta] {  ( ci(t+Delta) – ci(Delta))/Delta – 1}

be as small as possible. The drift rate is the rate at which the clock can gain or lose time.  Conversely, if we specify P as the maximum drift rate of a nonfauty clock, we must have
(1-p)(t2 – t1) <= C(t2) – C(t1) <= (1+p)(t2 – t1)
The clock is constrained to remain within the cone of acceptability, shown as heavy lines.
Every Ts C-units we run some synchronizaton algorithm to simultaneously adjusts the clocks so that they all tell roughly the same time after adjustment.  The fastes tclock would gain P seconds per second while the slowest clock could lose up to  p seconds per second.  Thus over a period of Ts c-seconds, the fastest and slowest clocks would be up to 2PTs r-seconds apart.  Thus to synchronize either Ts or  P must be small. 

Synchronization:-
      Two clocks are said to be synchronized if the times they tell are sufficiently close.  More precisely, Ci and Cj are synchronized at C-time T if for some given Delta < 0,
{Ci(T) – Cj(T)} < Delta
     The  quantity { Ci(T) – Cj(T)} is the skew between clocks Ci and Cj at C-time T.
     A set of clocks S is said to be internally synchronized at real time t if every pair of clocks Ci, Cj belongs to S is synchronized  at that time and time told by each clock lies within the cone of acceptability.  The parameters of synchronization are the  maximum allowed skew Delta, and maximum allowed system drift rate Psys.  Internal Synchronization proceeds by the clocks exchanging timing signals and adjusting themselves appropriately.
     Since p <<1  for all good clocks,
           1- p = (1+p) ^-1
           1+p = (1-p)^-1
      To see this , expand (1+p)^-1 in a Taylor series

(1+p) ^ -1 = 1- P + P^2/2! + ...+(-1)^n * P^n/n!+...

For  P = 10 ^ -6 (1-P) – (1+P)^-1 = 10^ 12 Similarly for  (1-P)^-1

(t2 -t1)/(1+p)  <= C(t2) – C(t1) <=  (t2 – t1)/ (1 – P)

     All this is based on a commondity  called real-time.  Real-time mean the time told by perfect clock in a world that obeys Newtonian Physics.  All the physical clocks we construct move so much slower than the  speed of light that relativistic effects are negligible and Newtonian physics holds.
     The speed of the computer is a function is a function of clock rate.  The clock period (inverse of clock rate) is chosen to be just long enough for signal propogation along the critical path of a computer circuit.  A nominal clock period of T c-second is, due to the clock drift realized anything in the range [ T-P*T, T+P*T] r-seconds.
     If tprop r-units is the time required for signal propagation along the critical path, then to guarantee that there is sufficient time for signals to propagate, we would require tprop <= T-P*T; i.e., we would have to set. T >= tprop/ (1-P) C-units.  The greater the value of P is the greater the value of T. This reducing the expected speed of the computer.
    To synchronize in hardware we can use phase-locked looops.  These date back to 1930s and have been widely used in radio and other forms of communicaiton.  In phase-locked loop the comparator puts out a signal that is proportonal to the difference between the phase of the input and that of the oscillator.  This is passed through a filter, and the resultant signal is used to modify the frequency of a voltage controlled oscillator (VCO).
      The advantage of hardware synchronization is the very small clock skews can be attained.  Skews are in the order of nanoseconds.  The chief disadvantage is the cost of the hardware.
      In software-based synchronization, we have an underlying hardware clock, and a software-based correction.  The clock time is the sum of the hardware time and the correction.
1	Interactive convergence averaging algorithm , CA1
2	 Interactive Convergence averaging algorithm, CA2
3	 Convergence non-averaging algorithm CNA

Clock Drift:-
     drift ( K, I) ={ Z ( Microtick(k, i+1) – Z ( Microtick(k, k+i))}/ n^k
     n^k noinal number of ticks of the reference clock within a granule of clock K.
    i.e., difference in the duration of a granule of clock K with the reference clock Z divided by the nominative of reference clock microticks in a granule.

Action, Order and Events:-
     Action is a function  or task that system performs [Behaviour].
     Instance of an action is event i.e., really happening.  Events are labelled using timestamps and acton values.
     Order explains relationship between events.  
     Instantaneous events are events wit no duration.
     Temporal order, if the events respective time instants are not equal n the time scale.
     Casual order, one event triggers the other event like cascaded systems.
     Delivery order, weak relationship between events defined by the communication system between system components.
    
     Logical Time and Logical Clock:-
     The easiest charactrization of logical time is one whre time progress by events.  That is no events impies no time progress.  The events are caualy related.
     A system of logical clocks consists of a time domain T and a logical clock C.  Elements of T form a partialy ordered set over the relation has happened before' [ Partially ordering is 
reflexive, transitive and antisymmetric relation ex: <=] 
      C is a function that maps on event e to an element of T.  C(e) is called the time-stamp
of event.

Task  Modelling And Task Management :-
-------------------------------------------
TASK:-
--------
  According to Garry Nutt a program can be defined as a 'static entity made up of program statements that define process behavior when executed on some set of data.
    An application program can be defined as a program consisting of the tasks and task behaviours in various states that are controlled by some scheduling mechanism process of the system software that lets it execute on the CPU, soe resource-management mechansism process of the system software that allows tasks to use the system memory.
      Task is a set of computations or actions that processes on a cpu under control of a scheduing kernel.  It also has a process structure,  called task control block that saves at the memory.  It has a unique ID.  It has states in the system as follows: Idle, Ready, Running, Blocked and Finished.  It is in ready state again after finish when it has infinite waiting loop – an important feature in embedded system design multi-tasking operations are by context switching between the various tasks.
    When theere are multiple devices, functions, ISRs and program objects, the embedded  software can be modeled as consisting of multple tasks and each task is scheduled by the kernel schedule and uses IPCs for synchronization functions are subunits of the processes or tasks or ISRs.  These don not have analogue of PCB or TCB and have only a stack and no associated scheduler like tasks scheduler or thread scheduler at the kernel.

Characteristics of the Functions, ISRs and Tasks

Function:
      Function is an entity used in any routine for performing specific set of actions as per the arguments passed to it.  It may be called from a process or task functions are subunits of the processes or tasks or ISRs.
     Each function has a program counter and stack that must save before calling another.
     A function calls another function and there may be nesting of one another.  There is synchronisation between the functions directly without control of scheduler or OS.

ISR
    All interrupt-source calls are independent and a call can be from h/w or s/w.  The CPU, during executing an ISR let another higher priority ISR execute.  It is either the ISR  process instructions or RTOS that controls the ISR scheduling on the cpu.  It depends on how kernal manager the ISRs.
    Each ISR has a stack for the program counter instantaneous value and other values that must save before letting another higher priority ISR execute.  The stack need not be at distinct memory bloc when the different ISRs execute.
    According to the given OS kernel features, there are three alternatives for responding and synchronizing the h/w soruce calls.

Task:-
     A task is an independent process and calls are from the system (RTOS).  RTOS can let another higher priority task execute.  It is the RTOS only that controls the task scheduling at the CPU.
     Each task has a distinct task stack for the context (program counter instantaneous values (including an ID) in task control block) that must save when blocking from its running state.  Each task has a process structure in at distinct memory block.
     There is no synchronization between the tasks without the kernel facilitating it.  Only the RTOS kernal calls a task to run at a time.  When a task runs and when it blocks is fully under the control of RTOS.  Two common scheduling:
i	Co-operative
ii	 Preemptive

Consider the following example
     A process controller with following modules 
              a clock tick comes every 20ms whe a clock module must run
              a control module must run every 40ms
              three modules with soft constraints
                      operator display update
                      operator input
                      management information logs

     Single Program Approach
     Ex:
                while(1){
                     wait for clock;
                      do clock module;
                       if(time for control) do control;
                       else if (time for display update) do display;
                       else if(time for operator input) do operator input;
                       else if(time for mgmnt request) do mgmnt output;
                }

           Must have t1 + max (t2,t3,t4,t5) <= 20ms

     Ex:2
                int main (void) {

                     Init.All();
                     for(;;){
                                 IO.Scan();
                                 IO.ProcessOutputs();
                                 KBD_Scan();
                                 PRN_Print();
                                 LCD_Update();
                                 RS232_Receive();
                                 RS232_Send();
                                 TMR_Process(); 
                          }
}
     Each change of state of an input or output results in an RS232 message sent out, a printout and on LCD update RX RS232 messages can result in printouts.  LCD updates, and output status update observations on the single program approach
      Each function called in the infinite loop represent an independent task
      Each of these tasks must return in a reasonable time, no matter what 'thread' of code is being executed
       We have no idea at what frequency main loop runs:
    In fact, the frequency is not constant and can significantly change with the changes in system status (data-dependent).  As printing a along document or displaying a large bitmap.
    Mix of periodic and event-driven tasks
          a most tasks are event driven
             e.g., IO_ProcessOutputs is an event-driven task
          dedicated input event queue associated with them
              e.g., IO_ProcessOutputs receives events from IO_SCAN, RS232_RECEIVE,
              and KBD_Scan when an output needs to be turned on
           others are periodic
               no trigger event, but may have different periods and may need to change their period over time
     Need some simple means of inter-task Communications
               e.g.,  May want to stop scanning the inputs after a perticular keypad entry and restart the sanning after another entry require a call from a keypad scanner to stop the I/O scanner task.
          May also want to slwo down the execution of some tasks depending on the circumstances.  Say there is an avalanche of input state changes, and our RS-232 link can no longer cope with sending all these messages.  Like to slow down the I/O Scanner task from the RS-232 sending task.
        May need to perfrom a variety of small but important duties
                e.g., dim the LCD exactly one minute after the very last key was presed, flash a cursor on the LCD at periodic, fixed and exact frequently a dedicating a separate task to each of these functions is definitely overkill – so handled through timers and TMR-Process.
       Handling Periodic Tasks with Variable Rates
              It involves slow down or speed up execution of tasks either relative to the main control  loop or in absolute terms(exact timing).  Tow variables execution counters and reload value, associated with tasks.
      Volatile unsigned int LCD_ReloadValue=LCD-TASK_DEFAULT_SPEED;
      Volatile unsigned int LCD_ExecCounter =  LCD_TASK_DEFAULT_SPEED;
      Execution counter counts down from the reload value.  In exact timing system the exection counter is decremented in a fixed frequency interrupt routine.  In relative timing system, the task itself decrements the counter when it reaches zero, the task is called, otherwise the entry function to task exits without further processig settig execution counter to special value TASK-DISABLED prevents the task execution.  This can be set by any other task.
    Decrementing in an ISR.
    void interrupt TIMER_IRQ_10ms(void)
           {
              #ifndef EXACT_TIMING
                   if ((LCD_Execcounter != TASK_DISABLED) && 
                       (LCD_ExecCounter))
                          --LCD_ExecCounter;
             #endif
            }

     Issues are (i) fair bit processing in the interrupt handler (ii) need mutually exclusive access to execution counter by task and interrupt code (iii) task must be written so that they return in a reasonable time-may need to split.
Handling Event-Driven Tasks:
     Each event driven task has an input event queue e.g., ring buffer GetEvent and PutEvent.
Allows to do asynchronous read and write to the buffer.
     Unique input event structure for each task 
                typedef unsigned int word;
                typedef struct {
                        word Inptr; /* Head of buffer */
                        word Outptr; /* Tail of buffer */
                        word Count; /* Counter */
                        EVENT_TYPE  Store[BUFFER_SIZE]; /* buffer space */
                      } INPUT_EVENT_QUEUE_TYPE;
  }

Sending an event
    /*  Some where in RS232 Module */
         OUTPUT_EVENT_TYPE OutputEvent;
         OutputEvent.NewState = 1;
         OutputEvent Number = 1;
          OUTPUT_PUTEVENT(&OutputEvent); /*inject an event */

Example event_driven task
    // this task is called from the main control loop
     void  IO_ProcessOutputs(void){
             word ret;
             OUTPUT_EVENT_TYPE OutputEvent;
// normal execution counter processing goes here 
//
// end of execution counter processing

if((ret = OUTPUT_GetEvent(&OutputEvent)!= EMPTY){
    // buffer not empty – process output events
    // turn on/off the required output 
       IO_OutputStateChange (OutputEvent  Number, OutputEvent NewState);
 }
}

Handling 'Simple' Periodic Actions
     Many actions that require events to happen at a fixed time once or periodically e.g
     -> a blinking cursor
    -> an output that needs to be periodically toggled.
    -> show a user message that will disappear or change after a fixed period.
    ->need to light up the keypad or the LCD and turn it off after a period of inactivity
     Making each of them periodic tasks is too heavy weight and lots of execution counters to be handled in interrupt
     Using software Timers solves the problem
     Tasks install user defined timeout function for each timer.  Then calls, TMR_Start and TMR_Stop functions.  Timers maintained in the 'delta list' so that only the timer to be next handled is decremented in the interupt list.
    eg., timers hat are to expire in 10, 60 and 200 clock ticks will be stored s 10 50 ( 60 – 10 ) 140 (=200-60) but more processing when we add or remove a timer to/from the delta queue.
    Beyond Single Program software:-
     Asynchronous implementatation approaches can be
i	Foregroun/ background systems
ii	 Multitasking

     Foreground (interrupt) on interrupt {
     do clock module;
      if(time for control) do control;
}
    Background
        while(1) {
             if( time for display update) do display;
             elseif(time for operator input) do operator;
             elseif (time for mgmnt request) do mgmnt;
        }

->  This Foreground/Background (decoupling) relaxes constraint t1+t2 <= 20 ms

Multitasking Approach:-
     In single program approach: one “task” only.  Foreground/Background had tow tasks.  The generalization is multiple tasks also called processes, threads etc;
     Each task is carried out in parallel.  There is no assumptions about number of processors.  Tasks simultaneously interact with extenal elements.  
    eg., monitor sensors, control actuators via DMA, interrupts, I/O etc.,
     Gives illusion of parallelism.  Requries scheduling (organising) of these tasks and sharing data between concurrent tasks.

Task Characteristics
     Tasks may have
i	resource requirements
ii	importance levels (priorities or criticalness)
iii	precedence relationships
iv	 communication requirements
v	 And of course, timing constraints
  (a)  Specify times at which action is to be performed, and is to be completed.
  (b) e.g., period of a periodic task
   © or deadline of an a  periodic task
Preemption:-

     Non-preemptive – In this taks once started, runs until it ends or has to do some I/O.
     Preemptive – a task may be stopped to run another
•	incurs overhead and implementation complexity
•	but has better schedulability
•	 with non-preemptive, quite restrictive constraints 
eg., N tasks, with task j getting ready every Tj, and needs Cj time during interval Tj then;
Tj>= C1+C2+..+Cn in the worst case because all other tasks may already be ready ie., period of every thread >= sum of comutation times.
Organize multiple tasks:-

    Cyclic Executive (Static table driven scheduling)
          Static schedulability analysis
          Resulting schedule or table used at run time.
          TDMA-like scheduling
    Event-driven non-preemptive
          tasks are represented by functions that are handlers for events
          next event processed after function for previous event finishes
    Static and Dynamic priority preemptive scheduling
          Static Schedulability analysis
          No explicit schedule constructed at runtime tasks are executed higher priority first
          Rate Monotonic, Deadline Monotonic, Earliest deadline first, least slack
    Dynamic Planning-based Scheduling
           Schedulability checked at run time for a dynamiclly arriving task
           Admission Control
           Resulting schedule to decide when to execute 
    Dynamic best-effort Scheduling
           no schedulability checking is done
           System tries its best to meet deadlines

Performance Characteristics to Evaluate Scheduling Algorithms
      Static Case:  Off-line schedule that meets all deadlines
            Secondary Metric:
                      Maximze average earliness
                      Minimize average tardiness
Dynamic case: no a priori guarantees that deadline would be met
Metric:  Maximize no of arrivals that meet deadlines
Concurrency:-
     The Principles of concurrency are fundamental regardless of the granularity of concurrent units (processes, tasks or threads).  Concurrent tasking means structuring  a system into concurrent tasks .  Concurrent tasking is a natural mode for many real time applications.  Separation of concerns of what each task does from when it does it.  Overall reduction in system execution time by overlapping executions of independent tasks.  Greater scheduling flexibility since time critical tasks with hard deadlines may be given a higher priority than less critical tasks.
     Concurrent tasks identified early in the design enables early performance analysis.  However concurrent tasking introduces complexity because of task interactions.

 Task Interaction:-
     Tasks execute asynchronously i.e. At different speeds, may need to interact with each other.  Three types of interactions.
i	Communication – transfer of data between two tasks
ii	Synchronisation – coordinates tasks
iii	Mutual Exclusion – Control  access to shared resources.

Results of Interaction:-
     Three types of behaviour,
i	Independence- tasks have no interaction with each other
ii	 Cooperating – communicate and synchronize perform some common operation 
iii	 Competing – Communicate and synchronize obtain access to shared resources.
 Implementing Task Interaction 
i	Shared Memory
ii	 Message Passing
Communication Mechanism:-

i	Channels – provide the medium for items of information to be passed between one task and other can hold more than one item at any time usuallly have the items passing through i an ordered manner
 provide a pipe of information passing from one task to another.  For the tasks to run truly asynchronously, there must be some buffering of information.  The larger the buffer, the greater the system flexibility.
 - queues, circular queues ( or ring buffers)
 - event flags
 - sockets and pipes
i	Pools – Make items of information available for reading and for writing by a number of tasks in the system  Acts as a repository of information, information deoes not flow within a pool.
 - Pools usually takes the form of system tables, shared data areas, and shared files, since a pool is shared by more than one task it is essential to control strictly the access
information in pools.
- Mailboxes (or ports), Monitors
-In all cases having a finite sized structure; the size of structure should be taken into account during the design phase of the system to prevent overflow

Task Synchronisation:-
     Synchronization involves the ability of one task to simulate or inhibit its own action or that of another task.  In other words in order to carry all the activities required of it, a task may need to have the ability to say stop, go, wait for a moment to itself or another task.  Two significant events wait and signal.
      One task wait for the event to occur and another signal that the event occurred.
      WAIT(event) and SIGNAL(event) WAIT and SIGNAL are procedures and indivisible operations, processor cannot be swapped while they are being executed.
WAIT (event)
      -Should event have already occurred the task will resume immediately.
      -A waiting task can be thought of s being in the act of reading event information from a channel or pool once this information apppears it can continue.
SIGNAL(event)
     -Broadcasts the fact that an event has occurred Its action ist o place event information in a chalnnnel or a Pool.    This is in turn may enable a waiting task to continue.
Synchronisation Via Semaphore:-
•	a non-negative integer that can only be manipulated by WAIT and SIGNAL apart from the initialization routine.
•	Event in WAIT and SIGNAL above refer to a semaphore.
•	Also used to manage mutual execlusion
Mutual Exclusion:-
    Critical region – a sequence of statement must appear to be executed indivisibly.
    Mutual Exclusion – the synchronisation required to protect a critical region .  Can be enforced using a semaphores.
Problems due to improper use of  Mutual Exclusion :-
i	Deadlocks – Two or more tasks are waiting indefinitely for an event that can be called only one of the waiting tasks.
ii	Livelocks – Busy waiting indefinitely only one of the busy waiting tasks
iii	Lockout or Starvation – One task that wished  to gain access to a resoruce is never allowed to doso because there are always other tasks gaining access before it.
         If a task is free from livelocks, deadlocks and lockouts, then it is said to possess liveness.  This property implies that if a task  wishes to perform same action, then it will 
eventually be allowed to do critical section then it will gain access within a condition among the problems.  There are deadlock prevention, deadlock avoidance and deadlock detection and recovery mechanisms are there
      Expressing Concurrency :-
•	Coroutines
•	Fork and Join
•	Cobegin and Coend
•	Explicit task declaration
Coroutines:-
     Like suroutines but allow control to pass explicitly between them in a symmetric rather than strictly hierarchical way controll is passed from one coroutine to another by means of the 'resume' statement which names the coroutine to be resumed.  When coroutine executes a resume it stops executions but retains local state information so that if another coroutine subsequently resumes it can and will continue its execution.
      NO run-time support system is needed ie the coroutines themselves sort out their order of execution.  The tasks can be written by independent parties and the number of tasks need not be known in adavance.
      ADA and Modula-2 have built in suppport for coroutines.  Not adequate  for true  parallel processing as their semantics allows for execution of only one routine at a time. Error-prone due to the use of a global variables for communication.
Fork and Join:-
     Fork specifies that a designated routine should start executing concurrentl with the invoker of the fork.
     -Join allows the invoker to synchronize with completion of the invoked routine.  Fork and Join allow  for  dynamic task creation and provide a means of pasing information to the child task via parameter usually only a single value is returned by the chld on its termination.  Flexible but error-prone in use because they donot  provide structured approach to task creation
•	available in unix
    Function F return 
    Procedure P;
           i:= Fork F;
           j:=join C;
    end P;
Cobegin and Coend
      Structured way of denoting the concurrent execution of a collection of statements Tasks between a pair of cobegin and coend statements execute concurrently.  Can een support testing of cobegins occam-2 suppports cobegins
        Cobegin
             S1;
             S2;
             S3;
         Coend;
Explicit Task Declaration:-
        Routines themselves state whether they will be executed conrurrently.   ADA support explicit task declaration by implicit task creation i that all tasks declared withn a block start executing concurrently at the end of the declarative part of that block ADA also supports dynamic task creation using the 'new' operator on a task type.  In ADA initialization data cannot be given to tasks upon creation.

Task Implementation:-
    Tasks can be implemeted over 
i	dedicated resource
ii	 shared resource

i	Dedicated Resources (Multiprocessing) 
   - dedicate one processor for each task
   - connect processors using communication links such as bus
   - different arrangements are possible such as shared memory (one big memory shared by all but with local memory too) or distributed memory ( all local memory)
i	 Shared Resources
 (a) Sharing the processor
  (b) shareing the memory
i	 Sharing Processor ( How/When/Which)
   -how the processor is to be shared? What mechanisms are required to enable a processor executing one taks to change its activity and execute and then task.
    -when the processor is to be shared – at what times or as a result of what events, should the processor change fro executing one task to executing other task
    -which task should the processor direct its attention to when sharing of the processor necessory (related to scheduling)
'How' and 'When' in Serial Execution :-
     Commence the next task at its starting point at the completion of the current task.
'How' and 'When' in Concurrent Execution:-
      Commence next task at the point where it previously left off when the current task gives up use of the processor.
Shared Memory:-
    Provide enough memory to hold all the tasks or do code sharing and memory sharing.
  Code Sharing
    Serialy reusable code – write the code in the subroutine shared (call it S) in such a way that it makes to assumptions about the values in its local variables when it is entered using a lock and unlock pair. Only one task can be made to use S at any time.

     Re-entrant Code:-
       In the above scheme all the temporary area that S needs reside in 'S'.  If these areas were to be part of the task currently using 'S'.  Then would consist of executable code any and it could be executed by more than one task at a time, provided that S did not modify its own task code in any way.  'S' uses the data areas indirectly, typically via relocation pointer which is associated with each task and which is passed as a parameter when 'S' is called.
Task Modeling Issues:-
Structure:-
       Static – number of tasks is fixed and known before runtime.
       Dynamic – tasks are created at any time the number of tasks is determined only at runtime  for example ADA and C.
Level of Parallelism:-
       Nested:  Tasks are defined at any level of the program text; in particular, they are allowed to be defined within other tasks.  For example ADA and C.
      Flat:  Tasks are defined only at the outermost level of the program text.
Granularity
     Coarse Grain:  Such a program contains relatively few big tasks eg ADA 
     Fine Grain:   Such a program contains a large no of simple tasks.

Initialization:-
     When a task is created, it may need to supplied with information pertinent to its execution.  Two ways:
     (a)  Pass information in the form of parameter to the task 
      (b) Communicate explicitly with the task after it has started its execution.

Termination Under the Following Circumstances
•	Completion of execution of the task body
•	 Suicide, by execution of a 'Self-terminate' statement
•	Abortion, through the explicit action of another task 
•	Occurrence of an untrapped error condition 
•	Never tasks are assumed to execute non-temination loops
•	When no longer needed.

MODEL :-
      A model is a representation in a certain medium of something in the same or an other medium.  The model captures the important aspects of the thing being modeled from a certain point of view and simplifies or omits the rest.  A model is used in engineering, architecture and many other creative fields.
      A model is created in a medium that is convenient for working.  Models of building may be drawings on paper, 3-D figures made a cardboard and papier-mache or finite element equations in an computer.  A construction model of a building shows the  appearance of the building but can also be used to make engineering and cost calculations.
Embedded System Models:-
     The different models of computation focus on different aspects of how to specify  a system.   Homogenous modeling uses one single language to specify the system, analyzes and allocates parts of the specification being implemented in H/W or the specification being implemented in H/W or S/W respectively.  Heterogenous modeling uses specific languages for the hardware parts, e.g., VHDL and the software parts, e.g., c or c++ allows a simple mapping to hardware and software system models.
     A system functionality can be described by different methods; each of these particular methods is called a model which has to be:
1	Formal to simplify the verification and analysis of a function.
2	Complete to describe all information required for system design
3	Comprehensible easy to understand, to capture and to modify
4	 Hierarchical and modular to handle the system complexity.
5	 Abstract to describe the functionality independent of the implementation

Different Models:

i	State-Oriented Models:-
    State-Oriented Models specify the system functinality by a set of states and a set of transitions between them.  The transitions react to external events.  The main application area is the domain of control flow dominated applications e.g., Reactive Systems.
 (a) Petri-Nets – Petrinets are a graphical language to model complex systems.  They are used to formulate discrete parallel systems.  In general petrinet consists of places, transistions and tokens.  The tokens which are stored in places are consumed and produced whenever a transition.  Petri nets are well suited to model and analyse concurrent systems.  eg., to end dead locks.  In practice, petrinets have proven to beuseful to describe protocols typically used in networks.  A disadvantage of Petrinets is that they become in comprehensible for complex systems.
(b) Finite State Machine:-
      Finite state machines consist of a set of states, a set of transistions connecting states and a set of actions.  One of the states is the initial state.  There are two well-known types of  FSMs.  The meal Automaton is a transistion based FSM which associates Actions and Transistions.  The Moore Automaton is a state-based FSM associating actions with states.  Because the system state is always defined explicitly, FSMs are well-suited for control-flow dominated systems.  A disadvantage of FSMs is that they lack of hierarchy and concurrency.
(c )Hierarchical Concurrent FSMs:-
       HCFSMs avoid the disadvantage of FSMs by decomposing states into a set of sub-states.  These sub-states may be concurrent sub-states communicating via global variables.  HCFSMs support both hierarchy and concurrency and are well suited to represent complex systems.  Control aspects can easily be modeled but no Data and no Activities.
i	 Structure Oriented Models
     Structure-Oriented models are used in later design phases.  In contrast to state-oriented and activity oriented models which specify the system functionality structure-oriented models describe the physical modules and interconnections of a system.  In many cases Structure-Oriented models are hierarchical so that a system block is also a structure oriented in hierarchy.  This model containing a set of sub-systems and Interconnnections.
  (a) Block Diagrams
(b) Register Transfer Schematic
 (c ) Gate-Level Schematic
i	 Activitiy Oriented Models
     Activity Oriented models specify a system global functionalit by a set of activities related by data or control dependencies.  In contrast to state-oriented models, they have no internal state.  Therefore, these models are often applied to Data-flow dominated applications, e.g., in digital signal processing (DSP).
(a)  Data – Flow Graphs are Directed Graphs DFG (V,E) the vertices V correspond to Actors representing inputs, outputs, Storages and operations, where operation may be complex functions represented in their turn by an own DFG.  The edges E represent data dependencies between vertices.  DFG support hierarchy and concurrency and they are well suited to specify complex transformational systems but control dependencies cannot be modeled.
 (b)  Control Flow Graph – CFGs are directed graphs CFG(V,E) the vertices V corresponds to Basic block or Decision Nodes, where a Basic Block is a sequence of statements without branches, a Decision Node is used to steer the bow of control into alternative directions.  The edges E represent control dependencies between vertices. CFGs are well suited to model control-flow dominated sytems but data dependencies cannot be modeled.
i	 Data-Oriented Models
        Data-Oriented Models define the relations between data which are processed by a system.  They are very useful to specify informational systems.
 (a)   Entity Relationship Diagram:-
              An ERD defines the data processed in a system by entities where each one contains set of attributes storing interestng information about the entity.  Relations whre each one reflects some fact relevant to its entities.
(b)  Heterogenous Models
                Heterogenous models combine special characteristics of the different models presented before.  Programming languages combine aspets of Data-Oriented and activity-oriented models. 
  (a) There are two major classes of programming languages
           -In programs implemented with imperative languages (eg. ANSI C, or PASCAL) the statements are executed in the same order as defined in the specification.
           -Programs implemented with Declarative languages (eg., Prolog) Specify no explicitly execution sequence of the program statements, the sequence of computation is driven by a set of functions or logic rules.  The general disadvantage of most programming languages is that they have no special constructs to model a system state.
(b)  Object-Oriented Models – OOMS are a combination of Data-Oriented and activity-oriented models.  Basic elements of these models are objects consisting of a set of Data and a set of operations transforming this data.  These objects execute their tasks independently representing a natural concurrency.  New aspects of ooms are data abstraction and information hiding.
(c ) Control / Data-Flow Graphs:-  CDFG combines the advantages of CFGs and DFG in one model.  The vertices of a CFG are now represented by DFGs.  Therefore a CDF represnts not only the control-flow of a system but also the internal data dependencies. CDFGs are often used as an intermediate format eg in high-level synthesis
 (d)   Program State Machine -  PSM combine the principles of hierarchical FSMs with programming language constructs.  A PSM consists of a hierarchy of program-states  executing a special mode of computation.
A program state may be a composite program state, consisting of concurrent or sequential sub-states or a leaf-program-state represnting a leaf in the hierarchy tree.  IT is described using programming language constructs.  PSMs overcome the limitations of programming languages and hierarchical FSMs.  A disadvantage of PSMs is that format verification methods cannot be applied.
Modeling Of Multiprocessor Systems:-
     Multiprocessor systems can be highly or loosely coupled to the memory.  It can also be coupled by mesh, ring, torrid or tree.  There are several methods of scheduling and synchronising the execution of instructions, SIMDS, MIMDS, and VLIWs in the system. The problem is how to partition the program into tasks or sets of instrucitons between the various processors, and then how to schedule the various processors, and then how to schedule the instructions and data over the available processors time and resources so that there is optimum performance.
   (a)  Synchronous Data Flow Graph(SDFG) Model 
                 An SDFG model is like DFG but also models the delays as well as the number of nputs and outputs.
   (b)  Homogenous Synchronous Data Flow Graph (HSDFG) Model  
                  HSDFG models are like on SDFG but have the feature that there is only one token that delays along an edge (arc or arrow) because there is only one token at input and one at output.
   (c ) Acrylic Precedence Expansion Graph (APEG) Model 
                     APEG Models are such thate there are no delays during execution at any stage in an APEG or chain of APEGs.  Complex problems are therefore first modeled as the SDFGS, then SDFGs are unfolded into HSDFGs and HSDFGs are separated into APEGS.  Processing is as per precedence constraints between the APEGs. APEG based algorithms become the simplest to schedule but precedence constraints in the algorithm among its APEGs remains the same as before.
(d) Timed Petri Nets and Extended Predicate/Transition Net Models:-
                 A coloured token means a token that may be an output or an event or an inhibitng event.  Its colour can change.  For examle, form inhibitng event ot enabling event.  Timed petri-nets are the petri-nets with defined times for firing a transistion, and for defined times for firing a transition, and for defined times for firing a transitions. Timed extended predicate/Transition Net are the timed Petri-nets with times distributed by the probabilistic functions.  These two types of Nets model  a multiprocessing system program flow.
(e)   Multi Thread Graph(MTG)  System model 
                     A multi threaded Graph Model is modeling by using two layers, one of CDFG and the other of timed Petri-Nets, for task level and processor level concurrent processing respectively.
     The nature of embedded systems leads to a set of requirements which a specification language should support.  We will have to consider:
      (i)  Analytical Aspects
       (ii) Commercial Aspects
       (iii) Expressive Power
Analyticsl Aspects:-
           This are important to analyze the behaviour of embedded system at specification time, i.e., before designing it . They include,
 1. Verifiability and Formal Analysis:-  Are key issues.
              Formal Specification languages based on a formal interpretation model enable to verify the specification, eg. To detect dead-locks.
2.  Model Executatbility is gained by executable specifications.  They allow to experiment with alternatives of te specification e.g., by simulating it with a set of stimuli. One goal is to validate and analyze the correct function of the system.  Another goal may be the detection of computation-intensive parts in the specification.
Commercial Aspects:-
       Certain Specification language has a great impact on the time-to-market of the products.  They include:
a. Availability of tools supporting a specific language eg., Simulators, debuggers, compilers for diffferent  processors, and synthesis tools for different hardware libraries is a most important aspect,; short time-to-market is a key goal.
b.  Standardization of a specification language is an important feature.  Standardized languages are well -defined, supported by tools and continously improved (eg., VHDL)
c. Simplicity and clarity may also be an important point to choose a specification language, because a clarified specification may serve as a good documentation of the system.
Expressive Power:-
     1.  Hierarchy allows to handle system complexity.  It simplifies the specification process by enabling top-down or bottom-up specification.  Structural Hierarchy enables to compose a system of inter-connected components which are composed of sub-components.  Behavioral hierarchy decomposes a behavior into a set of sub-behaviors e.g., procedures or functions.
2.    Programming constructs simplify the specification complex data types like records, arrays, lists, etc, describe the data in a comfortable way;- constructs like functions, procedures, loops, branches and assignments simplify to describe the sequential parts of the system behaviors.
3.  State-Transistions model the internal state of an embedded  system, which is important for control-flow dominated or reactive systems.  State-transitions can be modeled by programming constructs eg., a case statement.
4.  Behavioral completion determines when a behavior has executed all computations this is useful to start another behavior in sequence.
5.  Concurrency has to be expressible since the parts of an embedded sysem are working concurency.  These parts may work in parallel at different levels of abstraction like jobs or tasks.  All the process level threads of the processes working independent of each other should work in parallel.
6.  Communication mechanisms like the shared memory or the message passing model are required when concurrently working parts exchange data.
7.  Synchronization of this data exchange requires additional handshake protocols and status signals.
8.  Exceptons (eg., interrupts or resets) may occur in embedded systems, when they implement reactive systems communicating with their environment.
9.  Timing aspects have to be considered e.g., the response time of an automative embedded system-functional timing represents the time to execute a behavior timing constraints specify a min/max range of  elapsed  time to execute a special behavior.
10.  Non-determinism is useful to leave details of the implementation phase.
11. Environmental characteristics are non-functional aspects-such as timing specification of a incoming data.  They are important for embedded systems communicating intensively with the environment.
     Task Management:-
              The task can be in any of the following states:

               All tasks should be created before run-time and remain dormant until needed. This  guarntees that the resource demands will be known and that performance can be evaluated with respect to real-time deadlines.

Memory Management:-
        Consist of (i) Heap Management and
ii	Stack Management
iii	Heap Management
  Classic Heap (unix)
         -   The memory is collected into one giant heap and partioned according to the demand from the tasks.
         -   There are several 'Fit' memory allocation algorithm e.g., best-fit, first-fit, that also attempt to minimize memory fragmentation.
         -    Has a big management overhead so is not used in real-time sysems.
Priority Heap:-
         -Partitions the memory along priority boundaries equal low and high priority partiitons are created.
          -The high priority partition is given adequate memory for its worst case, and the remaining memory is given to the low priority partition.
          -In this scheme only low priority tasks wait due to insufficient memory.
Fixed Block Heap:-
         -Partitions the memory into several  pools of fixed block length and upon request, allocates a single block of memory from the pool with size equal or larger than the requested amount.
          - Partitions can be used to keep multiple tasks in memory  at the same time provided that use no of tasks is fixed and known.
          - Leads to fragmentation one approach to minimize this is that memory can be divided into regions in which each region contains a collection of different sized fixed sized partition.

Heap Issues:-
       Debug Info – Saving info with each block memory can help characterize memory usage a performance.  The additional information is useful in isolating such memory problems as memory leaks over – committed memory and thrashing.
       Keeping additional information  in the memory blocks allocated.
  - A memory block can be stamped with id of the task (task id) or the address of the statement in a task(return address of the routine) that requests it.
  -These can help identify the causes of the memory problems.
  -One more technique is to use a time stamp with each block allocated.
  -Time stamping in conjunction with taskid or return address makes it possible to see how long a memory block has been allocated if the time is long, it is usually a sign that the memory block was lost.  
- during the development phase, it may be desirable to have periodic task runing that examines the time stamps to identify the blocks with potential memory leaks.
-Low watermark, this alerts the devleloper whenever the number of unallocated blocks falls below and threshold and helps identify potential memory over commitment problems.
Stack Management:-
          When multiple tasks share a single processor, their contexts (Volatile information such as the contents of hardware registers, memory-management registers, and the program counter) need to be stored and restored so as to switch them.  This can be done using
        -Task control block model
       -One or more run-time stacks
-Task-Control block Model
•	Best for full-featured real-time OS.
•	Context is kept  in the control block of the task 
•	Having multiple tasks means multiple control blocks, which are maintained in a list. This list an be fixed, if the number of tasks is fixed and known/or dynamic.
•	 In the fixed case, the control block of a task is regarded as 'deleted even though it is not in the dynamic case, it is  actually deleted and the memory allocated for the task is returned to the heap.
-Run-time stacks
•	Used to keep contexts
•	May use only one run-time stack for all the tasks or one run-time stack in conjunction with several application stacks ( or private stacks) one for each task in memory.
•	Multiple stack case allows tasks to interrupt themselves, thus helping handle transient overload conditions or reentrancy and recursion.
•	 Stack size must be known a priori.  If recursion is not used, the stack size is equal to the number of tasks anticipated plus some provision for time overloading
•	Operating system manages the stacks
•	If it is necessary to maintain the context of an interrupt service routine over repeated interrupts, then an independent stack rather than the stack that is used for all the interrupt is required.

            
Sampling:-
            Voltages are generated by the sensors and may represent light levels, temperature, or vibration or perhaps the output of a microphone or audio system and need to be converted into digital data.  The whole process is known as sampling.  Preprocessing is required before sampling stage.
Amplifiers:-
              Amplifiers are used to interface one analog circuit to another.  An amplifier is a circuit that increases( or decreases) a given input voltage to produce an output voltage.  An amplifier is used between  the sensor and the sampling system to increase the sensors output.  The amount of increase or decrease  in the signal is known as the gain of the amlifier.
                   Gain = Vout/Vin
         The ability of a circuit to respond to a changing signal is typically limited to a given range of frequencies.  This is known as the 'Frequency Response' of a circuit. The frequency response of a circuit, such as the audio amplifier, should be flat over its frequency range.  This means that its responses to an input signal will be the same, no matter what the frequency.  So in the case of audio amp. The gain will be constant for any frequency of signal in the appropriate range.  Thus, the volume will not vary with frequency.  At either end of the frequency range, the ability of the amplifier to perform ideally diminshes.  At these extremes of frequency, the amplifiers gain diminishes.  This is known as roll off.  The frequency response is normally defined as the frequency range where the gain is within a certain limit of the ideal.
         The limitation of an amplifier to replicate the input signal at its output is the distortion of the amplifier.  Also termed as total harmonic distortion, smaller this number the better the amplifier.
           Discrete transistors or vacuum tubes (valves) or operational amplifiers (op amps) are the amplifying devices.
Analog-to-Digital Conversion:-
            A device that convertsan analog input voltage to a digital number is known as an Analog-to-Digital converter or simply ADC.  A codecis an ADC combined with a Digital-to-Analog Converter (DAC), providing both analog inut and analog output in the one chip.
             ADCs are found in cell phones and digital phones, converting voice to digital data for transmission used in computer to digitize the input from a microphone for speech recognition.  Professional recording studies use ADCs to convert audio to digital data preparation for CD mastering.  Similarly, video is sampled using ADCs prior to DVD mastering.  Scanner, web cam and digital cam corder all have ADCs in them.  ADCs are used to samle inputs from sensors.
Integrating ADCs:-
           Integrating ADCs use an internal voltage-controlled oscillator to produce a clock signal whose frequency is proportional to the voltage being sampled.  The clock signal is used to drive a counter, which provides the digital value for the sample.  The higher the sampled voltage, the higher the clock frequency, and therefore the higher the number reached by the counter.  The counter is reset prior to each conversion.  Because of this conversion technique, integrating ADCs are not known for their speed of conversion.
 Successive Approximation ADC:-
        Successive-Approximatin ADC uses a DAC to provide an analog reference voltage that is compared to the input voltage.  By incrementing the digital code driving the DAC, the  reference voltage is increased until a match is found.  Once this happens, the code used to dirve the DAC is used as the digital output of the ADC.
Flash ADCs ( also known as parallel ADCs)
        Flash ADCs use a bank of comparators to compare the input voltage with a range of reference voltages.  The conversion of the input analog voltage to a digital value is therefore very fast.  The catch is that flash ADCs tend to be more expensive than other types of ADCs and due to their complexity normally have a lower resolution than other forms of ADCs.
        The process of converting an analog signal to digital is known as sampling or quantization.  ADCs have two principal characteristics-sample rate and resolution.  Sample rate is expressed as samples per second (SPS) and refers to how frequently an analog inut signal converted into a digital code.  The faster an ADCs sample rate the more expensive that chip will be.  Resoluton determines the accuracy of each sample.  For example, an 8-bit ADC wil return an 8-bit code representing the sampled input signal.  This means that the input has been quantized into one of 256 discrete values.  A 12-bit ADC will quantize the signal into one of 4096 values, yielding a more accurate result.  However, the higher the resolution, the more expensive the ADC.
         An ADC will convert the analog signal into a number that represents the ratio of the input signal to a given reference voltage.
         Signal – (Sample/max-value) * reference_voltage
         For ADCs reference voltage is 5v, an 8-bit ADC with 255 representing full scale, the Sampled value of 153 from the ADC then.
         Signal  = (153/255)*5
                    = 3v
Sample Rates:-
          The rate at which the signal is sampled can have a dramatic effect on the quantized result and therefore can also affect the way in which software interprets that result.  When a sinusoidal signal that is sampled at a rate equal to its period, the sample happens to coincide.
With a peak in the signal.  The signal changes inbetween samples, but the choice of sample rate gives the same value each time. Giving a complexity false picture of what is really happening to that signal.  For sampling software each value returned is the same and so the signal appears to us as through it were a flat line.
          If sample rate is choosen double ( or more) the signal's highest frequency compnent, the signal appears in more detail.  This sampling frequency is known as the 'Nyquist Frequency' and is the lower limit of what will produce usuable results.
         If the sample rate is slower than the Nyquist frequency, false artifacts ( Sine wave appearing as a straight line) may appear in the sampled result.  These phantoms are known as 'aliasing' .
          The faster the sample rate, the more accurate sampled results.  Sampling is quantizing the signal both in terms of ampiltude(ADC resolution) and time(Sample Rate), a quantization error will always result.
         In quantization the smooth sine wave of the original signal has become a jagged representation.  Monitoring temperature this may be sufficient.  Temperature at specific intervals are required rather how the temperature signal changed.
         Sampling audio, the quantization effect can be a real problem.  Voice mail uses same rate of only 8 KHZ and a resolution of 12 bits and the resultant sound quality is limited.  CD audio uses a sample rate of 44KHZ and resolution 16-bit data.  DVD audio uses a sampe rate of 48KHZ and 24-bit data for even greater audio fidelity.  To further improve sound quality, both CD and DVD players have special outut filters to smooth the transistons between each sample when the data is converted back into analog form.
        A good general-purpose ADC for sensor application is the maxim MAX1245.  It has eight channels of analog input and can sample at 100,000 samples per second with a resolution of 12 bits.  The MAX1245 has on internal track and hold,  preventing a changing signal from corrupting the result during the conversion.  Every second wire in the connected cable will be ground  to provide a degree of noise immunity to our analog signals.
         AD22100 and AD22103 are temperature sensors by analog devices.  The output voltage corresponds to 22.5 mV/'c over the temperature range -50'c to +150'c and 28mV/'c over the temperature range 0'c to 100'c respectively.  And also 5v and 3.3 v supply respectively.  
           TAOS TSL250R is a light sensor from Texas Advanced Solutions Inc, The TSL250R consists of photodiode (a semiconductor that is responsive to light) and an integrated amplifier.  The spectral response for the TSL250R ranges from ultraviolet(left) to infrared (right) and peaks in the visible part of the spectrum.
           Pressure sensors work by mesuring the deflection of a diaphragm separating two chambers.  One chamber is exposed to the pressure that is being measured, while theother chamber holds a reference pressure.  The pressure difference between the two chambers causes the diaphragm to deflect, and this deflection is converted into a voltage that is proportional to a pressure difference, pressure sensors come in three different types: absolute, differential, and gauge.
         In an absolute pressure sensor the reference chamber is sealed.  Pressure readings are referenced to an absolute pressure.  Absolute sensors normally have the reference chamber pressure  at vacuum or at one atmosphere.  Ex:  Motorolo MPXA6115A absolute pressure sensor.  It operates from 5v supply and will give an output voltage of between 0.2v and 4.8v proportional to pressures of 15kPa to 115kPa signal conditioning, temperature compensation and signal amplification all integrated in single package.
           In differential sensor, the reference chamber is not sealed, and an external pressure reference may be applied.  Differential sensors are used to measure the relative pressures between  two gases or two liquids.
            In gauge sensor a variation of the differential pressure sensor, where the reference pressure chamber is open to the atmosphere. One interesting use of a gauge pressure sensor is to measure air speed.   
            Accelerometers are used to mesure linear acceleration of vehicles.  The ADXL150 is a single-axis (one dimensions) accelerometer with a resolution of 10mg and a full-scale range of +/- 50g.  For dual-axis(two-dimensional) sensing, choose the ADXL250 [g is the unit of acceleration and equal to 9.8 m/sec^2].  Commercial jet aircraft experiences a force of about 2g, when the aircraft turns.
 
Analog to Digital Conversion Methods:-
1	Parallel / Flash ADC
2	Successive Approximation ADC
3	Charge Redistribution ADC
4	Tracking and Dual Slope ADCs
5	ADC using Voltage to Frequency Conversion

Digital to Analog Conversion Methods:-
1	Binary-Weighted Resistor Network
2	R-2R Resistor Ladder Network
3	 Charge Redistribution DAC
4	 Multiplying DAC

Successive Approximation ADC:-
         Successive approximation ADC is a feedback-type converter that is widely used in a medium-speed applications such as PCM speech transmission.  The conversion process is analogous to determining the weight x of an unknown mass using a chemist's weight balance and a given number of known weights.  Assume, for example the known weights are 1Kg, 2Kg, 4Kg and 8Kg and the unknown mass is 11.5Kg.  Instead of starting at an arbitrary weight, the systematic procedure begins at half the maximum measurable weight of 8Kg.  Since X > 8 Kg we retain the 8 Kg-Weight at the beginning of second step and add the next lower weight of  4 Kg.  Now  X , 12 Kg hence 4 Kg weight is removed.  In step next lower weight of 2 Kg is added since X > 10 Kg to 2 Kg weight is retained.  In step 4 1 Kg weight  is added with all the weight used X is between 11 Kg and 12 Kg.
           In Successive Approximation ADC, the process starts with the digital value 100.00, which is half the digital range of the converter, in an N-bit register.  This register is referred to as a successive approximation register(SAR).  Each approximation step takes place during a clock interval. The DAC converts the SAR contents to analog voltage Va.  The comparator output C is used to  (a)  retain the current bit value of 1 in SAR if c= high that is Va > Vd or (b) change ( Complement) the current  bit value to 0 if C is low.  At the start of the next clock pulse, the next lower-order bit is set to 1.  The process of setting a bit to 1 and comparing Vd with Va carried out in sequence for all N bits.  At each step a voltage increment (or decrement ) of half the magnitude of the previous step results at the output of the DAC.  An offset voltage corresponding to -(1/2) lsb is usually added to Vd before applying Vd to the comparator. This keeps the conversion error in the range of +/- (½) lsb.
       By starting at the mid point 100.00, the circuit completes the conversion in exactly N clock pulses regardless of the analog signal amplitude. This is an advantage in applications in which the time required for conversion must be a constant such as in uniform sampling.
        Successive approximation ADCs with build-in or external sample-and-hold circuits are available for 8- to 16-bit resolution with conversion times in the range of a few Microseconds to tens of Microseconds.  The conversion speed is essentially dependent on the comparator switching speed the clock rate, and the bit resolution.  Both R-2R ladder and Weighted-capacitor (NMOS)networks are used for the DACs.
Tracking  and Dual Slope ADCs
         A simpler alternative to successive approximation ADC uses a counter and a DAC.  The reference voltage VR of the DAC is such that Vd at full scale ( that is, for the counter output of 11.11) is equal to the maximum analog input voltage ( Va) to be converted.  Conversion begins by resetting the counter to 0 at the arrival of a new sample of the analog voltage Va.  With the DAC output Vd  < Va, the comparator output switches to logic low when Vd reaches Va.  The counter output now corresponds to the digital value of Va within (½) lsb.  Conversion resolution is improved by using more bits for the counter the DAC.
        Conversion can be speeded up by using  up/down counter.
        Another type of DAC that uses a counter is the dual slope converter.  Instead of using a DAC in the feedback loop, this converter employs an integrator to integrate the analog voltage  Va over a fixed time interval.  Charge accumulated in the integrator capacitor is discharged at a constant rate to zero.  The ration of the charging and discharging time intervals is proportional to the digital value of Va.
         Proportional to the time interval T2 as T2 = ncT and T1 = 2^NT the above equation becomes
                         nc   =   (Va/VR)*2^N

         The resolution of this converter can be improved by increasing the size of the counter.  Usually used for converting slowly varying or noisy signals.  High-accuracy digital voltmeters are built using dual-slope converters.
Digital to Analog Conversion:-
 Binary-Weighted Resistor Networks
            Conversion in the circuit begins by discharging the capacitor C and connecting the SPDT switch  the input of the Op amp integrator to the input voltage Va (>0).  As the capacitor charges, the N-bit counter is simultaneously enabled to increment from Zero.  Since the charging current derived from Va is (Va/R), the output of the integrator (Connected to the inverting inut V- of the comparator) ramps down with a slope of (Va/Rc).  With the reference(non-inverting) voltage V+ at zero, the comparator output is at logic high for positive Va; hence, the clock signal passes to the counter.  When the counter reaches the full count and resets to zero after 2^N clock pulses, the integrator input is switched to a reference voltage VR < 0.  Since Vr is negative, the accumulated charge in  C is discharged at the rate of (VR/RC).  The comparator output is still high, so the counter continues to count from its reset state.  When V- reaches zero, the comparator output switches to low and the counter is disabled.  The output of the counter Nc is now proportional to the digital value of Va.
        The time T, during which C is charging is 2^NT where T is the period of the clock.  The output of the integrator, V-, reaches its peak value of Op = -(Vc/Rc)T, at the end of T1.  During T2, C discharges from its initial voltage Vp with a slope of (Vr/Rc).  Time interval T2 when the comparator output switches from high to low, is therefore given by
              (VR/RC) * T2  =  (Va/RC)  * T1    or
                     T2  =  (Va/Vr)*T1

           Since the counter output Nc at the end of T2 is the reference voltage source Vr sets the maximum voltage corresponding to (2^N -1).  Each single -pole double-throw (SPDT) switch connects the corresponding resistor to Vr if the bit bm(k= 0,1,...,(N-1) is 1 ( logic high), or to grund if bm is o(logic low).  CMOS transmission gates, for example, can be used to implement these switches.  The least significant bit(lsb) controls switch so, the next higher bit (bit 1) controls switch S1, and so on to the most significant bit (msb).  The pole of switch Sn-1 is connected to resistor Rn-1 = R.
            TO obtain a current proportional to the bit position, each resistor is binary-weighted according to the bit to which it is connected.  For a 4-bit (N=4) converter, the binary vale ranges from 0000 (decimal 0) to 1111(decimal 15).  Therefore, resistor R2 connecting bit 2 has twice the value of R3 (which connects the msb), R1 has four times R3 and R0 has eight times R3.
            Because of these binary-weighted values of resistors, this circuit is known as a binary-weighted resistor DAC.  The op amp serves as a buffer between the reference source and the output.  Using ideal amplifier characteristics, current  I at the summing (inverting) node (or virtual ground) can be calculated for any of the 16 different input bit combinations when the lsb is 1 and the rest of the bits are 0, that is, for data 0001, current I, into the virtual ground is given by
                       I1  =  VR/R0  = VR/8R
            For data 1000, in which only the msb is 1, current I8 is
               I8  = VR / R3 =  VR/R
Since the network is linear, current for the combination 1001(decimal 9) = 1000(decimal 8) + 0001 (decimal 1) is obtained using superposition as
             I = I9 = I8 + I 1
               = VR/R + VR/8R = VR/R(1 + 1/8)
         Hence, the output voltage V0 for 1001 is
              V0 = - Irf = -Vr (Rf/R) (1+1/8)
         In general, if bk = { 0,1} , for k = 0,1,2,3 represents the input data, with b0 as lsb and b3 as msb, the current at the summing node is given by
              I =  VR( b3/R3 + b2/R2 + b1/R1 + b0/R0)
                = VR/R(b3 + b2/2 + b1/4 + b0/8)
        Hence, the output voltage Vo for the four-bit converter is given by,
               Vo  =   -Vr (Rf/R)(b3+b2/2+b1/4+bo/8)
        This equation demonstrates that the magnitude of output voltage Vo is prorportional to the straight binary value of the input data.  For an N-bit converter employing N binary-weighted resistors R, 2R,..,2^KR...,2^(N-1)R for bits bN-1, bN-2, bN-1-k,...,b0 respectively, in the scheme shown, the current at  the summing node is given by
          I = VR/R (bN-1 + bN-2/2 + ... + bk/(2^(N-K-1))  ...b0/2^(N-1))
             = VR/R  SUM{k=0 to  N-1} (bk/2^(N-K-1))
and the corresponding output voltage is given by
          V0 = - VR * Rf/R(bN-1 + bN-2/2 +...+ bk/(2^(N-K-1))  ...b0/2^(N-1))
                = - VR*Rf/R SUM{k=0 to  N-1} (bk/2^(N-K-1))
                =  - VR/2^(N-1) (Rf/R)SUM{k=0 to  N-1}(bk*2^k)
        By a suitable choice of the reference voltage VR and the resistance Rf and R1 V0 can be varied over any range with each output voltage proportional  to the binary input data.
         The current through each resistor is either zero or a value proportional to the binary weight of the input bit.  This causes different currents to be switched from the reference source as inputs change; consequently, transients occur in the output waveform current transients from VR can be eliminated by connecting the digital SPDT switches at the summing node.  Each switch diverts a constant current from VR to the summing node or to ground.
          To compensate for the bias current effect when all bits are at zero,   a resistance may be connected from the noninverting terminal to the ground.  In bipolar technology, constant current proportional to the binary weights are generated and switched to the summing node, or to ground using diodes or differential amplifiers.
          The binary-weighted resistor network requires a wide range of  precision and tracking resistors or current sources.  For proper digital data tracking, all these resistors must have extremely low tolerances and temperature variations.  In integrated circuits, it is dificult to fabricate a wide range of resistors with high precision.  In addition, unequal amplifier bias (input) currents, though small, can cause significant errors in the output voltage when coupled with a large resistance on the other hand choosing a small value for the msb will drain a large current from the reference supply.
R-2R Resistor Ladder Network: 
       If another rresistor is added for each bit , the range can be reduced from R:2^(N-1) R to R: 2R. With the Thevenin resistance Rt = R and the Thevenin voltage Vt = Vr/2 at the inverting terminal, the input current into the summing node is
          I8    = VR/2 / R  =   VR/2R  for input data 1000
          Hence, the output voltage for input 1000 is
            V0   =   -  VR/2(Rf/R)
       For input data 0001, Rt=R and Vt = Vr/8 which yields
             I1 = Vr/16R
        and V0  =  - Vr/16(Rf/R)
         This discussion shows that, in general, for the 4-bit input b3, b2, b1,b0 the current into the summing node is given by
         I = Vr/R(b3/2 + b2/4 + b1/8+b0/16)
         and the output voltage V0 is
        V0 = - VR/16 (Rf/R)[8b3+4b2+2b1+b0]
      If we extend this equation for an N-bit converter , we get an output voltage of
       V0 = - VR/2 ^ N( Rf/R)[2 ^ (N-1)bn-1 + ... + 2 b1+ b0]
 or 
       V0 = -VR/2^N(Rf/R) SUM{k=0 to N-1} 2^k bk
         Note that the output resistance of the ladder network, that is , resistance seen by the summing  junction, is the same (=R) regardless of the input bit combination.
          The ladder network can be rearranged so that the current from VR  is constant.  Commercial DACs use a pair of NMOS transistors for each bit, to switch the binay-weighted current to the opamp or ground.
            DAC using the  R-2R ladder network are commercially available as monolithic circuits for 6 to 20-bt conversion.  These Ics commonly derive a stable reference voltage from supply voltages and generate an output current proprotional to the binary weight of the input data.  An opamp with a feedback resistor is used to convert this current to the required output voltage range.   
 Signal Processing:-          Most signal processing applications have some kind of real-tie requirements.  We focus here on those whose response times must be under a few milliseconds to a few seconds.  Examples are digital filtering, video and voice compression / decompression, and radar signal processing.
Processing Bandwidth Demands:-
         Typically a real-time signal processing application computes in each sampleing peirod one or more outputs.  Each output x(k) is a weighted sum of n inputs y(i)'s.
               X(k) = SUM{i= 1 to n} a(ki)y(i)
          In the simplest case, the weights, a (k,i)'s ae known and fixed.  In essence this computation transforms the given representation of an object ( e.g., a voice, an image or a radar signal)  in terms of the inputs, y(i)'s into another representation  in terms of the outputs, x(k)'s.  Different  set of weights, a(k,i)'s give different kinds of transforms.  This expression tells us that the time required to produce an output is O(n).
           The processor time demand of an application also depends on thenumber of outputs it is required to produce in each sampling period.  At one extreme, a digital filtering application ( e.g., a filter that suppresses noise and interferences in speech and audio) produce one output each sampling period.  The sampling rates of such applications range from a few KHZ to tens of KHZ,  n ranges from tens to hundreds.  Hence, such an application performs 10^4 to 10^7 multiplication and addition per second.
             The number of output may also be of order n and the complexity of the computation is O(n^2) in general.   Most image compression methods have  a transform step.  This step transforms the space representation each image into a transform representation ( e.g., a hologram).  Let us consider an mXm pixel, 30 frames/sec Video.  The number of inputs n = m^2.  The transformation of each frame  takes m^4 multiplications and additions.  If m is 100 the transformation of video takes 3 X 10 ^ 9 multiplication and additions per second.  One way reduce the computational demand at the expense of the compression ratio is to divide each image into smaller squares and perform transform on each square.  This indeed is what the video compression standard MPEG(ISO94) does.  Each image is divided into squares of 8X8 pixels.  In this way number of multiplication and additions performed in the transform stage is reduced  to 64m^2 per frame.  Video requires a transmission bandwidth of 2.7 Mbits per second. When each component (intensity and colour-luminance and two chrominance) at each pixel is encoded with 3 bits.  MPEG compression makes use of three techniques.  They are motion compensation for reducing temporal redundancy, discrete consine transform for reducing spatial redundancy and entropy encoding for reducing the number of bits required to encode all the information.  Depending on the application, the compressed bit rate ranges from 1.5 Mbits/sec to 35 Mbits/sec.  The achievable compression ratio depends on the content of the video.
 Motion Estimation:-
         Motion estimation step exploits interframe dependency.  The motion-compensation techniques used in this step assume the most small pieces of the image in the current frame can be obtained either by translating in space corresponding small pieces of the image in some previous frame or by interpolating some small pieces in some previous and subsequent frames.  The same way as I-Frame major blocks.
          A B-Frame is a bidirectionally predicted frame.  It is predicted from both the previous I-frame( or P-frame) and the subsequent P-frame( or I-Frame).  One way is to represent every B-frame major block by the differenes between the values of its pixel blocks and the corresponding pixel blocks of the best matching major block in either the previous I-frame or the subsequent P-frame.  Alternatively for each B-frame major block, an interpolation of the best matching major blocks in the I-frame and P-frame is first computed.  The B-frame major block is represented by the difference between it and this interpolation.  Again, the coder generates the motion vectors that the decoder will need to identify the best matching I-frame and P-frame major blocks.  Whereas some P-frame major blocks are encoded independently none of the B-frame major blocks are.
Discrete Cosine Transform and Encoding:-
       A cosine transform is performed on each of the 8X8 pixel blocks produced by the coder after motion estimation we let x(i,j), for i,j =1,2,...8, denote the elements of 8x8 transform matrix obtained from transforming the original marix that gives an 8X8 vlues of a pixel block.  The transform matrix usually has more zeros than the orignal matrix [ In the extreme when all the entries of the original matrix are equal, only X(0,0) is non-zero].  Moreover, if the entries X(i,j)'s are ordered in non decreasing order of i+j, zero entries tend to be adjacent forming sequences of zeros, and adjacent entries tend to have similar values. By quantizing the X(i,j)'s to create more zeros, encoding the entries in the transform matrix as 2-tuples(run length, value) and using a combination of variable-length and fixed-length codes to further reduce the bitrate, significant  compression is achieved.
         Each image is divided in to 16X16 pixel square pieces; they are called major blocks.  The luminance  component of each major block consists of four 8x8 pixel blocks.  Each of thechrominance component has only a quarter of this resolution.  Hence , each chrominance component of a major block is an 8X8 pixel block.
          Only frames 1+ alpha*K, for k= 0,1,2,... are encoded independently of other frames where alpha is an application specified integer constant. These frames are called I-frames (i.e., intra-coded frames).  The coder treats each I-frame as a still image, and the decoder can decompress each compressed I-frame are points for random access of the video.  The smaller  the constant alpha, the more random accessible is the video and poorer the compression ratio A good compromise is alpha = 9. 
          The frames between consecutive I-frames are called P- and B-frames.  When alpha is equal to Q, the sequence  of frames produced by the motion estimation step are I, B, B, P, B, B, P, B, B, I, B, B, P, .... For every K >= 0, frame 1+qk+3 is a p-frame (i.e.,  predictive coded frame).  The coder obtains a p-frame from the previous I-frame (or P-frame) by prediction how the image carried by the I-frame changes in the time interval between the times of these frames, speifically, if a major block in the p-frame closely resembles a major block in the p-frame  closely resembles a major block in the previous  I-frame , then the coder represents the p-frame major block by six 8X8 pixel blocks that give the difference between six P-frame pixel block and corresponding pixel blocks of the best matching (i.e., resembling most closely).  Major block in the previous I-frame.  In additon, the coder generates amotion vector based on which the decoder can identify the best matching I-frame major block.  Such a P-frame major block is said to be predictively coded.  On the other hand some P-frames major blocks may be images of newly visible objects and, hence, cannot be obtained from any major block in the previous I-frame.  The coder represents them in.
Decompression :-
         During decompression, the decoder first produces a close approximation of the original matrix ( ie., an 8x8 pixel block) by performing an inverse transform on each stored transform matrix (The computation of an inverse transform is the essentially the same as the cosine transform).  It then reconstruct the images in all the frames fro the major blocks in I-frames and difference blocks in P- and B-frames.
Radar System:-
           Radar signal processing and tracking system consists of an Input/Output(I/O) subsystem that samples and digitizes the echo signal from the radar and places the sampled values in a shared memory.  An array of digital signal processors processes these sampled values.  The data thus produced are analyzed by one or more data processors which not only interface with the display system, but also generate commands to control the radar and select parameters to be used by signal processors in the next cycle of data collection and analysis.
Radar Signal Processing:-
           To search for objects of interest in its coverage area, the radar scans the area by pointing its antenna in one direction at a time.  During the time the antenna dwells in a direction, it first sends a short radio frequency pulse.  It then collects and examines the echo signal returning to the antenna.
          The echo signal consists solely of background noise if the transmitted pulse does not hit any object on the other hand, if there is a reflective object (e.g., an airplane or storm cloud) at a distance x meters from the antenna, the echo signal reflected by the object return s to the antenna at approximately 2x/c seconds after the transmitted pulse, where C= 3X10^8 m/s is the speed of light.
          The echo signal collected at this time should be stronger than when there is no reflected signal.  If object is moving, the frequency of the reflected signal is no longer equal to that of the transmitted pulse.  The amount of frequency shift ( called Doppler Shift) is proportional to the velocity of the object.  Therefore by examining the strength and frequency spectrum of the  echo signal, the system can determine  whether there are objects in the directin pointed at by the antenna and if there are objects, what their positions and velocities are.
             Specifically, the system divides the time during which the antenna dwells to collect the echo signal into small disjoint intervals each time intrval corresponds to a distance rante, and the length of the interval is equal to the range resolution divided by C. (for example if the  distance resolution is 300m  then the range  interval  is one microsecond long).  The digital sampled values of the echo signal collected during each range interval are placed in a buffer called a bin .  The sampled values in each bin are the inputs used by a digital signal processor to produce of objects.  A track record on a nonexisting object is called a false return.  An application that examines all the track records in order to sort out false returns fro real ones and update the trajectories of detected objects is called a tracker using the jargon of the subject area, we say that the tracker assigns each measured value(ie., the tuple of position and velocity contained in each of the track records generated in a scan) to trjectory.  If the trajectory is an existing one, the measured value assigned to it gives the current position and velocity of the object moving along the tranjectory.  If the trajectory is new, the measured value gives the position and velocity of a possible new object.  In the example tracker runs on one or more data processors which communicate with the signal processors via the shared memory.
Gating:-
         Typically, tracking is carried out in two steps: gating and data association.  Gating is the process of putting each measured value into one of two categories depending on whether it can or cannot be tentatively assigned to one or more established trajectories.  The gating process tentatively assigns a measured value to an established trajectory if it is within a threshold distance G away from the predicted current position and velocity of the object moving along the trajectory ( Below, we call the distance of the assignment ).  The threshold G is called the track gate.  It is chosen so that the probability of a valid measured value falling in the region bounded by a sphere of radius G centered around a predicted value is a desired constant.
        At the strart, the tracker computes the predicted position (and velocity) of the object on each established trajectory.  In this example, there are two established trajectories output.  These output represents a discrete fourier transform of the corresponding segment of the echo signal.  Based on the characteristics of the tansforms the signal processor decides whether there is an object in that distance range.  If there is an object, it generates a track record containing the position and velocity of the object and places the record in the shared memory.
           The time required for signal processing is dominated by the time required to produce the fourier tranforms, and this time is nearly determinsitic. The time complexity of Fourier Transform (FFT) is O(nlogn), where n is the number  of sampled values in each range bin.  N is typically in therange from 128 to a few thousand.  So, it takes roughly 10^3 to 10^5 multiplication and additions to generate a Fourier transform.  Suppose that the antenna dwell s in each direction for 100ms and the range of the radar is divided into 1000 range intervals.  Then the signal proessing system msust do 10^7 to 10^9 multiplications and additions per second.  This is well within the capability of todays DSP.
            However, the 100ms dwell time is a ball park figure for a mechanical radar antennas.  This is orders of magnitude larger than that of phase array radars,  such as those used in many military applications.  A phase array radar can switch the direction of the radar beam scanning the coverage area and tracking individual objects at the some time.  Since the radar can collect data orders of magnitude faster than the rates stated above, the signal procesing throughout demand is also considerable higher.  This demand is pushing the envelope of DSP technology.
 Tracking:-
           Strong noise and man-made interferences, including electronic counter mesure (i.e., jamming) can lead the signal processing and detection process to wrong conclusions about the presence L1 and L2.  We also call the predicted positions of the objects on these tracks L1 and L2.  X1, X2 and X3 are the measured  values given by three track records.  X1 is assigned to L1 because it is within distance G from L1.  X3 is assigned to both L1 and L2 for the same reason on the other hand, X2 is not assigned to any of the trajectories.  If presents either a false return or a new object.  Since, it is not possible to distinguish between these two cases, the tracker hypothesizes that X2 is the position of a new object.  Subsequent radar data will allow the tracker to either validate or invalidate this hypothesis.  In the latter case, the trakcer will discard this trajectory fro further consideration.
Data Association-
            The tracking process completes if, after gating, every measured value is assigned to at most one trajectory and every trajectory is assigned at most one measured value.  This is likely to be case when (1) the radar signal is strong and interference is low ( and hence false returns are few) and(2) the density of objects is low under adverse conditions, the assignment produced by gating may be ambiguous, that is , some measured value is assigned to more than one trajectory or a trajectory is assigned more than one measured value.  The data association step is then carried out to complete the assignments and resolve ambiguities.
       There are many data association algorithms.  One of the most intuitive is the nearest neighbour algorithm.  This algorithm works as follows:
1	Examine the tentative assignments produced by te gating step
a.   For each trajectory tht is tentatiely assigned a single unique measured value, assign the measured value to the trajectory.  Discard from further examination the trajectory and the measured value, together with all tentative assignments involving them.
b. For each mesured value that is tentatively assigned to a single trajectory, discard the tentative assignments of those measured values that are tentatively assigned to the trajectory if the values are also assigned to some other trajectories.
1	  Sort theremaiing tentative assignments in order of nondecreasing distance.
2	   Assign the measured value given by the first tentative assignment in the list to the corresponding trajectory and discard the measured value and trajectory.
3	  Repeat Step(3) until the list of tentative assignments is empty.
        In the example the tentative assignment produced by the gating step is ambiguous. Step ( 1a)  does not eliminate any tentative assignment.  However step (1b) finds that X1 is assigned to only L1, while X3 is assigned to both L1 and L2.  Hence, the assignment of X3 to L1 is discarded from further consideration.  After step (1), there still are two tentative assignments, X1 to L1 and X3 to L2.  Step (2) Leaves them in this order, and the subsequent steps make these asignments.  X2 initiates a new trajectory.  If during subsequent scans, no measured values are assigned to the new trajectory, it will be discarded from further considerations.  
          The nearest neighbour algorithm attempts to minimize a simple local objectie function.  The distance(beween the measured and predicted values) of each assignment. Data associaton algorithms of higher time complexity are designed to optimize some global, and therfore more complicated, objective functions, for example, the sum of distances of all assignments and probability of errors.  The most complex in both time and space is the class of multiple hypotheseis tracking grow exponentially with the maximum number of hypotheses, the external being the number of scans required to eliminate each false hypothesis.  Without modern fast-processors and large memory, multiple hypothesis tracking would not be feasible.
         The operation of the radar is controlled by a controller that executes on the data processor.  In particular, the controler may alter the search strategy or change the radar operation mode (Say from searching to trackig an object) depending on the results found by the tracker.  (as the mentioned earlier, a phase-array radar can redirect its beam in any direction in less than a millisecond.  This capability makes it possible to dynamically adapt the operation of the radar system to changes i the detected scenario).  Similarly, the controller may alter the signal processing parametrs (e.gs., detection threshold and transform type) in order to be more effective in rejecting interferences and differentiating objects.  The responsiveness and iteration rate of this feedback process increase as the total response time of signal processing and tracking decreases.  For this reason, the developers of these applications are primarily concerned with their throughputs and response times.

Final Control:-
        The mesurement and evaluation of some process variablel is carried out using a low-energy analog or digital signal to represent the variable.  The control signal that carries feedback information back to the process for necessary corrective action is expresssed by te some low level of representation.  In general the controlled process itself may involve a high-energy condition, such as the how of thousands of cubic meters of liquid or several hundred thousand newton hydraulic forces, as in a stell rolling mill.  The function of the final control element is to translate low-energy control signals into a level of action commensurate with the process under control.
           A sensor used to measure some variable in a process-control application should have negligible effect on the process itself.  The final control element has a profound effect on the process possessive operational mechanisms.
Signal Conversion:-
           Controller output signals are typically in one of three forms (1) electric current, usually 4 to 20 mA (2) Pneumatic pressure, usually 3 to 15 psSi or 20 to 100 K PA and (3) digital signals usually TTL-Levels voltages in serial or parallel format.
 Relays:-
          Solid-State relays or electromechanical relays can be used for simple ON/OFF or two-position control. Silicon Controlled Rectifier (SCR).  SCR will conduct in only one direction.  SCR is forward biased (Positive voltage at anode and negative voltage to cathode ) it will not conduct.  When voltage is placed on the gate with respect to the cathode, if he gate voltage is taken away after a time, it will stay on regardless of the gate with respect to the cathode, if the gate voltage is taken away after a time, it will stay on regardless of the gate.  To switch-off  the SCR the voltage must drop below the forward voltage drop of the SCR so that the current drops below a minimum value called the holding current, or the polarity from anode to cathode must actually reverse.
TRIAC - TRIAC is a device thta can be triggered to conduct in either direction.  A positive trigger will cause it to conduct in one direction and a negative trigger will cause it to conduct in other direction.
 Actuators:-
           If a value is used to control fluid flow. some mechanisms must physically open or close the valve.  These are the examples of the requirements for an actuator in the process-control loop.  Solenoid - A solenoid is an elementary device that converts an electrical signal into mechanical motion, usually rectilinear(in a straight line).  Solenoid consist of a coil and plunger.  The plunger may be freestanding or spring loaded.
Electric Motors -
             DC motors, AC motors and stepping motors.
Control Elements:-
 Mechanical - Paper thickness control application, the mechanical control element is the movable roller, by varying the roller separation paper thickness is regulated.
Electrical-Speed of large electrical motors depends on the supply voltage level, load and others.
Temperature often is controlled by using electrical heaters.
Fluid Valves – Flow rate is volume per unit time ie 
        Q = AV
             Q  -   Flow rate (m^3/S)
              A -  Pipe Area (m^2)
              V – flow velocity (m/s)
Equal percentage – Rangeability, R = Qmax/Qmin
Q    = Qmin * R ^ s/smax

Controller Principles:-
         The equations necessary to obtain control  exist in only a few forms, independent of both the process itself and whether the controller  function is provided by an analog or digital computer.  These equations describe the modes or action of convroller operations.  The nature of preocess itself  and the particular variable controlled determine which mode or modes of control are to be used and the value of certain constants in the mode equations.

Process Characteristics
1	Process Equation
       A process-control loop regulates some dynamic variable in a process.  This controlled variable, a process parameter depends on many other parameters and suffer changes from many different sources we have selected one of these other parameters to be our controlling parameter.  If a measurement of the controlled variable shows a deviation from the set point, then the controlling parameter is changed which in then changes  the controlled variable.  In many cases the relationship between controlled variable and controlling parameter is not even analytically known.
1	  Process Load
           From the process equation, or knowledge of an experience with the process, it is possible to identify a set of values for the process parameters that result in the controlled variable having the setpoint value.  This set of parameters is called the nominal set.  The term process load refers to this set of all parameters, excluding the controlled variable.  If the setpoint is changed the control parameter  is alered to cause the variable to adopt this new operating point.  They are concerned only that variation in the controlling parametr brings the controlled variable back to the setpoint.  A transient is not a load change because it is not permanent.
1	Proess Lag:-
         At   some point in time process load change or transient causes a change in the controlled variable. A process-control loop ensures that some finite time later, the variable returns to setpoint value.  Part of this time consumed by process – itself and called the process lag. 
1	Cotrol Lag:-
           The control system also has a lag associated  with its operation that must be compared to the process lag.  When a controlled variable experienes a sudden change, the proess control loop reacts by outputting a command to the final control element to adopt a new value to compensate for the detected change.  Control lag refers to the time for the process control loop to make necessary adjustments to the final control element.
1	Dead Time:-
           Another time variable associated with process control is a fuction of both the process control system and the proess.  This is the elapesed time between the instant a deviation (error) occurs and when the corrective action first occurs.  A control system quickly changes a value setting to adjust flowrate but it takes time for the new flow rate to move down the length of the pipe.
1	 Cycling:-
         We frequently refer to the behaviour of the dynamic variable error under various modes of control.  One of the most important model is an oscillation of the error about zero.  This means the variable is cycling above and below the setpoint value.  Such cycling may continue indefinitely, in which case we have steady-state cycling.  Here we are interested in both the peak amplitude of the error and the period of the oscillation.
        If the cycling amplitude decays to zero, however we have a cyclic transient error. Here we are interested in the initial error, the period of the cyclic oscillation, and decay time for the error to reach zero.
1	Controller Modes:-
      In discontinous mode controller command initiates a discontinous change in control parameter.  In continous mode smooth variation of control parameter is possible.
      Reverse and Direct Action:-   When an increasing value of the controlled variable causes an increasing value of the controlled output is direct action.  When an increase in controlled variable causes a decrease in controller output is reverse action.
1	Self-Regulation:-
          Self-Regulation is the tendency to adopt a specific value the controlled variable for nominal load with no control operation.  An example of a process without a self-regulation is a tank from which liquid is pumped at a fixed rate.  Assume that the influx just matches the outlet rate.  Then the liquid in the tank is fixed at some nominal level.  If the influx increases slightly, however, the level rises until the tank overflows.  No self-regulation of the level is provided.
Control System Parameters:-
           (1) Error:-
                          The deviation or error of the controlled variable from the setpoint is given by
                        e = r-b
where 
                       e=error, b=measured indication of variable 
                       r=setpoint of variable (reference)
      Thus if the setpoint  in a 4 to 20 mA range corresponds to 9.9mA and the measured value is 10.7maA, we have an error of -0.8mA.
                       EP   =  (r-p)/(bmax-bmin)  x 100
                       EP – error expressed as percent of span
      setpoint = 10.5 mA and Measured Value = 13.7mA
                      EP =  (10.5mA – 13.7mA)/(20mA-4mA) X 100 = - 20 %
       Positive error indicates measurement below setpoint, and a negative error indicates a mesurement above the setpoint.
(2)  Variable Range :-
             Generally, the variable under control has a range of values within which control is to be maintained.  This range can be expressed as the minimum and  maximum value of the variable or the nominal value plus and minus the spread about this nomina.
  (3) Control Parameter Range:-
               Another range is associated with the controller output.  Here we assume the final control element has some minimum and maximum effect on the process
Control System
        There are two categories of control system (i) open-loop the control inputs are not influenced by the plant outputs. That is , there is no feedback around  the plant.
      Open-loop system has the advantage of simplicity, but its performance is highly dependent upon the properties of the plant which may vary with time.  The carburetor and the engine comprise a common type of control system wherein a larger-poer output is controlled with a small-power input.  In the graph, if the nominal curve is used,  a throttle angle of 80 produces an engine speed of 2300rpm. Suppose  a new curve, a throttle angle of 80 produces an engine speed of only 1000 rpm.  It may not be acceptable to have a sysem output change when other values changes.
II	Closed-Loop or Feedback Systems:-
        A path(or loop) is provided from the output back to the controller.   Some or all the outputs are measured and used by the controller. The controller may then compare a desired plant output with the actual output and act to reduce the difference between the two.
Discontinous Controller Modes
 Two Position Mode:-
          The most-elementary controller mode is the ON/OFF or two position mode.  This is an example of discontinous mode. P(%)
          The range 2Delta(Ep) which is referred to as the neutral zone or differential gap is often purposely designed above a certain minimum quantity to prevent excessive cycling. The existence of a such a neutral zone is an example of desirable hysteresis in a sytem.
Multiposition Mode:-
           A logical extension of the previous two-position control mode is to provide several intermediate rather than only two, settings of the controller outpu.  This discontinous control mode is used in an attempt to reduce  the cycling behaviour and overshoot and undershoot  inherent in the two-position mode.
          P = pi;  ep > |ei| i = 1,2,....,n
          As the error exceeds certain set limits!= ei the controller output is adjusted to preset values pi.
          P = {  100   ep  >  e2
                     50  -e1  <  ep  < e2
                        0  ep < - e1
Floating -Control Mode
           In the two previous mode of controller action, the output uniquely determined by the magnitude of the error input.  If the error exceeded some preset limit,  the output was change to a new setting as quickly as possible.  In floating control, the specific output of the controller is not uniquely determined by the error.  If the error is zero, the output does not change but remains(floats) at whatever setting it was when the error went to zero when the eror moves off zero, the controller output again begins to change.
           In the single-speed floating-control mode, the output of the control element changes at a fixed rate when the error exceeds the neutral zone.
           Dp/dt = +/- Kf |ep| > Delta(ep)
           dp/dt  -  rate of change of controller output with time
           Kf      -  rate constant (%s)
           Delta(ep) – half the neutral zone.
If equation (1) is integrated for the actual controller outpt, we get
           P = +/- Kpt + P(0)    |ep|  > delta(ep)
where p(0)  = controller output at t = 0
which shows that the present output depends on the time history of errors that have previously occurred.  Because such a history is not known, the actual value of P floats at an undertermined value.  If the deviation persists, then equation (2) shows that the controller saturates at either 100% or 0 % and remains there until an error drives it toward the opposite extreme.
Continous Controller Modes
            In these modes, the output of the controller changes smoothl in response to the error or rate of change of error.
Proportional Control Mode:-
            The two-position mode had the controller output of either 100% or 0%, depending on the error being greater or less than the  neutral zone.  In multiple-step modes, more divisions of controller outputs versus error are developed.  The natural extension of this concept is the proportional mode, where a smooth, linear, relationship exists between the controller output and the error.  Thus, over some range of errors about the setpoint, each value of error has a unique value of controller output in one-to-one correspondence.  The range of error to cover the 0% to 100% controller output is called the proportional bond, becaue the one-to-one correspondence exists only for errors in this range.
                    P= Kpep  + P0
      Kp  -  Proportional gain between error and controller output (% per %)
      P0   -  Controller output with no error(%)
                 proportional band is defined by the equation 
                      PB =  100/Kp
Offset:  An important characteristics of the proportional control mode is that it produces a permanent residual error in the operation point of the controlled variable when a change in load occurs.  This error is referred to as offset.  It can be minimized by a larger constant Kp, which also reduces the proportional band.
           For high gain the proportional mode causes oscillations of the error.
Integral-Control Mode:-
         The offset error of the proportional mode occurs because  the controller  cannot adopt to changing external  conditions – that is, changing loads.  In otherwords, the zero-error output is a fixed  value.  The integral mode eliminates this problem b allowing the controller  to adopt to changing external conditions by changing the zero-error output.
          The need for integral action shows up when it is noted that even with proportional action correction, the error does not go to zero in time.  Suppose a system has some error, ep, and the proportional mode provides a change in controller output, KpEp.  As we watch the error in time,  we note that the error may reduce, but it does not go to zero. In fact , it may become constant.
            Integral action is provided by summing the error over time,  multiplying  that sum by a gain, and adding the result to the present  controller  output.  If the error makes random excursions above and below zero, the net sum will be zero, so the integral action will not contribute.  But if the error becomes positive or negative for an extended period of time, the integral action will begin to accumulate and make changes to the controller output.
       In the mathematics of continous functions, such as error, summation is represented by integration.
        P(t) =  Ki Integral{0 to t} (epdt + p(0))  [dp/dt = kiEp]
    where P(0) is the controller output when the integral action starts. The gain K1 expresses how much controller output in percent is needed for every percent-time accumulation of error.
The characteristics of the integral mode
       1.    If the error is zeor, the output stays fixed a a value equal to what it was when the error went to zero.
2.   If the error is not zero, the output will begin to increase or decrease at a rate of Kpercent/Second  for every 1% of error.
Derivative Control Mode
        Even though the error at X-axis (T0) is zero, it is changing in time and will certainly not be zero in the following time.  Therefore some action should be taken even though the error is zero.
         Derivation controller responds to the rate at which the error is changing that is, the derivative of the error.
             P(t)  = Kd  * dep/dt
          where the gain, Kd, tells us by how much percent to change the controller output for every percent-per-second rate of change of error.  Derivative action is not used alone because it provides no output  when the error is constant.
            Derivative controller action is also called rate action and anticipatory control. The derivative made must be used with great care and usually with a small gain, because a rapid rate of change of error  can cause very large, sudden changes of controller output.  Such an event can lead to instability.
The Characteristics of derivative mode
      1.  If the error is zero, the mode provides no output 
      2.  If the error is constant in time, the mode provides no output 
      3.  If the error is changing in time, the mode contributes an output of Kd percent for every 1% per-second rate of change of error.
       4.  For direct action, a positive rate of change of error produces a positve derivative mode output.

Proportional-Integral Control:-
          P = KpEp  +  KpKi Integral{0 to t} (epdt + P1(0))
          P1(0)  = integral term value at t= 0 (initial value)
          The main advantage of this composite control mode is that the one-to-one correspondence  of the proportional mode is available and the  integral mode eliminates the inherent offset.
           The integral function provides he required new controller output  there by allowing  the error to be zero after a load change.  The controller output  is provided through a sum of proportional  plus integral action that finally leaves the error at zero.
The characteristics  of the PI mode:-
1	When the error is zero, the controller output is fixed at the value that the integral term had whe the error went to zero.  This output is given by P1(0) simply because we chose to define the time at which  observation starts at t=0.
2	If the error is not zero, the proportional term contributes a correction, and the integral term begins to increase or decrease the accumulated value[initially P1(0)], depending on the sign of the error and the direct or reverse action.
 The integral term cannot become negative.  Thus it will saturate  at zero if the error and action try to drive the area to a net negative value.
The mode may be used in systems with frequent or large load changes  Because of the integration time, however the process must have relatively slow changes in load to prevent oscillations induced by the integral overshoot.
Proportional-Derivative Control Mode (PD)
          This system cannot eliminate the offset of proportional controllers. It can, however, handle fast process load changes as long as the load change offset error is acceptable.  The effect of derivative action in moving the controller output is relation to the error rate change.
Three-Mode Controller (PID)
         One of the most powerful but complex controller mode operation combines the proportional , integral , and derivative modes.  This system can be used for virtually any process condition.
             P =  KpEp +  KpKt Integral{ 0 to t} epdt + Kp Kd dep/dt + P1(0)
           This mode eliminates the offset of the proporitonal mode and still provides fast response.  In the real world the sharp breaks in output  do not occur.
            Three-mode (PID) controller with opamps.
-Vout  = (R2/R1)Ve + (R2/R1) * 1/R1C1 Integral{Vedt} + (R2/R1)RpCd *dVe/dt + Vout(0)
  where R3 has been chosen from 2*Pi*Fmax*R3Cd = 0.1 for stability.
           Gp  = R2/R1; Gd =  RdCd ; Gi =  1/ R1C1
Process-Loop Tuning
       Open-loop transient response method.
      This method of finding controller settings was developed by Ziegler and Nichols and is sometimes referred to as a process   reaction method.  This method can be used only for systems with self-regulation.
        A tangent line is drawn at the inflection point of the curve where the tangent crosses the origin we get.
                  L  = log time in minutes
        The process reaction time(T),
                  N = delta(cp)/T  N = reaction rate in  % / min
                                            delta(Cp) = variable change in %
                                            T = process reaction time in minutes
Log ratio ( Cohen and Coon)
                 R = NL / Delta(Cp)
Kp = 1.2 Delta(P)/ NL
Ti  =  2 L
Td  =  0.5 L
If the quarter-amplitude criterion is used
         Kp = P/NL [1.33 + R/4]
         Ti   = [(32 + 6R)/(13+8R)] * L
          Td = L ( Delta/(11 + 2 R))
Ziegler -Nichols Method:-
         This technique, also called the ultimate cycle method , is based on adusting a closed loop until steady oscillatlions occur.  Controller settings are then based on the conditions that  generate the cycling.
1	Reduce any integral and derivative ations to their minimum effect.
2	Gradually begin to increase the proporitonal gain while providing periodic small disturbances to the process.
3	Note the critical gain, kc, at which the dynamic variable just begins to exhibit steady cycling – that is , oscillaltions about the set point.
4	Note the critical period, Tc, of these oscillations mesured in minutes.
Three-mode:-
          Kp = 0.6 Kc
           Ti = Tc/2.0
  Td  =  Tc / 8
For adjustment to give quarter-amplitude response, we get
            T1  =  Tc/15
            Td  =  Tc / 6
and adjust the proprotional gain for satisfaction of the quarter amplitude response.
Discrete-State Process Control:-
             Let us suppose that all measurement input variables( S1,S2,S3) and all control output variables ( C1,C2,C3) of the process can take an or be assigned only two values.  No a discrete state of the process at any moment to tbe the set of all input and output values.  Each state is discrete in the sense that there is only a discrete number of possible states.  If there are three input variables and three output variables, then a state consists of specification of all six values.  Because each variable can take two values, there is a total of 64 possible states.
              An event in the system is defined by a particular state of the system that is particular assignment of all output values and a particular set of the input variables. The event lasts for as long as the input variables remains in the same state and the output variable are left in the assigned state.
         Discrete-state process control is a particular sequence of events through which the process accomplished some objective.
Ladder Diagram:
  The ladder diagram is a symbolic and schematic way of represent both the system hardware and the processor controller.  It is called a ladder diagram because the various circuit devices connected in parallels across the ac line from something that looks like a ladder, with each parallel connection a 'rung' on the ladder.  In the construction of a ladder diagram, it is understood that  each rung of the ladder is composed of a number of conditions or input states and a single command output. The nature of the input states determines whether the output is to be energized or not energized.
Programmable Logic Controller:-
          The modern solution for the problem of how to provide discrete state control is to use a computer-based device called a programmable controller (PC) or programmable logic controller (PLC)
          Processor-  The heart of  a PLC is a microprocessor, much like the ones used in modern personal computers.  It is now possible to employ a desktop personal computer with data I/O boards runing PLC s/w to emulate PLC operation.
Input Modules-  The input modules examine the state of physical switches and other input devices and put their state into a form to provide 0 or 110 V ac to the input module.
Output Modules:-  The output modules supply ac power to external devices such as motors, lights, solenoids, and so on; just as required in the ladder diagram.  The output module can supply a certain maximum power.
PLC operation:-
         The operation is not simultaneous for the entire ladder diagram and is not continous as it is for relay sequences.  Operation of the programmable controller can be considered in two modes the I/O scan mode and the execution mode.
I/O  Scan Mode:-
         During the I/O scan mode, the processor updates all outputs and inputs the state of all inputs one channel at a time.  The time required for this depends on the speed of the processor.
Execution Mode:-
           During this mode, the processor evaluates each rung  the ladder diagram program that is being executed sequence starting from the first rung and proceeding to the last rung.  A rung is evaluated, the last known state o feach switch and relay contact in the rung is considered, and if any TRUE path to the output device is detected , then that output is indicated to be energized-that is, set to ON.
              At the end of the ladder diagram, the I/O mode is entered again, and all output devices are provided with the ON or OFF state determined from execution of the lader diagram program.  All inputs are sampled, and the executon mode starts again.
Scan Time:-
         An important charcteristic of the programmable controller is how much time is required for one complete cycle of I/O and execution.  Of course this depends o how many input and output channels are involved and on the length of the ladder diagram program.  A typical maximum scan/execution time is 5 to 20 ms.
         The length of time for one scan consists of three parts (1) input time
(2) execution time and (3) output time.  Most of the scan time comes from the execution phase.
Correlation and Convolution:-
        Applications to establish similarity between one set of data and another are found in 
     (a) image processing for robotic vision
      (b) remote sensing  by satellite in which data from different images is compared
     (c) inradar and sonar systems for range and position findng in which transmitted and reflected waveforms are compared.
    (d) in the detection and identification of signals in noise
     (e) in control engineering for observing the effect of input on outputs
     (f)  in the identification of binary codewords in PCM systems using Correlation detectors.
      (g)  in the computation of avg. power in wave forms 
       (h)  as an integral part of the least squares estimation techniques and
      (i)  Climatology
Convolution process is essentially the correlatin of two data sequenes in which one of the sequences has been reversed.  The process of convolution gives the output from a system which filters the input.
     Correlation Description:-
           Considering two data sequences each consisting of simultaneously sampled values taken from the two corresponding waveforms.  If the two waveforms varied similarly point for point, then a masure of their correlation might be obtained by taking the sum of the products of the corresponding pairs of points.  If two independent and random data sequences is considered the sum of the products will tend towards a vanishingly small random number as the number of pairs of points i.e., increased.  The existence of finite sum indicate a degree of correlation negative sum indicate negative correlation that increase in one variable is associated with decrease in the other variabl.  The cross-correlation r12(n) between two data sequences x1(n) and x2(n) each containing N data might therefore be written as 
                 r12    =  SUM{n=0 to N-1}  x1(n)  *  x2(n)
     This difinition of cross-correlation, however produces a result which depends on the number of sampling points taken.  This is corrected for by normalizing the result to the number of points by dividing by N.  Alternatively this may be regarded as averaging the sum of products.
                           R12 = 1/N SUM{n=0 to N-1} x1(n) * x2(n)
                           R12(j) = 1/N SUM{n = 0 to N-1} x1(n) * x2(n+j)
                                     = r21(-j) = 1/N SUM{n=0 to N-1} x2(n) x1(n-j)
          In practice when two waveforms are correlated their phase relationship will probably not be known and so the correlation will be computed for a number of different lags in order to establish the largest value of the correlation which is then taken to be the correct value.
        When x1(n) = x2(n) The waveform is then cross-correlated with itself.  This process is known as auto correlation
                          r11(j) = 1/N SUM{ n = 0 to N-1} x1(n) * x2(n+j)
                          r11(0) = 1/N SUM{n=0 to N-1} x1^2(n) = S
where S is the normalized energy of the waveform.
           If the waveform is completely random, for example corresponding to that of white, gaussian noise in an electrical system, then the autocorrelation will have its peak value at zero lag and will reduce to a random fluctuation of small magnitude about zero for lags greater than unity.  This constitutes  a test for random wave forms.
                        R11(0)  >= r11(j)
Convolution Description:-
            Convolution describes amongs the other things, how the input to a system interacts with the system to produce the output.  Generally the system output will be a delayed and attunuate or amplified version of the input.  It is particularly useful to consider the output from the system owing to an impulse input.  Because any input may be represented as a sequence of impulses of different strengths.  The output of the system owing to the impulse input will not be a corresponding impulse, but will vary with time, passing through maximum.
              Sequence of impulses x(m) to the system applied at the sampling instants m, the output at instant O is Y(0) is given by.
               Y(0)  =  h(0) * x(0)
                Y(1) = h(1) * x(0) + h(0) * x(1)
                Y(2) = h(2)*x(0) + h(1) * x(1) + h(0) * x(2)
                 .
                 .
                 .
                 Y(n) = h(n) * x(0) + h(n-1)*x(1) + ... + h(0)* x(n)
                    or
                   Y(n)  =  h(0)* x(n) + h(1)*x(n-1)+...+h(0)*x(0)
                    Y(n)  =  SUM{m = 0 to n} h(n-m) * x(m)
                     Y(n) =  SUM{m=0 to n} h(m) * x(n-m) = h(n)*x(n)
Control System:-
            A process control system is used to regulate the value of some process variable. The variable used to measure the performance of the control system is the error, e(t) which is the difference between the constant setpoint or reference value, r, and the controlled variable, c(t)
                      e(t)   =   r – c(t)
Since the value of the controlled variable may vary in time so may the error.
Control System Objective:-
            In principle, the objective of a control system is to make the error exactly zero, but the control system responds only to errors.  Conversely, if the error were zero and stayed zero, the control system would not be doing anything and would not be needed in the first place.  Therefore this objective can never be perfectly achieved, and there will always be some error.  The question of evaluation becomes one of how large the errors is and how it varies in time.
         A practical statement of control system objective is best represented by three requirements.
1	The system should be stable
2	The system should provide the best possible steady-state regulation
3	The system should provide the best possible transient  regulation
4	Stability:-
       The purpose of the control system is to regulate the value of some variable. This requires that action to be taken on the process itself in response to a measurement of the variable.  If this is not done correctly, the control system can cause the process to become unstable.  Following figure shows prior to the turning on a control system, the controlled variable drifts in a random fashion and is not regulated.  After the control system is turned on, the variable is forced to adopt the setpoint value and is well for a while.  Notice that some time later, how the variable begins to exhibit growing oscillations of value-that is, an instability.  This occurs even though the control system is still connected and operational in fact, it occurs because the system is connected and operational.
              The first objective is simply that the control system must be designed and adjusted so that the system is stable.  The typically as the control system is adjusted to give better control, the likelihood of instability also increases.
Steady-State Regulation:-
            The objective of the best possible steay-state regulation simply means that the steady-state error should be a minimum.  Generally, when a control system is specified thee will be some allowable deviation, +/DeltaC about the setpoint.  This means that variations at the variable within this band are expected and acceptable.  External infuences that tend to cause drifts of the value beyond the allowable deviation are corrected by the control system.
                 For example, a process-control technologist might be asked to design and implement a control system to regulate temperature at 150'c within I2C.  This means the setpoint is to be 150'C, but the temperature may be allowed to vary within the range of 148'c to 152'c.
Transient Regulation:-
                    Suppose the setpoint in the aforementioned temperature case were suddenly changed to 160'c.  Transient regulation specifies how the control system reacts to bring the temperature to this new setpoint.
                     Another type of transient influence is a sudden change of some other process variable.  The controlled variable depends on other process variables.  If one of them suddenly changes value, the controlled variable may be driven to change also to the control system acts to minimize the effect.  This is called transient response.
Evaluation Criteria:-
Damped Response:-
          The error is of only one polarity ( ie., never oscillates about the setpoint). Measures of quality are the duration, tD of the excursion and , for the transient, the maximum error, emax, for a given input.  The duration is usually defined as the time taken for the controlled variable to go from 10% of the change to 90% of the change following a setpoint change.  In the case of a transient, the duration is often defined as the time from the start of the disturbances until the controlled variable is again within 4% of the reference.
         Different tuning will provide different values of emax, and to for the some excitation.
Cyclic Response:-
           Another type of criterion applies to those cases in which the response to a setpoint change or transient is as should note that the controlled variable oscillates about the setpoint.  In this case, the parameters of interest are the maximum error emax and the duration, tD, also called the settling time.  The duration is measured from the time when the allowable error is first exceeded to the time when it falls within the allowable error and stays. 
               The nature of the response is modified by adjusting the control loop parameters, which is called typing.  There may be large maximum error but short duration or long duration with small maximum error and everything in between.
                 Two common types are minimum area and quarter amplitude.   In minimum area, the thing is adjusted until the net area under the error-time curve is a minimum, for the same degree of excitation.
                A = Integral { |e(t)| dt = minimum
The quarter amplitude criterion, specifies that the amplitude of each peak of the cyclic response be a quarter of the preceding peak.  Thus a2 = a1/4 a3=a2/4 and so on.
High Level Controls:-
      Controllers in a complex monitor and control system are typically organized hierarchically.  One or more digital controllers at the lowest leel control the physical plant.  Each output of a higher-level controller is a reference input of one or more lower-level controllers.  With few exceptions, one or more of the higher-level  controllers interfaces with the operator(s).
Examples of Control Hierarchy:-
          For example, a patient care system may consist of microprocessor-based controllers that monitor and control the patients blood pressure, respiration, glucose, an so forth.  There may be a higher-leel controller (eg., an expert system) which interacts with the operator ( a nurse or doctor) and choose the desired values of these health indicators  While the computation done by each digital controller is simple and nearly deterministic, the computation of  high-level controller is likely to be for more complex and variable. While the period of a low-level control-low computation ranges from milliseconds to seconds, the periods of high level control-law computations may be minutes, events hours.
              The hierarchy of flight control, avionics and air traffic control system ie the complex .  The Air Traffic Control (ATC) system is as the highest level regulate the flow of flights to each destination airport.  It does so by assigning to each aircraft an arrival time at each metering fix(or way point) en route to the desirable trajectories among all trajectories that meet the constraints of the system.  The trajectory is most desirable because it optimizes some cost functions.  The algorithms used for this purpose is the solution(s) of some constrianed optimization  problem(s).
    As an example in flight management system, the constraints that must be satisfied by the chosen flight path include the ones imposed  by the characteristics of the aircraft, such as the maximum and minimum allowed crusie speeds and decent/accent rates, as well as constraints imposed by external factors, such as the ground track and altitude profile specified by the ATC system and weather conditions.  A cost function is fuel consumption.  A most desirable flight path is a most fuel efficient among all paths that meet all the constraints and will bring the aircraft to the next metering fix at the assigned arrival time.  This problem is known as the constrained fixed-time, minimum-fuel problem.  When the flight is late, the flight management system may try to bring the aircraft to the next metering fix in the shortest time.  In that case it will use algorithm that solves the time-optima problem.
Complexity and Timing Requirements:-
          The constrained optimization problem that a guidance ( or path planning) sysem must solve are typically nonlinear.  In principle these problems can be solved by using dynamic programming and mathematical programming techniques.destination.  The aircraft is supposed to arrive at the metering fix at the assigned arrival time.  At any time while in flight the assigned arrival time to the next metering fix is a reference input to the on-board flight that brings the aircraft to the next metering fix at the assigned arrival time. The cruise speed, turn radius, descend, accend rates, and so forth required to follow the chosen time-referenced flight path  are the reference inputs to the flight controller at the lowest level of the control hierarchy.
          In general there may be several higher levels of control take a control system of robots that perform  assembly tasks in a factory for example path and trajectory planners at the second level determine the trajectory to be followed by each industrial robot. These planners typically takes  as an input the plan generated by a task planner, which chooses the sequence of assmebly steps to be performed in a space robot control system , there may be a scenario planner, which determines how a repair or rendezvous function should be performed .  The plan generated by this planner is an input of the task planner.
Guidance and Control:-
         While a digital controller deals with some dynamical behaviour of the physicalplant, a second level controller typically performs guidance and path planning functions to achieve a higher level goal.  In particular, it tries to find one of the most.  In practice, however, optimal algorithms are rarely used because most of them are not only very compute intensive but also do not guarntee to find a usable solution.  Heuristic algorithms used for guidance and control purposes typically consider one constriant at a time, rather than all the constraints at the same time.  They usually start the constraints at the same time.  They usually start with an initial condition ( eg., in the case of a flight management systems, the initial condition includes the initial position, speed, and heading of the aircraft) and some initial solution and adjust the value of one solution parameter at a time until satisfactory solution is found.
        Fortunately, a guidance system does not need to compute its control laws as frequently as a digital controller often, this computation can be done off-line. In the case of  flight management systems, for example, it needs to compute and store a climb speed schedule for use during takeoff, an optimum cruise trajectory for use enroute, and a desent trajectory for landing .  This computation can be done before takeoff and hence is not time-critical.   While in-flight , the system still needs to compute some control laws to monitor and control the transistions between different flight  phases(ie.,from climb to cruise and cruise to descent)  as well as algorithms for estimating and predicting times to waypoints, and so forth.  These time critical computations tend to be simpler and more deterministic and have periods in order of secods and minutes.  When the precomputed flight plan needs to be updated or a new oe computed in-flight, the system has minutes o compute and can accept suboptimal solution when there is no time.
Other Capabilities:-
              The complexity of a higher-level control system arises for many other reasons in addition to its complicated control algorithms.  It often interfaces with the operator and other systems.  To  interact with the operator , it updates displays and reacts to operator commands and other systems, we mean those outside the control hierarchy.  An example is a voice, telemetry, or multimedia communication system that supports operator interactions.  Other examples are radar and navigation devices.  The control system may use the information provided by these devices and partially control these devices.
               An avionic or flight management system has these capabilities one of its functions is to update the display of radar, flight path, and air-data information.  Like keyboard monitoring the display upates must done no less requently than once every 100ms to achieve a satisfactor performance.  Similarly, it periodically updates navigation data provided by inertial and radio navigational aids.  An aviionics system for a military aricraft also does tracking and ballistic computatons and coordintes radar and weapon control systems, and it does them with repetition periods of a few to is few hundred milliseconds.  The workload due to these functions is demanding even for today's fast processors and data links.
Real-Time Command and Control:-
        The controller at the highest level of a control hierarchy is  a command and control system.  An air traffic control (ATC) system is an excellent example.  The ATC system monitors the aircraft in its coverage area and the environment(eg., weather condition) and generates and presents the inormation needed by the operators (ie., the air traffic controllers).  Outputs from the ATC system include the assigned arrival times to metering fixes for individual aircraft.  As stated earlier , these outputs are reference inputs to n-board flight management systems.  Thus, the ATC system indirecly controls the embedded components in low levels of the control hierarchy.  In addition , the ATC system provides voice and telemetry links to on-board avionics.  Thus it supports the communication among the operators at both levels (ie., the pilots and air traffic controllers).
                 The ATC system gathers information on the 'state' of each aircraft via one or more active radars.  Such a radar interrogates each aricraft periodically when interrogated, an aricraft responds by sending to the ATC system its 'state variables': identifier, position, altitude, heading and so on.  The ATC system processes messages from aircraft and sotres the state information thus obtained in a database.  This information is picked up and processed by display processors.  At the same time, a surveillnce system continously analyzes the scenario and alerts the operators wheneer it dete cts ay potential hazard (eg., a possible collision).  Again, the rates at hich human interfaces (eg., keyboards and displays) operates must be at least 10HZ.  The other resonse times can be consideable larger.  For example, the allowed response time from radar inputs is one to two seconds and the period of weather updates is in the order of ten seconds.
            From this example, we can see that a command and control system bears little  resemblance to low -level controllers.  In contrast to a low-level controller whose workload is either purely or mostly eriodic, a workload is either purely or mostly periodic, a command and control system also computes and communicates  in response to sporadic event s and operator's commands furthermore, it may process image and speech, query and updae databases, simulate various scenarios, and the like.  The resource and processing time demands of these tasks can be large and varied fortunately most of the timing requirements of a command and control system are less stringent whereas a low-level control system typically runs on  one computer or a fw computers connected by a small network or dedicated links, a command and control system is often a large distribution system containing tens and hundreds of computers and many different kind of networks.  In this respect, it resebles interactive, on-line translation systems(egs., a stock price quotation system) which are also sometimes called real-time systems.

  
Fault-Tolerance:-
------------------
        Methodologies  for analysing reliability of complex systems and techniques for making such systems tolerant to faults, thus increasing the reliability are well established In hardware  the emphasis is an improved components and construction techniques and the use of redundancy to maintain critical systems functions in the event of single falures ( in some systems multiple failures).  In software the emphasis has been on improved softare construction techniques – 'Software engineering' to reduce the latent errors; there has also been work on techniques to introduce redundancy into software systems.
             The majority of work on fault tolerance ahs concentrated on what Anderson and Lee(1981) have termed 'anticipated faults', that is faults which the designer can anticipate and hence 'design in' tolerance.  A much more difficult and insidious problem is tht of faults in the design of the system.  These are by definition 'unanticipated faults' ( and unanticipateable).  Design faults can occur both hardware and software but are more common in software and much of the effort of software engineering has been directed towards reducing design faults, that is unanticipated faults.
           Fault tolerance is one aspect of constructing dependable computer systems. Dependability is defined by Laprie as that property of computing system which allows reliance to be justifiably placed on the service it delivers.

                                                              | --- Faults
                          | -----Impairments------|---- Errors
                          |                                    |---- Failures     |--Fault avoidance 
                          |                           |--Procurement-------|--Fault tolerance
Dependability ---|-----Means------|
                          |                           |--Validation---|---Fault removal
                          |                                                   |---Fault Forecasting
                          |
                          |-----Mesures---|--Reliability
                                                    |--Availability 

                  Characteristics of Dependability

          An error is the consequence of fault in the system and a failure is the effect of an error on the service provided by the system.
Redundancy:-
                  A well established techniques for increasing the reliability of hardware sysems is to dublicate or triplicate hardware units.  Hardware redundancy can be introduced in two forms:  Static ( or masking) redundancy and dynamic redundancy.  In static redundancy the duplicate system take over the operation in the event of failure and hence mask the failure of the system from the environment. To detect that a failure has occurred requires some secondary indication of failure has occurred requires  some secondary indication of failure.  For example, a computer  control system with several processors operating in parallel and carrying out the complete functions of the system with the final action being determined by  a majority voting system involves static redundancy.
                     In dynamic redundancy an error detectio is used to detect error. Once detected the error must be corrected by redundancy elsewhere i the sstem.  An example of dynamic redundancy is a distributed compute system in which each unit carries out a specific subset of the overall functions, but which has some means of detecting when a unit fails and transferring the actions  of the failed unit to one or more of the operating units.
          The most common example of the static redundancy approach is triple modular redundancy(TMR) in which three identical units are run in parallel and a majority voting system is used to check the outputs.  The system is designed to tolerate failure of single module.  It produces output only when two modules aree (1 out-of 3 system).
             The parallel channel system does not provide any protection against common mode or systematic failures.  The decision or voting unit produes unambiguous result for two-valued logic signals ( any two are true the output will be true/any tow are false the output will be false) and for integer values ( required to be equal). If the signals are analog modulating signals or discrete real numbers then the decision unit is more difficult to implement.

Three Common Techniques are:

Average or Mean Value:-
            If the signals do not deviate from each other greatly or if a large number of channels are used.  For a TMR system a fault which causes one of the signals to go to a maximum or minimum value can introduce a significant error in the output.
Average with Automatic self-purging:-
              The average is calculated but if one  of the channels deviates by more than a specified amount from the average that channel is disconnected.  This technique can generate a large transient when the faulty channel is disconnected.
Median Selection:-
               Instead of taking the average, the median value of three or more channels is selected. This technique avoids large transients.
               The average with automatic self-purge technique provides detection of fialure of a channel. In any system employing parallel chanels there will be divergence, that is the individual channels will not give identical values and also the differences in values may change with time without implying failure of any particular channel.  To avoid divergence resulting in disconnection of a functioning channel some of channel equalisation is necessary.
                In hardware it is assumed that each unit functions correctly according to its specification and that failure is due to some physical cause-wear, a faulty component, unusual physical stress- that is not common to both units.  In software the major causes of failure are design faults- ranging from misinterpretation of specification to coding errors.
                Software redundancy requires productin of independent software modules from the same specification.  The errors can be reduced if independent groups report back to the co-ordinator.  When using redundancy agreement between modules can induce a false sense of confidence in the system, or input parts of the system in result in the failure to diagnose common mode or systematic errors
Fault-Tolerance in mixed Hardware-Software:-
            Redundancy introduces complexity and hence likelihood of fault occuring .  In reliability and fault-tolerance design with mixed hardware-software sysems introduced  diffculties in determining the actual reliability structure of the system.  At the software design stage the input driver ( driving input device distributed over the CPU, memory, interface bus and the input device) clearly defined as a module this structure may not be apparent when  the software is run.  Anderson and Lee proposes a view  in which software is run.  They term this interface interpretative interface.   This represents a language that provides objects and operations to manpulate those objects.  At the simplest level this is the machine language of the hardware.  This model can be extended to multileel-interpreter and extended interpreter.
Mechanisms and mesures:-
          Mechanism provides a specific facility at the interpreter interface and is implemented as part of the interpreter.  Measure performs some specific task and is implemented by means of a set of instructions in the system that is implemented.  Mechanism are likely to be more general purpose and widely applicable than mesures and Anderson and Lee place emphasis on generating fault tolerance through the use of mechanisms.
Exceptions:-
             Separate the normal behaviour of a system from abnormal behaviour.  A fault condition will generate an error which will be an exception.  A way of reducing complexity is to separate the response to an event into normal response and an exception response.
       Ex:  divide by zero the computer hardware is designed to detect this fault and generate exception response.
Fault-Detection Measurs:-
(a)  Replication Checks:-
             Involves duplicating or replicating the activityof the system that is to be checked ex: Triple redundancy (TMR) and multiple redundancy ( N-Modular redundancy, NMR).  Higher orders of redundancy enable faulty unit to be identified and the system to continue to run.  Replication is expensive and complex.  Reduced by replicating selected critical functions.  Replication can be used in a simple way to detect transient errors by repeated operation of the same system( disk drives read or write to a disk repeats access before reproting an error)
(b) Expected value methods:-
                  Each module passes to its successor module a unique numerical value.  If the value received by the succcessor module is not expected value the sequence  of modules is incorrect. 'Assertion test' is used for range checking and input/output checks.  For real-time control the expected vlue method can be  extended to include the limit and trend checking as well as techniques based on prediction and analysis of the incoming data from the plant.
(c ) Watch-dog Timers:-
                   Timing checks, that it checks that some function has been carried out within a specified time, can be used to detect errors in a system.  It should be noted that timing checks donot indicate that system is functioning correctly: they can only indicate it has failed some way.
                    A 'watch dog' task run at fixed time interval as high-priority task.  It decrements counters held in a pool and checks that he counters have not reached zero.  If the reached zero the watch dog task signals to the executive the time out has occurred.  Tasks being monitored by the watch-dog timers periodically reset the counters: thus time out occurs when they fail to reset the counter within a given time interval.
Reversal Checks:-
          For a system in which there is  one-to-one relationship between input and output a useful error check is to compute whate the input should be for the actual output and compare the computed inputs value with the actual input value. Obvious example is to check the computation of square root by squaring the answer.
Parity and Error coding checks:-
            Parity and error coding checks are used to detect and correct errors in memory and data transmission.  Single bit errors odd or even parity check can be used.  For multibit errors detection and correction Hamming, cyclic redundancy and M-out N codes.  These cods adds a greater amount of redundacny that  the use of a simple parity code.
Structural Checks:-
               Checksum codes are applied to data structures and provide a check on the consistency and integrity of the data contained in the structure.
Diagnostic checks:-
                 Diagnostic checks are used to test the behaviour of components used to construct the systems, not the system itself.
Fault Detection Mechanisms:-
                  Mechanisms for fault detection based on interface exceptions are illegal instruction, arithmetic overflow, underflow, protection violation and non-existent memory.  The use of tagged storage in which a few extra bits in each word allows to identify the type of object being held in the world.
                 Other useful fault detection mechanisms attempt to exceed array bounds or to exceed ranges specified for integers are provided in some computers.
Damage Containment and Assessment:-
        Damage results from faults or errors propagating throughout the system.  Assessing the extent of damage arises through the presence of parallel operations.  Access control mechanisms – monitors, guards, locks are used to protect critical sections or objects.  
Provision of Fault Tolerance:-
 (a) Redundancy:-
                 A method for introducing redundant modules into a system is the use of  recovery blocks.  Associate with a check point is a recovery block which contains one or more alternative code modules.  If an error is detected primary alternative is used.  At the end of the recovery block there is an acceptance test if, as a result of running the alternative code module the acceptance test ispassed the recovery block is exited.  If the aceptance test fails then the next alternative module is tried.  If all code modules are exhausted before an acceptable result is achieved then an error is reported.
(b) Deadline Mechanisms:-
-------------------------
          This is an attempt to deal with the requirement that service must be complete within a specified time.  In this mechanism alternate module is error free and requires less time run than the primary module.  For the 10ms deadline if the alternate module is estimated to take 3ms then the rimary module must return a result within 7ms.
(c ) Bad Data Marking:-
------------------------
              The use of modular design techniques facilitates are use of defensive programming to detect bad or faulty data.  The major problems arises not in detecting bad data but in deciding what action to take.  Interesting solution arises from the designers of CUTLASS system.  Associated with each data variable is a tag bit which indicates whether or not the data is bad.  Bad data is allowed to propagate through the system but carries with it an indication that its bad system but carries with it an indication that its bad .  The language support system contains known rules for evaluating expressions containing bad data.
(d) Recovery Measures – Check Points:-
------------------------------------------
           At a check point a copy of data which would be required to restart the program at that point is written to backing store or to some protected area of memory.  If a fault is detected at a test point or the next check point in the program then program is 'rolled back' to the previous check point and restarted.  Recovery mechanisms involving the storage of data values can provide protection against hardware faults or software faults which donot recur.
Data Diversity:-
----------------
          Sometimes hardware or software fals for certain inputs, but not for other inputs tht are very close to them.  So instead of applying the same input data to the redundant processors, slighty different input data to them.  This gives another line of defense against failure.  This approach will only work if the sensitivity of the output is either vary small with respect to small changes in the input or if perturbing the output can be corrected analytically.
            Data diversity can also be used with recovery blocks.  Instead of running alternative software when the primary fails the acceptance test, the primary can be reinvoked with slightly different data.
Malicious or Byzantine Failures:-
---------------------------------
          Whenever a failure can cause a unit to behave arbitrarily, malicious or Byzantine failure is said to happen.  In malicious failures sensor sends out conflicting information to different processors.
        For correct operation , it is often the case that copies of the same data as seen by various processors must be consistent (ie, the same) When communication is limited to two-party messages, the faulty units must be fewer than a third of the total number of units if consistency is to be guarnteed.  This may come as a surprise to those who, conditioned by the simple majority voting covered in earlier sections, may believe intuitively that a system can maintain consistency so long as only a minority of units are faulty.
        Data Originating from a sensor are to be distributed among the processors shown.  If the sensor is non faulty, we would like all the functioning processors to read the sensor output consistently (ie., for all the processors to see the same data value).  If the sensor is faulty, we would like the processors also to agree on some input from the sense ( which may be a default value if they realize that the sensor is faulty).
          In the field of Byzantine failures, three units are insufficient to maintain consistency in the face of one malicious failure.
Byzantine Algorithm:-
          The algorithm Byz(m) is recursive and is a function of m, which is the specified maximum number of traitors that must be sustained. In the following, when we say that x sends a message to y, we assume either that such a message is received by Y or that Y (upon a time-out after receiving no such message) assumes that x transmitted a default value ( say “retreat”).
Algorithm Byz(0)
-----------------
1	The commander sends his order to every lieutenant
2	The lieutenant uses the order he receives from the commander, or the default(say”retreat”) if he receives no order.
Algorithm Byz(x)
-----------------
1	The commander sends his order to every lieutenant Let Vi be the order he sends to lieutenant Li.
2	For each i, lieutenant Li acts as the commander in a Byz(x-1) algorithm, and sends out the order Vi to  each of the n-2 other lieutenant.  That is, the n-2 other lieutenant try to obtain consensus on lieutenant Li's order for every i.
3	   For each i, and j!= i, let wi,i be te order that lieutenant Li received from Lj i step 2 ( using the Byz(x-1) algorithm), or the default ( say “retreat”) if he received no such order.  Lieutenant Li follows the order majority { vi, wi,j, j!=i}

The Byzantine generals algorithm is improtant whenever we have a single sensor sending out variable values to processors in a redundant cluster that then vote on the result, using the schemes considered earlier in this chapter ( The analogy here is sensor = supreme commander; processor = lieutenant).  For majority voting schemes to work, the inputs to the processors should be consistent.  If the sensor can suffer Byzantine failure, then a Byzantine generals algorithm is required to obtain consistent values for the processors.
         The Byzantine general algorithm wil also work with kinds of voting other than majority voting.
          Note that throughout we have assumed that the participants in this algorithm are expecting a message.  This assumes either a synchronized clock or a watchdot timer, before whose expiry a message is expected.  This is necessary; otherwise a traitor could cause everyone to wait forever by simply not providing any output.
Integrated Failure Handling:-
         When an error is detected, the system must respond swiftly to deal with it. In the short term, the error might be masked by voting.  In the long term, the system will have to locate the failure that gave rise to the error and decide what to do with the failed unit.  Three options are usually available: retry, disconnect and replace.
          Instruction retry simply consists of retrying the failed instruction, in the hope that the failure was caused by a transient fault, which has since gone away.  To be able to to this, we need to be able to detect the error very quickly.  If the error is detected after several further instructions have been executed, the question of which instruction caused the error is not easy to answer.  To catch such errors, we need fast detection using signal-level detection mechanisms.  Such mechanisms include error-detection codes, duplicated circuits with matchers, and so on.  These mechanisms are distinct from function-level detection mechanisms, which operate at the function or module level, and take much more time to catch an error.
         If instruction retry is impractical, it might be useful to wait for some time and then run a diagnostic on the affected processor.  If the failure is a result of a transient fault that has since vanished, the processor will now pass this test.  If, after a long time processor still exhibits faulty behavior we can designate it as a permanent failure.  How long we wait for the failure to go away before declaring the failure permanent depends on the lifetime of transient faults.  Designers use their past experience, or use collected data on transient-fault durations to answer this question.  Alternatively the system might gather data on its own transients and dynamically adjust this waiting time.
          If we decide that the processor has suffered permanent failure, it must be disconnected from the rest of the system.  This can be done by preventing it from communicating on the network or by ignoring its output.  If a processor is disconnected, we must find new processors to run the tasks that it was allocated.
             Replace is another way of responding to permanent  failure.  If spare processors exists, they can be switched in to take the place of the failed unit.  All the duties previously performed by the failed processor duties previously performed by the failed processor will now be transferred to the  replacement.  The replacement procesor must have its memory updated suitably to allow it ot undertake these computations and must have its clock synchronized  with the rest of the system.
Recovery Actions:-
Timing Information:-
          The overall aim is to meet the hard deadlines of the critical tasks.  This is the ultimate test of success or failure, and everything is subordinated to the need to a maximize the probability of meeting such deadlines.  Timing information includes the worst-case requirements of the current workload, together with the requirements of any interrupt-issued  tasks that may be released.  It will also include any impending mode changes that can cause a change in the workload.
Recovery Time:-
                This is connected with the probability of meeting hard deadlines. Different recovery  mechanisms take different amounts of time  and this therefore 
affects the choice of mechanism.
Probability of the recovery action Succeeding:-
        There is often a trade-off between low overhead and the probability of succcess.  Instruction retry has perhaps the lowest overhead of all.  However , if the failure is a transient one of long duration, or a permanent fault, it will not succeed.  At the other end o the spectrum, the entire system can be reconfigured to isolate the failure.  This has a high probability of success but takes a long time. A recovery action that fails is worse than no recovery  action at all, because it consumes precious time.  On the other hand, a recovery action that could have succeeded with little overhead, but which was overlooked in favour of another higher overhead action represents a waste of time that can affect reliability and performacne.
State Transistion Rates:  The rate at which failures occur will play  a role in determining  what recovery action to take.  If  for example, there is a resonable probability that a second failure will occur while the first is still being dealt with, this will cause us to place an increased premium on short recovery actions.
         In order to determine a response to failure, the sysem must be aware of the time taken  by the various error-detection and failure handling mechanisms.

FORMAL VERIFICATION:-
-------------------------------
                      Formal methods are techniques used to model complex systems as mathematical entities.  By building a mathematically rigorous model of a complex system, it is possible to verify the systems properties in a more thorough fashion than empirical testing. While rigorous descriptions promise to improve system reliability, design time an dcomprehensibility, they do so at the cost of an increased learning curve.  The metamodels used by most foral methods are often  limited in order to enhance provability.  Tradeoff between the need for rigor and the ability to model all behaviours.
                       Formal methos use mathematical proof as a complement to system testing in order to ensure correct behavior.  Formal methods differ from other design systems through the use of formal verification schemes, the basic principles of the system must be proven correct before they are accepted.  Traditional system design has used extensive testing to verify behavior, but testing is capable of only finite conclusions.  Dijikstra and others have demonstrated that tests can only shsow the situations where a system won't fail, but cannot say anything about the behaviour of the system outside of the testing scenarios.  In contrasts, once a theorem is proven true it remains true.
         Formal verification doesnot obviate the need for testing.  Formal verification cannot fix bad assumptions in the design, but it can help identify errors in reasoning which would otherwise be left unverified.
         Formal design is a three step process 
Formal Specification:-
----------------------
          Formal specification phase, defines a system using modeling language modeling language fixed grammars which allow users to made complex structures out of predefined types.  Formal specification is similar to coverting word problem into algebraic notation. There is a distinction between WFFs ( well-formed Formulas) and non-WFFs ( Syntactically incorrect statements).

Verification:-
-------------
            Formal methods differ from other specification systems by their heavy emphasis on provability and correctness.  By building a system using  a formal specification, the designer is actually developing a set of theorems  about this system.  All formal systems use an automated theorem  proving  tool of some form.
Implementation:-
-----------------
              Once the model has been specified and verified it is implemented by converting the specification into code.  Hardware systems such as the VIPER and AAMPS processors have been developed using formal appraoaches
               Formal methods very difficult to use, especially for engineeers untrained in the type theory needed for most formal systems.
               VDM and Z are some of the formal specifications. 
                Formal verification emphasis on correctness and proof which is another measure of system integrity.  Testing cannot demonstrate that a system operates properly, it can only demonstrate that a system operates properly, it can only demonstrates that the system works for the tested cases.  Formally proving extensively used by Knuth and Dijkstra their methods are based on the traditional mathematical methods.