c sistemeintegrate

Upload: ace-daniel

Post on 14-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 c SistemeIntegrate

    1/93

    2008 2009

    Cosmin Ionete

    Dragos Surlea

    Nicolae Neagu

    FACULTY OF

    AUTOMATIONEMBEDDED SYSTEMS

  • 7/27/2019 c SistemeIntegrate

    2/93

    Contents

    1. Embedded Systems Architecture .............................................................................................................. 5

    1.1 What is an embedded system ? ---------------------------------------------------------------------------------5

    1.2 Microprocessor and Microcontroller Architectures--------------------------------------------------------6

    Hardwired Signals required to execute instruction generated by logic gates (combinational circuitry)

    The "control matrix" is: Faster Less flexible-----------------------------------------------------------10

    1.3 Microprocessor/Microcontroller Basics ---------------------------------------------------------------------10

    1.3.1 What is a microprocessor? ............................................................................................................. 11

    1.3.1.2 Microprocessor Fundamentals................................................................................................ 16

    1.3.2 What is a microcontroller?............................................................................................................. 20

    1.3.3 Some differences between microprocessors and microcontrollers............................................... 21

    1.3.4 Microcontroller Software and Programming Tools........................................................................ 24

    1.4 Microcontroller CPU, Interupts, Memory, and I/O -------------------------------------------------------26

    1.4.1 CPU Central Processing Unit................................................................................................... 26

    1.4.2 Interrupts................................................................................................................................... 28

    1.4.2.1 Vectored Interrupts & Non-Vectored Interrupts......................................................... ..... 30

    1.4.2.2 Interrupt Priority............................................................................................................... 30

    1.4.3 On-Chip Memory ....................................................................................................................... 30

    1.4.3.1 Read-Only Memory (ROM) ............................................................................................... 31

    1.4.3.2 Random-Access Memory (RAM) ....................................................................................... 32

    1.4.4 I/O .............................................................................................................................................. 34

    1.5 Peripheral devices ------------------------------------------------------------------------------------------------ 35

    1.5.1 Timers/Counters........................................................................................................................ 35

    1.5.1.1 Reloading a timer .............................................................................................................. 35

    1.5.1.2 Input Capture Timer.......................................................................................................... 36

    1.5.1.3 Watchdog Timer................................................................................................................ 36

    1.5.1.4 Using Timers...................................................................................................................... 36

    1.5.2 PWM .......................................................................................................................................... 38

    1.5.2.1 PWM Output ..................................................................................................................... 39

  • 7/27/2019 c SistemeIntegrate

    3/93

    1.5.3 Digital-to-Analog Converters (DAC)........................................................................................... 48

    1.5.4 Analog-to-Digital Converters (ADC)........................................................................................... 48

    1.5.4.1 Reference Voltage............................................................................................................. 49

    1.5.4.2 Resolution ......................................................................................................................... 49

    Communication ....................................................................................................................................... 50

    1.5.4.3 UART.................................................................................................................................. 50

    1.5.4.4 RS232................................................................................................................................. 51

    1.5.4.5 Serial Peripheral Interface ................................................................................................ 55

    1.5.4.6 Local Interconnect Network (LIN)..................................................................................... 58

    1.5.4.7 Controller Area Network................................................................................................... 63

    2. IDE Integrated Development Environment .......................................................................................... 71

    2.1 Source Code Editor ----------------------------------------------------------------------------------------------- 72

    2.2 Compiler ------------------------------------------------------------------------------------------------------------- 72

    2.2.1 Front end ................................................................................................................................... 72

    2.2.2 Back end..................................................................................................................................... 73

    2.3 Linker ----------------------------------------------------------------------------------------------------------------- 73

    2.4 Debugger ------------------------------------------------------------------------------------------------------------ 74

    3. Real-Time Operating Systems.................................................................................................................. 75

    3.1 Introduction -------------------------------------------------------------------------------------------------------- 75

    3.2 Defining an RTOS--------------------------------------------------------------------------------------------------75

    3.3 The Scheduler ------------------------------------------------------------------------------------------------------76

    3.3.1 Schedulable Entities................................................................................................................... 76

    3.3.2 Multitasking............................................................................................................................... 77

    3.3.3 The Context Switch.................................................................................................................... 78

    3.3.4 The Dispatcher........................................................................................................................... 78

    3.3.5 Scheduling Algorithms............................................................................................................... 79

    3.4 Objects ---------------------------------------------------------------------------------------------------------------80

    3.4.1 Tasks .......................................................................................................................................... 80

  • 7/27/2019 c SistemeIntegrate

    4/93

    3.4.1.1 Introduction ...................................................................................................................... 80

    3.4.1.2 Defining a Task .................................................................................................................. 81

    3.4.1.3 Task States and Scheduling ............................................................................................... 82

    3.4.1.4 Typical Task Operations .................................................................................................... 85

    3.4.2 Semaphores ............................................................................................................................... 88

    3.4.2.1 Introduction ...................................................................................................................... 88

    3.4.2.2 Defining Semaphores........................................................................................................ 88

    3.4.2.3 Typical Semaphore Operations......................................................................................... 92

    3.5 Services --------------------------------------------------------------------------------------------------------------93

  • 7/27/2019 c SistemeIntegrate

    5/93

    1. Embedded Systems Architecture1.1 What is an embedded system ?An embedded system is a special-purpose computer system designed to perform one or a

    few dedicated functions. It is usually embedded as part of a complete device including hardwareand mechanical parts. In contrast, a general-purpose computer, such as a personal computer, can domany different tasks depending on programming. Since the embedded system is dedicated to

    specific tasks, design engineers can optimize it, reducing the size and cost of the product, orincreasing the reliability and performance. Complexity varies from low, with a singlemicrocontroller chip, to very high with multiple units, peripherals and networks mounted inside alarge chassis or enclosure.

    In general, "embedded system" is not an exactly defined term, as many systems have someelement of programmability. For example, Handheld computers share some elements withembedded systems - such as the operating systems and microprocessors which power them - but arenot truly embedded systems, because they allow different applications to be loaded and peripheralsto be connected.

    Some of the actual commercial applications ofembedded systems include:

    Market Embedded Device

    Ignition SystemEngine Control

    Brake System (Antilock Braking System)Automotive

    Interior/Exterior Lights

    Set-Top Boxes (DVDs, VCRs, Cable Boxes, etc.)

    Kitchen Appliances (Refrigerators, Toasters, Microwave Ovens)

    Cameras

    Handheld tools

    Remote control devices

    Security systemsGlobal Positioning Systems (GPS)

    Consumer

    Electronics

    Cordless and cellular phones

    Industrial Control

    Robotics and Control Systems (Manufacturing)

    Electronic measurement instruments (e.g., digital multimeters, frequency

    synthesisers, and oscilloscopes)

    Infusion Pumps

    Dialysis Machines

    Prosthetic Devices

    Hearing aids

    Medical

    Cardiac MonitorsRouters

    HubsNetworking

    Gateways

    Fax Machine

    Monitors

    Scanners

    Photocopier

    Office Automation

    Printers

  • 7/27/2019 c SistemeIntegrate

    6/93

    Selecting a particular processor for a given application is usually a function of the designersfamiliarity with a particular architecture. While there are many variations in the details and specificfeatures, there are two general categories of devices: microprocessors and microcontrollers. The keydifference between a microprocessor and a microcontrolleris that a microprocessor contains only acentral processing unit (CPU) while a microcontroller has memory and I/O on the chip in additionto a CPU. Microcontrollers are generally used for dedicated tasks. Microcomputer is a general term

    that applies to complete computer systems implemented with either a microprocessor ormicrocontroller.

    1.2 Microprocessor and Microcontroller ArchitecturesMicroprocessors are generally utilized for relatively high performance applications where

    cost and size are not critical selection criteria. Because microprocessor chips have their entirefunction dedicated to the CPU and thus have room for more circuitry to increase execution speed,they can achieve very high-levels of processing power. However, microprocessors require externalmemory and I/O hardware. Microprocessor chips are used in desktop PCs and workstations wheresoftware compatibility, performance, generality, and flexibility are important.

    By contrast, microcontroller chips are usually designed to minimize the total chip count andcost by incorporating memory and I/O on the chip. They are often application specialized at the

    expense of flexibility. In some cases, the microcontroller has enough resources on-chip that it is theonly IC required for a product. Examples of a single-chip application include the key fob used toarm a security system, a toaster, or hand-held games. The hardware interfaces of both devices havemuch in common, and those of the microcontrollers are generally a simplified subset of themicroprocessor. The primary design goals for each type of chip can be summarized this way:

    microprocessors are most flexible microcontrollers are most compact

    Microcontroller Architectures

  • 7/27/2019 c SistemeIntegrate

    7/93

    A. Princeton (Von Neumann) vs. Harvard

    All memory space on same busEvery location has unique addressSo instructions and data treated the same way

    Possible bottleneck between instruction and data fetchesOvercome with instruction prefetching (overlapping, pipelining) and/or

    Instruction/Data cachesSimplifies processor design -- one memory interface

    More reliable -- fewer things can failAlso RAM can be used for both data and instruction storage

    Greater flexibility in design of software (esp. real-time OS)

    There are also differences in the basic CPU architectures used, and these tend toreflect the application. Microprocessor based machines usually have a von Neumannarchitecture with a single memory for both programs and data to allow maximum flexibilityin allocation of memory. Microcontroller chips, on the other hand, frequently embody the

    Harvard architecture, which has separate memories for programs and data. Figure 1.1illustrates this difference.

  • 7/27/2019 c SistemeIntegrate

    8/93

    CPU

    Program

    and Data

    Memory

    Data

    Memory

    Program

    MemoryCPU

    Figure 1.1 - At left is the von Neumann architecture; at right is the Harvard architecture

    One advantage the Harvard architecture has for embedded applications is due to the twotypes of memory used in embedded systems. A fixed program and constants can be stored in non-volatile ROM memory while working variable data storage can reside in volatile RAM. Volatilememory loses its contents when power is removed, but non-volatile ROM memory alwaysmaintains its contents even after power is removed.

    The Harvard architecture also has the potential advantage of a separate interface allowingtwice the memory transfer rate by allowing instruction fetches to occur in parallel with datatransfers. Unfortunately, in most Harvard architecture machines, the memory is connected to theCPU using a bus that limits the parallelism to a single bus.

    A typical embedded computer consists of the CPU, memory, and I/O. They are most oftenconnected by means of a shared bus for communication. The peripherals on a microcontroller chipare typically timers, counters, serial or parallel data ports, and analog-to-digital and digital-to-

    analog converters that are integrated directly on the chip. The performance of these peripherals isgenerally less than that of dedicated peripheral chips, which are frequently used withmicroprocessor chips. However, having the bus connections, CPU, memory, and I/O functions onone chip has several advantages:

    - Fewer chips are required since most functions are already present on the processor chip.- Lower cost and smaller size result from a simpler design.- Lower power requirements because on-chip power requirements are much smaller than

    external loads.- Fewer external connections are required because most are made on-chip, and most of the

    chip connections can be used for I/O.- More pins on the chip are available for user I/O since they arent needed for the bus.- Overall reliability is higher since there are fewer components and interconnections.

    Of course there are disadvantages too, including:- Reduced flexibility since you cant easily change the functions designed into the chip.- Expansion of memory or I/O is limited or impossible.- Limited data transfer rates due to practical size and speed limits for a single-chip.- Lower performance I/O because of design compromises to fit everything on one chip.

    The von Neumann machine, with only one memory, requires all instruction and data

    transfers to occur on the same interface. This is sometimes referred to as the von Neumann

    bottleneck. In common computer architectures, this is the primary upper limit to processor

    throughput. The Harvard architecture has the potential advantage of a separate interface allowing

  • 7/27/2019 c SistemeIntegrate

    9/93

    twice the memory transfer rate by allowing instruction fetches to occur in parallel with data

    transfers. Unfortunately, in most Harvard architecture machines, the memory is connected to the

    CPU using a bus that limits the parallelism to a single bus. The memory separation is still used to

    advantage in microcontrollers, as the program is usually stored in non-volatile memory (program is

    not lost when power is removed), and the temporary data storage is in volatile memory.

    Non-volatile memories, such as read-only memory (ROM) are used in both types of systems

    to store permanent programs. In a desktop PC, ROMs are used to store just the start-up or bootstrapprograms and hardware specific programs. Volatile random access memory (RAM) can be read and

    written easily, but it loses its contents when power is removed. RAM is used to store both

    application programs and data in PCs that need to be able to run many different programs. In a

    dedicated embedded computer, however, the programs are stored permanently in ROM where they

    will always be available. Microcontroller chips that are used

    in dedicated applications generally use ROM for program storage and RAM for data storage.

    B. CISC vs. RISC

    CISC (Complex Instruction Set Computers)

    Tend to have many instruction in instruction setCan carry out complex operations (many used very infrequently)Many are very long (many bits)And require many clock cycles

    RISC (Reduced Instruction Set Computer)Few instructionsSimple instructionsShort (few bits) and fastOften orthogonal instruction sets

    Can read/write/use all registers in same wayAllows for great power and flexibility

    Example PICmicroMany other microcontrollers use RISC

    Some microprocessors offer both CISC and RISC features

    C. Microcoded versus Hardwired processors

    The under cover design of a processor

    MicrocodedProcessor within a processorSignals required to execute instructions "fetched" from internal "Control ROM" memory

    Allows for great flexibility in instruction setEasier to designSlower than hardwired

  • 7/27/2019 c SistemeIntegrate

    10/93

    Hardwired

    Signals required to execute instruction generated by logic gates (combinational circuitry)

    The "control matrix" is:

    Faster

    Less flexible

    1.3 Microprocessor/Microcontroller BasicsMicroprocessor vs Micro-controllers Microprocessors

    high end of market where performance mattershigh power dissipationhigh costneed peripheral devices to work

    mostly used in microcomputers Microcontollers

    targeted for low end of market where performance does not matterlow power dissipationlow costmemory plus I/O devices, all integrated into one chipMostly used in embedded systems

  • 7/27/2019 c SistemeIntegrate

    11/93

    1.3.1 What is a microprocessor?

    A device that integrates a number of useful functions into a single IC packageSome functions are:

    - Ability to execute a stored set of instructions to carry out user defined tasks.- Ability to access external memory chips to read/write data from/to memory.- Ability to interface with I/O devices

    There are three groups of signals, or buses, that connect the CPU to the other major

    components. The buses are:

    - Data bus

    - Address bus

    - Control bus

    concepts ofaddress and data is fundamental to the operation of the microprocessor

    memory -consists oflocations uniquely identified by CPU through their address

    CPU communicates with those addresses to read and write the data

    the communications go via buses

    the CPU -responsible for control of address, data and control buses

    All devices attached to data bus -potential clash

    Devices connected to data buses can be driven to high-impedance states

    The ability of devices to set their output at either logic 1, logic 0 or in a high impedance state is an

    essential feature of common bus systems and is termed a tristate device.

    A. Data bus - to transfer the data associated with the processing function of the microprocessor. (8lines, typically)

    Thedata bus width is defined as the number of bits that can be transferred on the bus at one

    time. This defines the processors word size. Many chip vendors define the word size based on

    the width of an internal data bus. A processor with eight data bus pins is an 8-bit CPU. Both

    instructions and data are transferred on the data bus one word at a time. This allows the re-use of

    the same connections for many different types of information. Due to packaging limitations, the

  • 7/27/2019 c SistemeIntegrate

    12/93

    number of connections or pins on a chip is limited. By sharing the pins in this way, the number of

    pins required is reduced at the expense of increased complexity in the external circuits. Many

    processors also take this a step further and share some or all of the data bus pins to carry address

    information as well. This is referred to as a multiplexed address/data bus. Processors that have

    multiplexed address/data buses require an external address latch to separate and hold the address

    information stable for the duration of a data transfer. The processor controls the direction of data

    transfer on the data bus(read/write).

    B. Address bus - contains the address of a specific memory location for accessing (reading/writing)stored data. 16, typically

    Theaddress bus is a set of wires that are used to point to the memory or I/O location that is

    to be read from or written to. The address signals must generally be held at a constant value for

    some period of time before, during, and after the data is transferred. In most cases, the processor

    actively drives the address bus with either instruction or data addresses.

  • 7/27/2019 c SistemeIntegrate

    13/93

    Memory Read and Write Cycles

    Hardware Control lines used by the CPU to Control reads and Writes to Memory

    Active low signal RD asserted for a Read Cycle Active Low signal WR indicates a writeRD and WR signals supply timing information to

    memory device

  • 7/27/2019 c SistemeIntegrate

    14/93

    Read cycle It lasts 2 cycles of the clock signal:1. address of required memory location puton address bus (by CPU), at rising edge2. while device held at tristate level -control bus issues read signal (active low) to the device(2nd cycle begins)3. after delay -valid data placed on data bus4. levels on the data bus sampled by CPUat falling edgeof the 2nd cycle

    Write cycle

    1. CPU places address at rising edge2. decoding logic selects correct device3. 2nd cycle -rising edge: CPU outputs data onto data bus & sets WRITE control bus signalactive (LOW)Note:memory devices & other I/O components have static logic -do not depend on clock signal-read data from data bus when write signal high (inactive) - data must be valid for transition

    C. Control bus - carries the control signals to the memory and the I/O devices. Arbitrary number,

    often 15.Thecontrol bus is an assortment of signals that determine what kind of information is on the

    data bus and determines where the data will go, in conjunction with the address bus. Most of the

    design process is concerned with the logic and timing of the control signals. The timing analysis is

    primarily involved with the relative timing between these control signals and the appearance and

    disappearance of data and addresses on their respective buses.

  • 7/27/2019 c SistemeIntegrate

    15/93

  • 7/27/2019 c SistemeIntegrate

    16/93

    1.3.1.2 Microprocessor Fundamentals

    MPU Register set and Internal ArchitectureMPU busesMemory ConsiderationsMPU interfacing

    The CPU

    processes the data by executing a program stored in the memory performs sequence of fetch-and-execute operations consists of:

    Control Unit + ALU + Registers responsible for the control of address, data and control buses (a master) all actions within P synchronised to the CPU via a clock signal clock signal = a logic square-wave to drive all the circuitry in the P, typically 1 to 30 MHz orhigher

  • 7/27/2019 c SistemeIntegrate

    17/93

    The Control Unit determines timing and sequence of operations generates timing signals which are used to fetch program instructions from memory and to

    execute it also responsible for decoding instructions supplies control signals to read and write data into registers, controls ALU and external

    control signals

    The ALU The arithmetic and logic unit (ALU) -responsible for data manipulation

    arithmetic operations, logic operations (AND, OR, XOR etc.) bit shifting, rotating, incrementing, decrementing, negate, complementing, addition etc.

  • 7/27/2019 c SistemeIntegrate

    18/93

    Registers

    Registers data/adressesthat CPU currently uses -stored in special memory (Small and fast)locations on the CPUaccumulator register-input to ALU is stored temp and sometime I/O operations. It may be8, 16, 32 bits wideflags registeror status registerIndividual bits in the register are called flags. Conditions ofthe latest ALU operations are reflected. Used by subsequent jump, branch instructionsgeneral purpose register-temporary storage for data or addresses. Not assigned anyspecific task.

    program counter-tracks CPUs position in program. Width of the program counter is sameas address bus instruction register-stores instruction where it can be decoded; not accessible by theprogrammer index registers-hold the address of an operand when the indexed address mode is usedstack pointer register-holds the address of the next memory location in the stack in RAM.Stack -special area of RAM: last-in first-out (LIFO or FILO) file organisation. It is usedduring subroutine calls andinteruppts

    Types of registers:

    Stack

    Part of memory where program data can be stored by a simple PUSH operation Restore data by a POP Stack is in main memory and is defined by the program Stack Pointer (SP) keeps track of the next location available on the Stack Organised as a FILO Buffer

    General Registers Small set of internal registers -temporary data storage CU ensures that data from the correct register is presented to the CPU CU ensures that data is written back to correct register

  • 7/27/2019 c SistemeIntegrate

    19/93

    Accumulatorusually holds ALU result

    Status or Flags Register

    CF -Carry Flag1 -there is a carry out from the most significant bit0 -no carry out frommsb

    PF -Parity Flag1-low bye has an even number of 1 bits0 -low byte has odd parity

    AF -Auxiliary carry Flag1 -carry out from bit 3 on addition0 -borrow into bit 3 on addition

    ZF -Zero Flag1 -zero result

    0 -non-zero result SF -Sign Flag

    1 -msbis 1 (negative)0 -msbis 0 (positive)

    TF -Trap FlagUsed by debuggers for single step operation1 -Trap on0 -Trap off

    IF -Interrupt Flag1 -Enabled0 -Disabled

    OF -Overflow Flag

    1 -signed overflow occurred0 -no overflow

    Flag bits are set by instructions

    Flag bits are basis of conditional jump instructions

    The program status word (PSW) is an area of memory or a hardware register which containsinformation about program state used by the operating system and the underlying hardware. It will

  • 7/27/2019 c SistemeIntegrate

    20/93

    normally include a pointer (address) to the next instruction to be executed. The program status wordtypically contains an error status field and condition codes such as the interrupt enable/disable bitand a supervisor / user mode bit.

    PSW

    PSW contains information such as:condition code bits (set by various comparison instructions)

    CPU prioritymode:

    user-mode: only a subset of instructions and features are accessible.kernel-mode: all instructions and features are accessible.

    The program status word (PSW) is 32 bits in length and contains the information required forproper program execution. The PSW includes the instruction address, condition code, and otherfields. In general, the PSW is used to control instruction sequencing and to hold and indicate thestatus of the system in relation to the program currently being executed. The active or controllingPSW is called the current PSW. By storing the current PSW during an interruption, the status of theCPU can be preserved for subsequent inspection. By loading a new PSW or part of a PSW, the stateof the CPU can be initialized or changed

    1.3.2 What is a microcontroller?

    - Common component in modern electronic systems- Microprocessor-based device- Basically, a device which integrates a number of the components of a

    microprocessor system onto a single chip: Single-chip computer- Completely self-contained with memory and I/O- Only need to be supplied power and clocking

    Primary role: provide inexpensive, programmable logic control and interfacing to externaldevices e.g., turn devices on/off, monitor external conditions

    Microcontroller combines on the same chip:

    The CPU core

    I/O

    Memory: PROM/EPROM/EEPROM/Flash memoryVariable RAM memory

  • 7/27/2019 c SistemeIntegrate

    21/93

    Most microcontrollers will also combine other devices such as:

    A Timer module to allow the microcontroller to perform tasks for certain timeperiods.

    Serial I/O (UART) for data flow between microcontroller and devices such as a PCor other microcontroller.

    Analog input and output (e.g., to receive data from sensors or control motors)

    Interrupt capability (from a variety of sources) Bus/external memory interfaces (for RAM or ROM)

    Built-in monitor/debugger program

    Support for external peripherals (e.g., I/O and bus extenders)

    A typical microcontroller; the different sub units integrated onto the microcontroller chip.

    The heart of the microcontroller is the CPU core

    1.3.3 Some differences between microprocessors and microcontrollers

    MP: suited to processing information in computer systemsMC: suited to control of I/O devices requiring a minimum component count

    Instruction sets:

    MP: processing intensivepowerful addressing modesinstructions to perform complex operations & manipulate large volumes of dataprocessing capability of MCs never approaches those of MPslarge instructions -- e.g., 80X86 7-byte long instructions

    MC: cater to control of inputs and outputsinstructions to set/clear bitsboolean operations (AND, OR, XOR, NOT, jump if a bit is set/cleared), etc.

  • 7/27/2019 c SistemeIntegrate

    22/93

    Extremely compact instructions, many implemented in one byte(Control program must often fit in the small, on-chip ROM)

    Instruction sets:

    The set of instructions given to the P to execute a task is called an instruction set Generally, instructions can be classified into the following categories:

    Data transfer Arithmetic Logical Program control

    Differ depending on the manufacturer, but some are reasonably common to most P's.

    A. Data transfer

    1. Load reads the content of a specified memory location and copies it to the specified registerlocation in the CPU2. Store copies the current contents of a specified register into a specified memory location.

    B. Arithmetic3. Add Adds the contents of a specified memory location to the data in some register4. Decrement subtracts 1 from the content of a specified location.5. Compare indicates whether the contents of a register are greater than, less than or same as thecontents of a specified memory location. The result appears as a flag in the status register.

    C. Logical6. AND carries out the logical AND operation with the contents of a specified memory location and

    the data in some register7. OR carries out the logical OR operation with the contents of a specified memory location andthe data in some register8. EXCLUSIVE OR-(similar to 6, but for exclusive OR)9. Logical shift moving the pattern of bits in the register one place to the left or right by moving zero (0) tothe end of the number10. Arithmetic shift moving the pattern of bits one place left/right but with copying of the end bit into thevacancy created by shift

    D. Program control

    11. Jump changes the sequence in which the program is executed. So the program counter jumps tosome specified location (other than sequential)12. Branch a conditional instruction which might be 'branch if zero'or 'branch if plus'. It is followedif the right conditions are met.13. Halt stops all further microprocessor activities

  • 7/27/2019 c SistemeIntegrate

    23/93

    Hardware & Instructionset support:MC: built-in I/O operations, event timing, enabling & setting up priority levels

    for interrupts caused by external stimuliMP: usually require external circuitry to do similar things (e.g, 8255 PPI, 8254 PIT,

    8259 PIC)

    Bus widths:MP: very wide

    large memory address spaces (>4 Gbytes)lots of data (Data bus: 32, 64, 128 bits wide)

    MC: narrowrelatively small memory address spaces (typically kBytes)less data (Data bus typically 4, 8, 16 bits wide)

    Clock rates:MP very fast (> 1 GHz)MC: Relatively slow (typically 10-20 MHz)

    since most I/O devices being controlled are relatively slow

    Cost:MP's expensive (often > $100)MCs cheap (often $1 - $10)

    4-bit: < $1.00

  • 7/27/2019 c SistemeIntegrate

    24/93

    8-bit: $1.00 - $8.0016-32-bit: $6.00 - $20.00

    1.3.4 Microcontroller Software and Programming Tools

    ProgrammingGenerally done in either the core's native assembly language or C

    Sometimes HLL support (often BASIC) is availableAssemblers/Linkers often supplied free by the micro's manufacturerC compilers vary from free and very buggy to very expensive and only moderately buggyEnvironments generally not friendly or reliable

    DownloadingProgram development usually done on a PCSoftware tools must produce a file to download to the MC's EPROMSeveral standard formats (e.g., binary, hex)EPROM burner often necessary

    Can download program to an EPROM emulatorBut to reprogram, must us an UV erasor first

    Flash memory programmers make this easierVery easy to reprogram with inexpensive "in-circuit debugger"

    Interacts with MC via 3 pins + power + groundOr can be programmed/debugged with a resident monitor program

    on-chip UART for communications with PCNo burner or UV erasor neededNo expensive quartz window requiredExpedites program-test-erase-reprogram code development cycle

    MonitorA program module that communicates with PC softwareTypically uses a serial port to talk to a PC's terminal programCapabilities vary widelyUsually can send/receive text and ASCII-converted numbersOften has commands to examine/change registers, memory locations, I/O ports

  • 7/27/2019 c SistemeIntegrate

    25/93

  • 7/27/2019 c SistemeIntegrate

    26/93

    1.4 Microcontroller CPU, Interupts, Memory, and I/OThe interconnection between the CPU, memory, and I/O of the address and data buses is

    generally a one-to-one connection. The hard part is designing the appropriate circuitry to adapt the

    control signals present on each device to be compatible with that of the other devices. The most

    basic control signals are generated by the CPU to control the data transfers between the CPU and

    memory, and between the CPU and I/O devices. The four most common types of CPU controlled

    data transfers are:

    - CPU reads data/instructions from memory (memory read)

    - CPU writes data to memory (memory write)

    - CPU reads data from an input device (I/O read)

    - CPU writes data to an output device (I/O write)

    1.4.1 CPU Central Processing UnitThe four major CPU components are:

    - the arithmetic logic unit (ALU) The ALU contains the circuitry to perform simple

    arithmetic and logical operations on the inputs

    - registers a type of fast memory

  • 7/27/2019 c SistemeIntegrate

    27/93

    - the control unit (CU) The control unit is the circuitry that controls the flow of data through

    the processor, and coordinates the activities of the other units within it. In a way, it is the

    "brain within the brain".

    - the internal CPU buses interconnect the ALU, registers, and the CU

    The Figure 1.2 presents the internal block diagram of the V850 CPU.

    Figure 1.2 Internal block diagram of V850ES CPU

    - The general-purpose registers can be used to store a data variable or an address variable.

    - The program counter holds the instruction address during program execution.

    - The system registers control the status of the CPU and hold interrupt information

    - The program status word (PSW) is an area of memory or a hardware register which contains

    information about program state used by the operating system and the underlying hardware.It will normally include a pointer (address) to the next instruction to be executed. The

    program status word typically contains an error status field and condition codes such as the

    interrupt enable/disable bit and a supervisor / user mode bit.

    Registers

    Registers are simply a combination of various flip-flops that can be used to temporarily storedata or to delay signals. A storage register is a form of fast programmable internal processormemory usually used to temporarily store, copy, and modify operands that are immediately or

    frequently used by the system. Shift registers delay signals by passing the signals between thevarious internal flip-flops with every clock pulse.Registers are made up of a set of flip-flops that can be activated either individually or as a

    set. In fact, it is the number of flip-flops in each registerthat is actually used to describe a processor(for example, a 32-bit processor has working registers that are 32 bits wide containing 32 flip-flops,a 16-bit processor has working registers that are 16 bits wide containing 16 flipflops, and so on).The number of flip-flops within these registers also determines the width of the data buses used inthe system

    While ISA designs do not all use registers in the same way to process the data, storagetypically falls under one of two categories, either general purpose or special purpose. General

  • 7/27/2019 c SistemeIntegrate

    28/93

    purpose registers can be used to store and manipulate any type of data determined by theprogrammer, whereas special purpose registers can only be used in a manner specified by the ISA,including holding results for specific types of computations, having predetermined flags(single bitswithin a register that can act and be controlled independently), acting as counters(registers that canbe programmed to change statesthat is, increment asynchronously or synchronously after aspecified length of time), and controlling I/O ports (registers managing the external I/O pinsconnected to the body of the processor and to board I/O). Shift registers are inherently special

    purpose, because of their limited functionality.The number of registers, the types of registers, and the size of the data that these registers

    can store (8-bit, 16-bit, 32-bit, and so forth) varies depending on the CPU, according to the ISAdefinitions. In the cycle of fetching and executing instructions, the CPUs registers have to be fast,so as to quickly feed data to the ALU, for example, and to receive data from the CPUs internal databus. Registers are also multi-ported so as to be able to both receive and transmit data to these CPUcomponents.

    1.4.2 InterruptsAn interrupt is an asynchronous signal from hardware indicating the need for attention or a

    synchronous event in software indicating the need for a change in execution.Hardware interrupts are triggered by a physical event, such as the closure of a switch, that

    causes a specific subroutine to be called. They can be thought of as a sort of hardware initiatedsubroutine call. They can and do occur at any time in the program, depending on when the eventoccurs. These are referred to as asynchronous events because they may occur during the executionof any part of the program. Interrupts allow the programs to respond to an event when it occurs.

    A software interrupt is a special subroutine call. It is synchronous meaning that it alwaysoccurs at the same time and place in the program that is interrupted. It is frequently used as a quickand simple way to do a subroutine call for accessing programs such as the operating system and I/Oprograms. Software interrupts are usually implemented as instructions in the instruction set, whichcause a context switch to an interrupt handler similar to a hardware interrupt.

    Interrupts can be categorized into: maskable interrupt (IRQ), non-maskable interrupt (NMI),interprocessor interrupt (IPI), software interrupt, and spurious interrupt.

    - A maskable interrupt(IRQ) is a hardware interrupt that may be ignored by setting a bit in an

    interrupt mask register's (IMR) bit-mask.- Likewise, a non-maskable interrupt(NMI) is a hardware interrupt that does not have a bit-

    mask associated with it - meaning that it can never be ignored. NMIs are often used fortimers, especially watchdog timers.

    - An interprocessor interruptis a special case of interrupt that is generated by one processorto interrupt another processor in a multiprocessor system.

    - A software interruptis an interrupt generated within a processor by executing an instruction.Software interrupts are often used to implement System calls because they implement asubroutine call with a CPU ring level change.

    - A spurious interruptis a hardware interrupt that is unwanted. They are typically generatedby system conditions such as electrical interference on an interrupt line or throughincorrectly designed hardware.

    An interrupt can notify the processor when an analog-to-digital converter (ADC) has newdata, when a timer rolls over, when a direct memory access (DMA) transfer is complete, whenanother processor wants to communicate, or when almost any asynchronous event happens. Theinterrupt hardware is initialized and programmed by the system software. When an interrupt isacknowledged, that process is performed by hardware internal to the processor and the interruptcontroller integrated circuit (IC) (if any).

  • 7/27/2019 c SistemeIntegrate

    29/93

    When an interrupt occurs, the on-chip hardware performs the following functions:

    It saves the program counter (the address the processor was executing when theinterrupt occurred) on the stack. Some processors save other information aswell, such as registercontents.

    It executes an interrupt acknowledge cycle to get a vector from the interrupting peripheral,depending on the processor and the specific type of interrupt.

    It branches to a predetermined address specific to that particular interrupt.The destination address is the interrupt service routine(ISR, or sometimes ISP for interrupt

    service process). The ISR performs whatever functions are required and then returns. When thereturn code is executed, the processor performs the following tasks:

    It retrieves the return address and any other saved information from the stack.

    It resumes execution at the return address.The return address, in nearly all cases, is the address that would have been executed next if

    the interrupt had not occurred. If the implementation is correct the code that was interrupted will noteven knowthat an interrupt occurred. The hardware part of this process occurs at hardware speed-microseconds or even tens of nanoseconds for a fast CPUwith a high clock rate.

    Re-entrant code or a re-entrant routine is code that can be interrupted at any point whenpartially complete, then called by another process, and later return to the point where it wasinterrupted to complete the original function without any errors. Non-re-entrant code, however,cannot be interrupted and then called again without problems. An example of a program that is notre-entrant is one that uses a fixed memory address to store a temporary result. If the program isinterrupted while the temporary variable is in use and then the routine is called again, the value inthe temporary variable would be changed. When execution returns to the point where it wasinterrupted, the temporary variable will have the wrong value. In order to be re-entrant, a programmust keep a separate copy of all internal variables for each invocation. Re-entrant code is requiredfor any subroutines that must be available to more than one interrupt driven task.

    Interrupts can be processed between execution of instructions by the CPU any time they areenabled. Most CPUs check for the presence of an interrupt request at the end of every instruction. Ifinterrupts are enabled, the processor saves the contents of the program counter (PC) on the stack,

  • 7/27/2019 c SistemeIntegrate

    30/93

    and loads the PC with the address of the ISR. Some CPUs allow certain instructions to beinterrupted when they take a long time to process, such as a block move instruction.

    1.4.2.1Vectored Interrupts & Non-Vectored InterruptsIn a vectored interrupt system, the interrupt request is accompanied by an identifier, referred

    to as a vector or interrupt vector number that defines the source of the interrupt. The vector is apointer that is used as an index into a table known as the interrupt vector table. This table contains

    the addresses of the ISRs that are to be executed when the corresponding interrupts are processed.When a vectored interrupt is processed, the CPU goes through the following sequence ofevents to begin execution of the ISR:

    - After acknowledging the interrupt, the CPU receives the vector number.- The CPU converts the vector into a memory address in the vector table.- The ISR address is fetched from the vector table and placed in the program counter.

    For example, when an external event occurs, the interrupting device activates the IRQ inputto the interrupt controller that then requests an interrupt cycle from the CPU. When the CPUacknowledges the interrupt, the interrupt controller passes the vector number to the CPU. The CPUconverts the vector number to a memory address. This address points to the place in memory, whichin turn contains the address of ISR.

    For systems with non-vectored interrupts, there is only one interrupt service routine entry

    point, and the ISR code must determine what caused the interrupt if there are multiple interruptsources in the system. When an interrupt occurs a call to a fixed location is executed, and thatbegins execution of the ISR. It is possible to have multiple interrupts pointing to the same ISR. Thefirst act of such an ISR is to determine which interrupt occurred and branch to the appropriatehandler. Serial I/O ports frequently have one vector for transmit and receive interrupts.

    1.4.2.2Interrupt PriorityThere are a number of variations in the way interrupts can be handled by the processor.

    These variations include how multiple interrupts are handled, if they can be turned off, and how

    they are triggered. Some processors allow multiple (nested) interrupts, meaning the CPU can handle

    multiple interrupts simultaneously. In other words, interrupts can interrupt interrupts. When

    multiple interrupts are sent to the CPU, some method must be used to determine which is handled

    first. Here are the most common prioritization schemes currently in use.

    - Fixed (static) multi-level priority. This uses a priority encoder to assign priorities, with the

    highest priority interrupt processed first. Nested interrupts allow an ISR itself to be

    interrupted by a higher-priority device. Interrupts from lower-priority devices are ignored

    until the higher-priority ISR is completed. This is the most common method of assigning

    priorities to interrupts.

    - Variable (dynamic) multi-level priority. One problem with fixed priority is that one type

    of event can dominate the CPU to the exclusion of other events. The solution is to rotate

    priority each time an event occurs. This ensures that no interrupt gets locked out and all

    interrupts will eventually be processed. This scheme is good for multi-user systems because

    eventually everyone gets priority.

    - Equal single-level priority. If an interrupt occurs with an interrupt, the new interrupt gains

    control of the processor.

    1.4.3 On-Chip MemoryThe CPU goes to memory to get what it needs to process, because it is in memory that all of

    the data and instructions to be executed by the system are stored. Embedded platforms have a

    memory hierarchy, a collection of different types of memory, each with unique speeds, sizes, and

  • 7/27/2019 c SistemeIntegrate

    31/93

    usages (see Figure 1.3). Some of this memory can be physically integrated on the processor, such as

    registers, read-only memory (ROM), certain types of random access memory (RAM) and level-1

    cache.

    Figure 1.3 Memory hierarchy

    1.4.3.1Read-Only Memory (ROM)On-chip ROM is memory integrated into a processor that contains data or instructions that

    remain even when there is no power in the system, due to a small, longer-life battery, and thereforeis considered to be nonvolatile memory (NVM). The content of on-chip ROM usually can only be

    read by the system it is used in.The most common types of on-chip ROM include:

    - MROM(mask ROM), which is ROM (with data content) that is permanently etched into themicrochip during the manufacturing of the processor, and cannot be modified later.

    - PROMs (programmable ROM), or OTPs (one-time programmables), which is a type ofROM that can be integrated on-chip, that is one-time programmable by a PROMprogrammer (in other words, it can be programmed outside the manufacturing factory).

    - EPROM (erasable programmable ROM), which is ROM that can be integrated on aprocessor, in which content can be erased and reprogrammed more than once (the number of

  • 7/27/2019 c SistemeIntegrate

    32/93

    times erasure and re-use can occur depends on the processor). The content of EPROM iswritten to the device using special separate devices and erased, either selectively or in itsentirety using other devices that output intense ultraviolet light into the processors built-inwindow.

    - EEPROM (electrically erasable programmable ROM), which, like EPROM, can be erasedand reprogrammed more than once. The number of times erasure and re-use can occurdepends on the processor. Unlike EPROMs, the content of EEPROM can be written and

    erased without using any special devices while the embedded system is functioning.WithEEPROMs, erasing must be done in its entirety, unlike EPROMs, which can be erasedselectively.Acheaper and faster variation of the EEPROM is Flash memory. Where EEPROMs are

    written and erased at the byte level, Flash can be written and erased in blocks or sectors (a group ofbytes). Like EEPROM, Flash can be erased while still in the embedded device.

    1.4.3.2Random-Access Memory (RAM)RAM (random access memory), commonly referred to as main memory, is memory in

    which any location within it can be accessed directly (randomly, rather than sequentially from somestarting point), and whose content can be changed more than once (the number depending on the

    hardware). Unlike ROM, contents of RAM are erased if RAM loses power, meaning RAM isvolatile. The two main types of RAM are static RAM (SRAM) and dynamic RAM (DRAM).

    As shown in Figure 1.4, SRAM memory cells are made up of transistor-based flip-flopcircuitry that typically holds its data due to a moving current being switched bi-directionally on apair of inverting gates in the circuit, until power is cut off or the data is overwritten.

    Figure 1.4 6 Transistor SRAM cell

    As shown in Figure 1.5, DRAM memory cells are circuits with capacitors that hold a chargein place (the charges or lack thereof reflecting data). DRAM capacitors need to be refreshedfrequently with power in order to maintain their respective charges, and to recharge capacitors afterDRAM is read (reading DRAM discharges the capacitor). The cycle of discharging and rechargingof memory cells is why this type of RAM is called dynamic.

    Figure 1.5 DRAM (capacitor based) memory cell

  • 7/27/2019 c SistemeIntegrate

    33/93

    One of the major differences between SRAM and DRAM lies in the makeup of the DRAMmemory array itself. The capacitors in the memory array of DRAM are not able to hold a charge(data). The charge gradually dissipates over time, thus requiring some additional mechanism torefresh DRAM, in order to maintain the integrity of the data. This mechanism reads the data inDRAM before it is lost, via a sense amplification circuit that senses a charge stored within thememory cell, and writes it back onto the DRAM circuitry. Ironically, the process of reading the cellalso discharges the capacitor, even though reading the cell in the first place is part of the process of

    correcting the problem of the capacitor gradually discharging in the first place. A memorycontroller in the embedded system typically manages a DRAMs recharging and discharging cycleby initiating refreshes and keeping track of the refresh sequence of events. It is this refresh cyclingmechanism that discharges and recharges memory cells that gives this type of RAM its namedynamic RAM (DRAM)and the fact that the charge in SRAM stays put is the basis for itsname, static RAM (SRAM). It is this same additional recharge circuitry that makes DRAMslower in comparison to SRAM. (Note that SRAM is usually slower than registers, because thetransistors within the flip-flop are usually smaller, and thus do not carry as much current as thosetypically used within registers.)

    SRAMs also usually consume less power than DRAMs, since no extra energy is needed fora refresh. On the flip side, DRAM is typically cheaper than SRAM, because of its capacitance baseddesign, in comparison to its SRAM flip-flop counterpart (more than one transistor). DRAM also can

    hold more data than SRAM, since DRAM circuitry is much smaller than SRAM circuitry and moreDRAM circuitry can be integrated into an IC.

    DRAM is usually the main memory in larger quantities, and is also used for video RAMand cache. DRAMs used for display memory are also commonly referred to as frame buffers.SRAM, because it is more expensive, is typically used in smaller quantities, but because it is alsothe fastest type of RAM, it is used in external cache and video memory (when processing certaintypes of graphics, and given a more generous budget, a system can implement a better-performingRAM).

    Reading speed

    Although the relative speed of RAM vs. ROM has varied over time, as of 2007 large RAM

    chips can be read faster than most ROMs. For this reason (and to make for uniform access), ROMcontent is sometimes copied to RAM or shadowed before its first use, and subsequently read fromRAM.

    Writing speed

    For those types of ROM that can be electrically modified, writing speed is always muchslower than reading speed, and it may require unusually high voltage, the movement of jumperplugs to apply write-enable signals, and special lock/unlock command codes. Modern NAND Flashachieves the highest write speeds of any rewritable ROM technology, with speeds as high as15 MiB/s (or 70 ns/bit), by allowing (indeed requiring) large blocks of memory cells to be writtensimultaneously.Memory Management

    Goals:

    Protectthe programs from each other, and the kernel from the programs.Perform relocationRelocation:User program thinks it has the whole address space from address 0x0 to 0xffffffff.Really it only has a part of the physical memory.Need to map virtual address into aphysical address.This is performed by the MMU (Memory Management Unit), but the OS must configure it.

  • 7/27/2019 c SistemeIntegrate

    34/93

    Context Switching

    Whenever execution switches between a user program and the OS, a context switch occurs. The

    operating system must now:

    Save the PC, Stack Pointer, PSW.

    Save the contents of the registers.

    Reprogram the MMU registers.

    Wait while the instructions in the CPU pipeline are trashed.

    Wait for cache lines to load from new programs memory.

    Context switching is pretty expensive.

    1.4.4 I/OThe entire point of an embedded microprocessor is to monitor or control some real-world

    event. To do this, the microprocessor must have I/O capability. Like a desktop computer without amonitor, printer, or keyboard, an embedded microprocessor without I/O is just a paperweight. TheI/O from an embedded control system falls into two broad categories: digital and analog. However,at the microprocessor level, all I/O is digital. (Some microprocessor ICs have built-in ADCs, but the

    processor itself still works with digital values.) The simplest form of I/O is a register that themicroprocessor can write to or a buffer that it can read.Most of the peripherals require the use of a certain set of pins on the processor. In many

    cases, the majority of those pins can be used for their specific function (serial port receiver, timeroutput, DMA control signal, etc.), or they can be programmed to just act as a simple input or outputpin (PIO). This flexibility allows the silicon to be configured based on the needs of the design. Forexample, if you dont need two serial ports (and the processor comes with two), then the pins thatare allocated to the second port (RX2, TX2, and maybe DTR2, CTS2, etc) can be programmed tofunction as simple PIO pins and used to drive an LED or read a switch. Programmable pins aresometimes referred to as dual function. Note that this dual functionality should not be assumed.

  • 7/27/2019 c SistemeIntegrate

    35/93

    How each pin is configured and the ability to configure it to run in different modes is dependent onthe processor implementation.Often a pin name is chosen to reflect the pins dual personality. Forexample if RX2 can be configured as a serial port 2 receiver or as a PIO pin, then it will probably belabeled as RX2/PION (or something similar), where N is some number between one and M, and Mis the number of PIO pins on the processor.Some microprocessors may be advertised as having a setof features but actually provide these features on dual-function pins. Hence, the full set ofadvertised features (two serial ports and 32 PIO lines) may not be simultaneously available (because

    the pins used for the second serial port are dual-functioned as PIO lines.

    1.5 Peripheral devices1.5.1 Timers/Counters

    Timers and counters, which are present in most microcontroller chips, allow generation ofpulses and interrupts at regular intervals. They can also be used to count pulses and measure eventtiming. Some of the more sophisticated versions can measure frequency, pulse width, and relativepulse timing on inputs. Outputs can be defined to have a given repetition rate, pulse width, and evencomplex sequences of pulses in some cases.A simple timer consists of a simple, loadable 8-bit counter. You could build this from a couple of

    74HC161 counters or equivalent PLD logic.The microprocessor can write a value to the timer that is transferred to the counter outputs.

    If the counter is an UP counter, it counts up. A DOWN counter counts down. A typical timerembedded in a microcontroller or in a timer IC will have some means to start the timer once it isloaded, typically by setting a bit in a register. The clock input to the counter may be a derivative ofthe microprocessor clock or it may be a signal applied to one of the external pins. A real timer willalso provide the outputs of the counter to the microprocessor so it can read the count. If themicroprocessor loads this timer with a value of 0xFE and then starts the timer, it will count from FEto FF on the next clock. On the second clock, it will count from FF to 00 and generate an output.The output of the timer may set a flip-flop that the microprocessor can read, or it may generate aninterrupt to the microprocessor, or both. The timer may stop once it has generated an output, or itmay continue counting from 00 back to FF. The problem with a continuously running timer is that it

    will count from the loaded value the first time it counts up, but the second time it will start from 00.

    1.5.1.1Reloading a timerThis timer has an 8-bit latch to hold the value written by the microprocessor. When the

    microprocessor writes to the latch, it also loads the counter. An OR gate also loads the timer when itrolls over from FF to 00. For this example, we will assume that the logic in the IC gets all thepolarities and timings of the load signal correct so that there are no glitches or race conditions.

    The way this timer works is that the microprocessor writes a value to the latch (also loadingit into the timer) and then starts the timer. When the timer rolls over from FF to 00, it generates anoutput (again, either a latched bit for the microprocessor to read or an interrupt). At the same timethat the output is generated, the timer is loaded from the latch contents. Since the latch still holdsthe value written by the microprocessor, the counter will start counting again from the same point it

    did before. Now the timer will produce a regular output with the same accuracy as the input clock.This output could be used to generate a regular interrupt, to provide a baud rate clock to a UART, orto provide a signal to any device that needs a regular pulse. A variation of this feature used in somemicrocontrollers does not load the counter with the desired count value but instead loads it into adigital comparator. The comparator compares the counter value to the value written by themicroprocessor. The counter starts at zero and counts up. When the count equals the value writtenby the microprocessor, the counter is reset to zero and the process repeats. The effect is the same asthe timer just described.

  • 7/27/2019 c SistemeIntegrate

    36/93

    1.5.1.2Input Capture TimerIn this case, the timer counts from zero to FF. When a pulse occurs on the capture input pin,

    the contents of the counter are transferred to an 8-bit latch and the counter is reset. The input pulsealso generates an interrupt to the microprocessor. The timer is connected directly to the input pin; inan actual circuit, of course, there will be some gating and synchronizing logic to make sure all thetiming is right. Similarly, the capture pin will not connect directly to a microprocessor interrupt butwill be passed through some flip-flops, timing logic, interrupt controller logic, and so on.

    This configuration is typically used to measure the time between the leading edge of twopulses. The timer is run at a constant clock, usually a derivative of the microprocessor clock. Eachtime an edge occurs on the input capture pin, the processor is interrupted and the software reads thecapture latch. The value in the latch is the number of clocks that occurred since the last pulse. Somemicrocontrollers do not reset the counter on an input capture but letthe counter free run. In those configurations, the software must remember the previous reading andsubtract the new reading from it. When the counter rolls over from FF to 00, the software mustrecognize that fact and correct the numbers; if it doesnt, negative values will result. Manymicrocontrollers that provide a capturetype timer also provide a means for the counter to generatean interrupt when it rolls over, which can simplify this software task.

    1.5.1.3Watchdog TimerThe watchdog timer (WDT) acts as a safety net for the system. If the software stops

    responding or attending to the task at hand, the watchdog timer detects that something is amiss andresets the software automatically. The system might stop responding as a result of any number ofdifficult-to-detect hardware or firmware defects. For example, if an unusual condition causes abuffer over run that corrupts the stack frame, some functions return address could be overwritten.When that function completes, it then returns to the wrong spot leaving the system utterly confused.Runaway pointers (firmware) or a glitch on the data bus (hardware) can cause similar crashes.Different external factors can cause glitches. For example, even a small electrostatic dischargenear the device might cause enough interference to momentarily change the state of one bit on theaddress or data bus. Unfortunately, these kinds of defects can be very intermittent, making themeasy to miss during the projects system test stage.

    The watchdog timer is a great protector. Its sole purpose is to monitor the CPU with a you

    scratch my back and Ill scratch yours kind of relationship. The typical watchdog has an input pinthat must be toggled periodically (forexample, once every second). If the watchdog is not toggledwithin that period, it pulses one of its output pins. Typically, this output pin is tied either to theCPUs reset line or to some nonmaskable interrupt (NMI), and the input pin is tied to an I/O line ofthe CPU. Consequently, if the firmware does not keep the watchdog input line toggling at thespecified rate, the watchdog assumes that the firmware has stopped working, complains, and causesthe CPU to be restarted.

    1.5.1.4Using TimersTime-Based Temperature Measurement - An example that illustrates some of the

    important issues you must consider when using timers involves measurement of temperature. TheMaxim MAX6576 is an IC that measures temperature. The MAX6576 has a single wire output and

    produces a square wave with a period that is proportional to temperature in degrees Kelvin. TheMAX6576 can operate from -40C to +125C. By connecting the TSO and TS1 inputs to ground orVcc in various combinations, the MAX6576 can be configured so that the period varies 10, 40, 160,or 640s per degree. In the configuration shown, the period will vary by 40s per degree. At 25 C,the period will be:

    (25 + 273.15) x 40 = 11,926 microseconds, or 11.926msSay you connect this to an microprocessor using input capture mode. Lets supose the

    microprocessor is operating with a 4.096MHz crystal and using a prescaler of 256, so the timer getsa clock of 4.096MHz/256, or 16,000Hz. The counter increments every 62.5 s. For this application,

  • 7/27/2019 c SistemeIntegrate

    37/93

    it doesnt matter whether the input capture occurs on the rising or falling edge of the MAX6576output.

    How accurately can you measure temperature with this arrangement? Since the MAX6576changes 40s per degree and the clock to the counter is 16,00OHz, each increment of the countercorresponds to 62.5/40 or 1.56 degrees. This is the best resolution you can get. If the temperature ofthe sensor is 25C, the captured count value will be 11,926/62.5 = 190.8. Since the counter can onlycapture integral values, the actual count will be 190 (the .8 is dropped). For the count to be less than

    190, the temperature must go to 23.7C. Any changes between these two values cannot be read bythe microprocessor.

    If we decide that this is insufficient accuracy for our application, we might change theprescaler to 1, making the counter clock the same as the CPU clock, 4.096MHz. Now the counterincrements every 244.1ns, and the resolution is 244.1ns/40s, or .0061 degrees per counterincrement. This is much better accuracy than the sensor itself has. What happens in thisconfiguration if the temperature goes from 25C to 125C? The count value will go from 11,926 to15,926. This will result in a captured count of 65,232. The timer is 16 bits wide, so this is not aproblem, but it is very close to the 65,535 upper limit of the counter.

    What happens at 125C if we take the accuracy of the sensor itself into account? TheMAX6576 has a typical accuracy of 35C at 125C, but the maximum error is +5C. This meansthat, at 125C, the output may actually indicate up to 130C. At 130C, the output period is

    16126ms. This corresponds to a count value of 66,052, which means the timer we are using wouldroll over from 65,535 to zero while sampling. The actual count that would be captured would be517, indicating a much lower temperature than the MAX6576 is actually sensing.

    There are several solutions to this specific problem: The timer prescaler could be changed,the configuration of the MAX6576 could be changed, or even the microprocessor crystal could bechanged. You could leave the hardware as-is and handle the error in software by detecting therollover. The important point is to perform this type of analysis when you use timers inmicroprocessor designs.

    Another issue that arises from this example is that of sampling time. The system can onlysample the temperature at a rate equal to the period of the output. As the temperature goes up, thetime between samples also goes up. If several samples need to be averaged, the sampling rate goesdown proportionally. While a worstcase sample time of 16ms is probably not unreasonable for a

    temperature measurement system, an analysis of the effects of sample time should be performed incases where the input rate of a signal affects it.

    Motor Control - Say you have a DC motor that is part of a microprocessor controlsystem. Themotor has an encoder that produces 100 pulses per revolution, and the microprocessor must controlthe speed of the motor from 10RPM to 2000RPM. Some undefined external source provides acommand to the microprocessor to set motor speed.

    At 10RPM, the microprocessor will get pulses from the motor encoder at the followingfrequency:

    Sec

    Pulses

    Sec

    Min

    v

    Pulses

    Min

    v6.16

    60

    1

    Re100

    Re10 =

    A similar calculation results in a frequency of 3333.33 pulses/sec at 2000RPM. If the inputcapture hardware is configured to generate an interrupt when the input pulse occurs, then theprocessor will get an interrupt every 60ms at lORPM, and every 300 ps at 2000 RPM.Say we want to calculate motor speed by using a microcontroller with input capture capability tomeasure the time between encoder pulses. If the input capture is measured with a 1MHz referenceclock, then the input capture registers will contain 1 MHz/16.6Hz or 60,024 at 10RPM. Similarly,the registers will contain a value of 300 at 2000RPM.

    The l00 count encoder produces one pulse every 3.6 degrees of rotation (360/100). This istrue at any motor speed. However, the input capture reference clock is fixed, so its accuracy (indegrees of rotation) vanes with the motor speed. At 10RPM, each reference clock corresponds to:

  • 7/27/2019 c SistemeIntegrate

    38/93

    ckferenceCloDegreesPerckferenceClo

    Sec

    seEncoderPul

    Deg

    Sec

    sesEncoderPulRe1060

    Re1000000

    16.366.16 6=

    At 2000RPM, this becomes .012 degrees. While either of these is probably adequate for amotor control application, the principle is important; at faster RPM, the accuracy of the referenceclock with respect to the input signal is less.

    1.5.2

    PWMPWM Control How It Works

    Pulse-width modulation control works by switching the power supplied to the motor on and off veryrapidly. The DC voltage is converted to a square-wave signal, alternating between fully on (nearly12V) and zero, giving the motor a series of power "kicks".

    If the switching frequency is high enough, the motor runs at a steady speed due to its fly-wheelmomentum.

    By adjusting the duty cycle of the signal (modulating the width of the pulse, hence the 'PWM') ie,the time fraction it is "on", the average power can be varied, and hence the motor speed.

    Advantages are,

    1. The output transistor is either on or off, not partly on as with normal regulation, so lesspower is wasted as heat and smaller heat-sinks can be used.

    2. With a suitable circuit there is little voltage loss across the output transistor, so the top endof the control range gets nearer to the supply voltage than linear regulator circuits.

    3. The full-power pulsing action will run fans at a much lower speed than an equivalent steadyvoltage.

    Disadvantages:

    1. Without adding extra circuitry, any fan speed signal is lost, as the fan electronics' powersupply is no longer continuous.

    2. The 12V "kicks" may be audible if the fan is not well-mounted, especially at low revs. Aclicking or growling vibration at PWM frequency can be amplified by case panels.

    3. Some authorities claim the pulsed power puts more stress on the fan bearings and windings,shortening its life.

  • 7/27/2019 c SistemeIntegrate

    39/93

    An oscillator is used to generate a triangle or sawtooth waveform (green line). At low frequenciesthe motor speed tends to be jerky, at high frequencies the motor's inductance becomes significantand power is lost. Frequencies of 30-200Hz are commonly used.

    A potentiometer is used to set a steady reference voltage (blue line).

    A comparator compares the sawtooth voltage with the reference voltage. When the sawtooth

    voltage rises above the reference voltage, a power transistor is switched on. As it falls below thereference, it is switched off. This gives a square wave output to the fan motor.

    If the potentiometer is adjusted to give a high reference voltage (raising the blue line), the sawtoothnever reaches it, so output is zero. With a low reference, the comparator is always on, giving fullpower.

    A simple PWM consists of an 8-bit up/down counter that counts from 00 to FF, then back

    down to 00 and an 8-bit comparator that compares the value in the 8-bit latch to the counter value.

    When the two values are equal, the comparator clocks the D flipflop (again, timing logic makes

    sure everything works correctly). If the counter is counting up, a 1 is clocked into the D flip-

    flop. If the counter is counting down, a 0 is loaded. The flip-flop output is connected to one of themicrocontroller output pins.

    Say the microprocessor writes a value of 0xFE into the latch. The counter counts from 00 to

    FE, where the PWM output goes to 1 because the counter bits match the latched value. The

    counter continues to FF, then back down through FE to zero. When the counter passes through FE,

    the PWM output goes to zero. So in this case, the PWM output is high for two counts (FE and FF)

    out of 256, or about .78 percent duty cycle. If the microprocessor writes 0xF0 to the latch, the PWM

    output will be high from F0 to FF and back to F0, for a total of 30 counts or 11.7 percent duty cycle.

    A more sophisticated PWM timer would include a second latch and comparator so the

    counter can reverse direction at values other than FF. In such a timer, this comparator would set the

    frequency of the PWM signal while the other comparator would set the duty cycle. Some

    microprocessors provide other means to generate PWM. Some microcontrollers dont use an

    up/down counter but instead they provide two comparators. After the first count value is reached,

    the counter is reset and the second comparator is used to indicate end-of-count. The output pin

    indicates which comparator is being used so a PWM output can be generated by controlling the

    ratios of the comparator values.

    1.5.2.1PWM OutputSimilar considerations apply to timer outputs. If you are using an 8-bit timer to generate a

    PWM signal, the output duty cycle can only be changed by one timer count, or 1 in 256. This

    results in a duty cycle resolution of .3 percent. Note, though, that this applies only if the timer is

    allowed to run a full 256 counts. If you are using an 8-bit timer but only 100 counts for the PWMperiod, then one step is 1 percent of the total period. In this case, the best resolution you can get is I

    percent. This is sufficient for many applications but is inadequate for others. In an application in

    which you vary the PWM period and duty cycle, you need to be sure that the resolution at the

    fastest period (least number of timer counts per cycle) is adequate for the application.

    PWM Control

  • 7/27/2019 c SistemeIntegrate

    40/93

    Pulse-width modulation control works by switching the power supplied to the motor on and off very

    rapidly. The DC voltage is converted to a square-wave signal, alternating between fully on (nearly

    12V) and zero, giving the motor a series of power "kicks".

    If the switching frequency is high enough, the motor runs at a steady speed due to its fly-wheelmomentum.

    By adjusting the duty cycle of the signal (modulating the width of the pulse, hence the 'PWM') ie,

    the time fraction it is "on", the average power can be varied, and hence the motor speed.

    Advantages are,

    The output transistor is either on or off, not partly on as with normal regulation, so less power is

    wasted as heat and smaller heat-sinks can be used.

    With a suitable circuit there is little voltage loss across the output transistor, so the top end of the

    control range gets nearer to the supply voltage than linear regulator circuits.

    The full-power pulsing action will run fans at a much lower speed than an equivalent steady

    voltage.

    Disadvantages:

    Without adding extra circuitry, any fan speed signal is lost, as the fan electronics' power supply is

    no longer continuous.

    The 12V "kicks" may be audible if the fan is not well-mounted, especially at low revs. A clicking or

    growling vibration at PWM frequency can be amplified by case panels. A way of overcoming this

    by "blunting" the square-wave pulse is described in Application Note #58 from Telcom. (a 58k pdf

    file, right-click to download). I've tried this, it works, but some of advantage #3 is lost.

    Some authorities claim the pulsed power puts more stress on the fan bearings and windings,

    shortening its life.

    How It Works

  • 7/27/2019 c SistemeIntegrate

    41/93

    An oscillator is used to generate a triangle or sawtooth waveform (green line). At low frequencies

    the motor speed tends to be jerky, at high frequencies the motor's inductance becomes significant

    and power is lost. Frequencies of 30-200Hz are commonly used.

    A potentiometer is used to set a steady reference voltage (blue line).

    A comparator compares the sawtooth voltage with the reference voltage. When the sawtooth

    voltage rises above the reference voltage, a power transistor is switched on. As it falls below the

    reference, it is switched off. This gives a square wave output to the fan motor.

    If the potentiometer is adjusted to give a high reference voltage (raising the blue line), the sawtooth

    never reaches it, so output is zero. With a low reference, the comparator is always on, giving full

    power.

    Principle

    An example of PWM: the supply voltage (blue) modulated as a series of pulses results in a sine-like

    flux density waveform (red) in a magnetic circuit of electromagnetic actuator. The smoothness of

    the resultant waveform can be controlled by the width and number of modulated impulses (pergiven cycle)

  • 7/27/2019 c SistemeIntegrate

    42/93

    Fig. 1: a square wave, showing the definitions ofymin,ymax and D.

    Pulse-width modulation uses a square wave whose pulse width is modulated resulting in the

    variation of the average value of the waveform. If we consider a square waveformf(t) with a low

    valueymin, a high valueymax and a duty cycle D (see figure 1), the average value of the waveform is

    given by:

    Asf(t) is a square wave, its value isymax for andymin for . The above

    expression then becomes:

    This latter expression can be fairly simplified in many cases whereymin = 0 as . From

    this, it is obvious that the average value of the signal ( ) is directly dependent on the duty cycle D.

    Fig. 2: A simple method to generate the PWM pulse train corresponding to a given signal is the

    intersective PWM: the signal (here the green sinewave) is compared with a sawtooth waveform

  • 7/27/2019 c SistemeIntegrate

    43/93

    (blue). When the latter is less than the former, the PWM signal (magenta) is in high state (1).

    Otherwise it is in the low state (0).

    The simplest way to generate a PWM signal is the intersective method, which requires only a

    sawtooth or a triangle waveform (easily generated using a simple oscillator) and a comparator.

    When the value of the reference signal (the green sine wave in figure 2) is more than the modulation

    waveform (blue), the PWM signal (magenta) is in the high state, otherwise it is in the low state.

    Fig. 3 : Principle of the delta PWM. The output signal (blue) is compared with the limits (green).

    These limits correspond to the reference signal (red), offset by a given value. Every time the output

    signal reaches one of the limits, the PWM signal changes state.

    Fig. 4 : Principle of the sigma-delta PWM. The top green waveform is the reference signal, on

    which the output signal (PWM, in the middle plot) is subtracted to form the error signal (blue, in

    top plot). This error is integrated (bottom plot), and when the integral of the error exceeds the limits

    (red lines), the output changes state.

  • 7/27/2019 c SistemeIntegrate

    44/93

    Fig. 5 : Three types of PWM signals (blue): leading edge modulation (top), trailing edge modulation

    (middle) and centered pulses (both edges are modulated, bottom). The green lines are the sawtooth

    signals used to generate the PWM waveforms using the intersective method.

    Square wave is a unique function for many applications such as Pulse Width Modulation (PWM).

    PWM is widely used in a variety of applications in measurement and digital controls. It offers a

    simple method for digital control logic to create an analog equivalence.

    The majority of microcontrollers today has built-in PWM capability that facilitates the

    implementation of the control. Using PWM in communication systems is very popular due to the

    fact that the digital signal is more robust and less vulnerable to noise.

    Concepts of Pulse Width Modulation (PWM)

    PWM is a method of digitally encoding analog signal levels. The duty cycle of a square wave is

    modulated to encode a specific analog signal level using high-resolution counters. The PWM signal

    is still a digital signal because at the given instant of time, the full DC supply is either fully on or

    fully off.

    The voltage or current source is supplied to the analog load by a repetitive series of ON and OFF

    pulses. The ON time is the period when the DC supply is applied to the load, and the OFF time is

    the period when the DC supply is switched off. If the available bandwidth is suffi cient, any analog

    value can be encoded using PWM.

    An analog signal has a continuously varying value, with infinite resolution in both time and

    magnitude, and it can be used to control many electronic devices directly. For example, in a simple

    analog radio, a knob is connected to a variable resistor. When turning the knob, the resistance goes

    down or up, and the current fl owing through the resistor increases or decreases. Consequently, the

    current that drives the speaker is changed proportionally, thus increasing or decreasing the volume.

    Although analog control may be considered intuitive and simple, it is not always economically

    attractive or practical. Analog circuits tend to drift over time and are very difficult to tune.

  • 7/27/2019 c SistemeIntegrate

    45/93

    Problems solved by precision analog circuits can be large, heavy, and expensive.

    Analog circuits tend to generate heat through the power dissipation. The power dissipated is

    proportional to the voltage across the active elements, multiplied by the current that flows through

    it. Analog circuitry can also be sensitive to noise because of its infinite resolution; even minor

    perturbations of an analog signal can change its value.

    By controlling analog circuits digitally, system costs and power consumption can be drasticallyreduced. Many microcontrollers and digital signal processors (DSPs) already include PWM

    controllers in the chip, thus making implementation easier.

    Frequency and Duty Cycle

    Figure 1 illustrates a circuit established using a battery, a switch and a LED. This circuit turns on

    the

    LED for one second and then turns off the LED for one second using the switch control.

    The LED is ON for 50% of the period and OFF the other 50%. The period is defined as the total

    time it takes to complete one cycle (from OFF to ON state and back to OFF state).

    The signal can be further characterized by the duty cycle, which is the ratio of the ON time

    divided by the period. A high duty cycle generates a bright LED while a small duty cycle generates

    a dimmer LED. The example shown in Figure 1 provides a 50% duty cycle.

    In Figure 2, two waveforms with different frequencies produce the same amount of light. Note that

    the

    amount of light is independent from the frequency, but proportional to the duty cycle.

    The frequency range you can use to control a circuit is limited by the number of response time to

    the circuit.

    In the example shown in Figure 1, a low frequency can cause the LED to flash noticeably. A high

    frequency, in turn, can cause an inductive load to saturate.

    For example, a transformer has a limited frequency range to transfer the energy efficiently. For

    some designs, harmonics (or beat frequencies) of the PWM frequency can get coupled into the

    analog circuitry, causing unwanted noise. If the right frequency is selected, the load being

  • 7/27/2019 c SistemeIntegrate

    46/93

    controlled will act as a stabilizer, a light will glow continuously and the momentum will allow a

    rotor to turn smoothly.

    Generating PWM signals

    The PWM signals are easy to generate using a comparator with a sine wave as one of the input

    signals. Figure 3 shows a sample block diagram of an analog PWM generator.

    Figures 4 and 5 show the PWM output waveform (red line) generated by a comparator with two

    input signals: a sine wave (black line) and an input signal (gray line). The input signal of 0.5 VDC

    is the voltage reference to be compared w