unit 2 new

Upload: auxilia-richard

Post on 06-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Unit 2 new

    1/42

    Unit-II

    MICROCONTROLLER

    PIC is a family of Harvard architecture microcontrollers made by Microchip Technology,

    derived from the PIC1640 originally developed by General Instrument's Microelectronics

    Division. The name PIC initially referred to "Programmable Interface Controller", but

    shortly thereafter was renamed "Programmable Intelligent Computer".

    PICs are popular with developers and hobbyists alike due to their low cost, wide availability,

    large user base, extensive collection of application notes, availability of low cost or free

    development tools, and serial programming (and re-programming with flash memory)

    capability.

    Core Architecture of the 8-bit CPUs

    The PIC architecture is distinctively minimalist. It is characterized by the following features:

    separate code and data spaces (Harvard architecture)

    a small number of fixed length instructions

    most instructions are single cycle execution (4 clock cycles), with single delay cycles

    upon branches and skips

    a single accumulator (W), the use of which (as source operand) is implied (ie is not

    encoded in the opcode)

    All RAM locations function as registers as both source and/or destination of math and

    other functions.

    a hardware stack for storing return addresses

    http://en.wikipedia.org/wiki/Harvard_architecturehttp://en.wikipedia.org/wiki/Microcontrollerhttp://en.wikipedia.org/wiki/Microchip_Technologyhttp://en.wikipedia.org/wiki/General_Instrumenthttp://en.wikipedia.org/wiki/Accumulator_(computing)http://en.wikipedia.org/wiki/Image:PIC_microcontrollers.jpghttp://en.wikipedia.org/wiki/Harvard_architecturehttp://en.wikipedia.org/wiki/Microcontrollerhttp://en.wikipedia.org/wiki/Microchip_Technologyhttp://en.wikipedia.org/wiki/General_Instrumenthttp://en.wikipedia.org/wiki/Accumulator_(computing)
  • 8/3/2019 Unit 2 new

    2/42

    a fairly small amount of addressable data space (typically 256 bytes), extended

    through banking

    data space mapped CPU, port, and peripheral registers

    the program counter is also mapped into the data space and writable (this is used to

    implement indirect jumps)

    Unlike most other CPUs, there is no distinction between "memory" and "register" space

    because the RAM serves the job of both memory and registers, and the RAM is usually just

    referred to as the register file or simply as the registers.

    Data Space (RAM)

    PICs have a set of registers that function as general purpose ram. Special purpose control

    registers for on-chip hardware resources are also mapped into the data space. The

    addressability of memory varies depending on device series, and all PIC devices have some

    banking mechanism to extend the addressing to additional memory. Later series of devices

    feature move instructions which can cover the whole addressable space, independent of the

    selected bank. In earlier devices (ie. the baseline and mid-range cores), any register move had

    to be achieved via the accumulator.

    To implement indirect addressing, a "file select register" (FSR) and "indirect register" (INDF)

    are used: A read or write to or from INDF will actually be to or from the register pointed to

    by FSR. Later devices extended this concept with post- and pre- increment/decrement for

    greater efficiency in accessing sequentially stored data. This also allows FSR to be treated

    almost like a stack pointer.

    External data memory is not directly addressable except in some high pin count PIC18

    devices.

    Code Space

    All PICs feature Harvard architecture, so the code space and the data space are separate. PIC

    code space is generally implemented as EPROM, ROM, orFLASH ROM.

    In general, external code memory is not directly addressable due to the lack of an external

    memory interface. The exceptions are PIC17, select high pin count PIC18 devices, and

    PIC24/dsPIC.

    http://en.wikipedia.org/wiki/Harvard_architecturehttp://en.wikipedia.org/wiki/EPROMhttp://en.wikipedia.org/wiki/Read-only_memoryhttp://en.wikipedia.org/wiki/FLASH_ROMhttp://en.wikipedia.org/wiki/Harvard_architecturehttp://en.wikipedia.org/wiki/EPROMhttp://en.wikipedia.org/wiki/Read-only_memoryhttp://en.wikipedia.org/wiki/FLASH_ROM
  • 8/3/2019 Unit 2 new

    3/42

    Word Size

    The word size of PICs can be a source of confusion. All PICs (except dsPICs and PIC24s)

    handle (and address) data in 8-bit chunks, so they should be called 8-bit microcontrollers.

    However, the unit of addressability of the code space is not generally the same as the data

    space. For example, PICs in the baseline and mid-range families have program memory

    addressable in the same wordsize as the instruction width, ie. 12 or 14 bits respectively. In

    contrast, in the PIC18 series, the program memory is addressed in 8-bit (bytes), which differs

    from the instruction width of 16 bits.

    In order to be clear, the program memory capacity is usually stated in number of (single

    word) instructions, rather than in bytes.

    Stacks

    PICs have a hardware call stack, which is used to save return addresses. The hardware stack

    is not software accessible on earlier devices, but this changed with the 18 series devices.

    Hardware support for a general purpose parameter stack was lacking in early series, but this

    greatly improved in the 18 series, making the 18 series architecture more friendly to high

    level language compilers.

    Instruction Set

    A PIC's instructions vary in number from about 35 instructions for the low-end PICs to about

    70 instructions for the high-end PICs. The instruction set includes instructions to perform a

    variety of operations on registers directly, the accumulator and a literal constant or the

    accumulator and a register, as well as for conditional execution, and program branching.

    Some operations, such as bit setting and testing, can be performed on any register, but bi-

    operand arithmetic operations always involve W -- writing the result back to either W or the

    other operand register. To load a constant, it is necessary to load it into W before it can be

    moved into another register. On the older cores, all register moves needed to pass through W,

    but this changed on the "high end" cores.

    PIC cores have skip instructions which are used for conditional execution and branching. The

    skip instructions are: 'skip if bit set', and, 'skip if bit not set'. Because cores before PIC18 had

    only unconditional branch instructions, conditional jumps are implemented by a conditional

    http://en.wikipedia.org/wiki/Accumulator_(computing)http://en.wikipedia.org/wiki/Accumulator_(computing)
  • 8/3/2019 Unit 2 new

    4/42

    skip (with the opposite condition) followed by an unconditional branch. Skips are also of

    utility for conditional execution of any immediate single following instruction.

    The PIC architecture has no (or very meager) hardware support for automatically saving

    processor state when servicing interrupts. The 18 series improved this situation by

    implementing shadow registers which save several important registers during an interrupt.

    Interrupt Latency

    A very useful and unique property of PICs is that their interrupt latency is constant (it's also

    low: 3 instruction cycles). The delay is constant even though instructions can take one or two

    instruction cycles: a dead cycle is optionally inserted into the interrupt response sequence to

    make this true. External interrupts have to be synchronized with the four clock instruction

    cycle, otherwise there can be a one instruction cycle jitter. Internal interrupts are already

    synchronized.

    The constant interrupt latency allows PICs to achieve interrupt driven low jitter timing

    sequences. An example of this is a video sync pulse generator. Other microcontrollers can do

    this in some cases, but it's awkward. The non-interrupt code has to anticipate the interrupt and

    enter into a sleep state before it arrives. On PICs, there is no need for this.

    Criticisms

    PIC microcontrollers have a very small set of instructions, leading some to consider them

    RISC devices. However, the PIC architecture does not reflect many of the advantages of

    RISC design. For example:

    PIC does not have a load-store architecture, as memory is directly referenced in

    arithmetic and logic operations it has a single working register, while RISC designs typically include 16 or more

    general purpose registers

    its addressing modes are not orthogonal, since some instructions can address RAM or

    immediate data, while others can only use the working register

    register-bank switching is required to access the entire RAM of many PIC devices,

    making the development of libraries of position-independent code complex and

    inefficient

    a stackcannot be implemented efficiently, so it is difficult to generate reentrant code

    http://en.wikipedia.org/wiki/Reduced_instruction_set_computerhttp://en.wikipedia.org/wiki/Accumulatorhttp://en.wikipedia.org/wiki/General_purpose_registerhttp://en.wikipedia.org/wiki/Orthogonal#Computer_sciencehttp://en.wikipedia.org/wiki/Constanthttp://en.wikipedia.org/wiki/Bank_switchinghttp://en.wikipedia.org/wiki/Position-independent_codehttp://en.wikipedia.org/wiki/Stack_(data_structure)http://en.wikipedia.org/wiki/Reentranthttp://en.wikipedia.org/wiki/Reduced_instruction_set_computerhttp://en.wikipedia.org/wiki/Accumulatorhttp://en.wikipedia.org/wiki/General_purpose_registerhttp://en.wikipedia.org/wiki/Orthogonal#Computer_sciencehttp://en.wikipedia.org/wiki/Constanthttp://en.wikipedia.org/wiki/Bank_switchinghttp://en.wikipedia.org/wiki/Position-independent_codehttp://en.wikipedia.org/wiki/Stack_(data_structure)http://en.wikipedia.org/wiki/Reentrant
  • 8/3/2019 Unit 2 new

    5/42

    These properties have made it difficult to develop compilers that target PIC microcontrollers.

    While several commercial compilers are available, the Free software Small Device C

    Compiler has not yet completed support for PIC as of 2007. By contrast, Atmel's AVR

    microcontrollerswhich are competitive with PIC in terms of hardware capabilities and

    price, but feature a RISC instruction sethave long been supported by the GNU C Compiler.

    PIC assembly language code can be difficult to com prehend due to the limited addressing

    modes, code obfuscation via the "skip" instruction, and register juggling through the

    accumulator.

    However, it should be noted that judicious use of simple macros can make PIC assembly

    language much more palatable, but at the cost of a reduction in performance. For example,

    the original Parallax PIC assembler "pasm" has macros which hide W and make the PIC look

    like a two-address machine. It has macroinstructions like "mov b,a" (move the data from

    address a to address b) and "add b,a" (add data from address a to data in address b). It also

    hides the skip instructions by providing three operand branch macroinstructions such as "cjne

    a,b,dest" (compare a with b and jump to dest if they are not equal).

    Other drawbacks have been addressed in the PIC18 and PIC24/dsPIC series, but still apply to

    earlier cores:

    Data stored in program memory is space inefficient and/or time consuming to access,

    as it is not directly addressable. This is true of most Harvard architecture

    microcontrollers.

    The PIC architecture is somewhat unfriendly to high level language compilation.

    o A data stack implementation (for parameters and locals) would be dreadfully

    inefficient, leading to compilers storing these values at fixed memory

    locations. Thus, most C compilers do not generate re-entrant code.

    o The instruction set lacks an indexed addressing mode. The call stack is so small that program structure must often be flattened.

    The call stack is not addressable, so pre-emptive task switching cannot be

    implemented.

    Program memory is paged on PIC16 and older devices with large program memory.

    There are two page sizes to worry about: one for CALL and GOTO and another for

    computed GOTO (typically used for table lookups). For example, on PIC16, CALL

    and GOTO have 11 bits of addressing, so the page size is 2KB. For computed

    GOTOs, where you add to PCL, the page size is 256 bytes. In both cases, the upper

    http://en.wikipedia.org/wiki/Free_softwarehttp://en.wikipedia.org/wiki/Small_Device_C_Compilerhttp://en.wikipedia.org/wiki/Small_Device_C_Compilerhttp://en.wikipedia.org/wiki/As_of_2007http://en.wikipedia.org/wiki/Atmelhttp://en.wikipedia.org/wiki/Atmel_AVRhttp://en.wikipedia.org/wiki/GNU_C_Compilerhttp://en.wikipedia.org/wiki/Macro_(computer_science)http://en.wikipedia.org/wiki/Parallax%2C_Inc._(company)http://en.wikipedia.org/wiki/Harvard_architecturehttp://en.wikipedia.org/wiki/Free_softwarehttp://en.wikipedia.org/wiki/Small_Device_C_Compilerhttp://en.wikipedia.org/wiki/Small_Device_C_Compilerhttp://en.wikipedia.org/wiki/As_of_2007http://en.wikipedia.org/wiki/Atmelhttp://en.wikipedia.org/wiki/Atmel_AVRhttp://en.wikipedia.org/wiki/GNU_C_Compilerhttp://en.wikipedia.org/wiki/Macro_(computer_science)http://en.wikipedia.org/wiki/Parallax%2C_Inc._(company)http://en.wikipedia.org/wiki/Harvard_architecture
  • 8/3/2019 Unit 2 new

    6/42

    address bits are provided by the PCLATH register. This register must be changed

    every time control transfers between pages. A non-obvious case of this includes after

    when a CALL to a different page returns, since RETURN itself does not restore the

    current page number. PCLATH must also be preserved by any interrupt handler.

    Family Core Architectural Differences

    Baseline Core Devices

    These devices feature a 12-bit wide code memory, and a tiny two level deep call stack. They

    are represented by PIC10 series, as well as some PIC12 and PIC16 devices. Baseline devices

    are available in 6-pin to 40-pin packages.

    Mid-Range Core Devices

    These devices feature a 14-bit wide code memory, and an improved 8 level deep call stack.

    The instruction set differs very little from the baseline devices, but the increased opcode

    width allows more memory to be directly addressed. The mid-range core is available in the

    majority of devices labelled PIC12 and PIC16.

    PIC17 High End Core Devices

    The 17 series never became popular and has been superseded by the PIC18 architecture. It is

    not recommended for new designs, and may be in limited availability.

    Improvements over earlier cores are 16-bit wide opcodes (allowing many new instructions),

    and a 16 level deep call stack. PIC17 devices were produced in packages from 40 to 68 pins.

    The 17 series introduced a number of important new features:

    a memory mapped accumulator

    read access to code memory (table reads)

    direct register to register moves (prior cores needed to move registers through the

    accumulator)

    an external program memory interface to expand the code space

    an 8bit x 8bit hardware multiplier

    a second indirect register pair

  • 8/3/2019 Unit 2 new

    7/42

    auto-increment/decrement addressing controlled by control bits in a status register

    (ALUSTA)

    PIC18 High End Core Devices

    Microchip introduced the PIC18 architecture in 2002 , and unlike the 17 series, it has proven

    to be very popular, with a large number of device variants presently in manufacture. In

    contrast to earlier devices, which were more often than not programmed in assembly, C has

    become the predominant development language.[citation needed]

    The 18 series inherits most of the features and instructions of the 17 series, while adding a

    number of important new features:

    much deeper call stack (31 levels deep)

    the call stack may be read and written

    conditional branch instructions

    indexed addressing mode (PLUSW)

    extending the FSR registers to 12 bits, allowing them to linearly address the entire

    data address space

    the addition of another FSR register (bringing the number up to 3)

    The auto increment/decrement feature was improved by removing the control bits and adding

    four new indirect registers per FSR. Depending on which indirect file register is being

    accessed it is possible to postdecrement, postincrement, or preincrement FSR; or form the

    effective address by adding W to FSR.

    In more advanced PIC18 devices, an "extended mode" is available which makes the

    addressing even more favourable to compiled code:

    a new offset addressing mode; addresses which were relative to the access bank are

    now interpreted relative to the FSR2 register

    the addition of several new instructions, notable for manipulating the FSR registers.

    All new PIC18 devices being sold today (July 2007) are extended devices, and many popular

    PIC18 devices that were not extended have been replaced with extended devices. For

    example, the recommended replacement for the 18F452 is the 18F4520.

    http://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_needed
  • 8/3/2019 Unit 2 new

    8/42

    These changes were primarily aimed at improving the efficiency of a data stack

    implementation. If FSR2 is used either as the stack pointer or frame pointer, stack items may

    be easily indexed -- allowing more efficient re-entrant code. Microchip C18 chooses to use

    FSR2 as a frame pointer.

    PIC24 and dsPIC 16-bit Microcontrollers

    Microchip introduced the dsPIC series of chips in 2001, and they entered mass production in

    late 2004. They are Microchip's first inherently 16-bit microcontrollers. PIC24 devices are

    designed as general purpose microcontrollers. dsPIC devices include digital signal processing

    capabilities in addition.

    Architecturally, although they share the PIC moniker, they are very different than the 8-bit

    PICs. The most notable differences are

    they feature a set of 16 working registers

    they fully support a stack in RAM, and do not have a hardware stack

    bank switching is not required to access RAM or special function registers

    data stored in program memory can be accessed directly using a feature called

    Program Space Visibility

    interrupt sources may be assigned to distinct handlers using an interrupt vector table

    Some features are:

    hardware MAC (multiply-accumulate)

    barrel shifting

    bit reversal

    (16x16)-bit multiplication and otherDSP operations.

    hardware support for loop indexing

    Direct Memory Access

    dsPICs can be efficiently programmed in C using a variant ofgcc.

    PIC32MX 32-bit Microcontrollers

    In November 2007 Microchip introduced the new PIC32MX family of 32-bit

    microcontrollers. The initial device line-up is based on the industry standard MIPS

    http://en.wikipedia.org/w/index.php?title=DsPIC&action=edithttp://en.wikipedia.org/wiki/Digital_signal_processinghttp://en.wikipedia.org/wiki/Multiply-accumulatehttp://en.wikipedia.org/wiki/Barrel_shifterhttp://en.wikipedia.org/wiki/Digital_signal_processinghttp://en.wikipedia.org/wiki/Direct_Memory_Accesshttp://en.wikipedia.org/wiki/GNU_Compiler_Collectionhttp://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2018&mcparam=en532888http://www.mips.com/products/cores/32-bit-cores/mips32-m4k/http://en.wikipedia.org/w/index.php?title=DsPIC&action=edithttp://en.wikipedia.org/wiki/Digital_signal_processinghttp://en.wikipedia.org/wiki/Multiply-accumulatehttp://en.wikipedia.org/wiki/Barrel_shifterhttp://en.wikipedia.org/wiki/Digital_signal_processinghttp://en.wikipedia.org/wiki/Direct_Memory_Accesshttp://en.wikipedia.org/wiki/GNU_Compiler_Collectionhttp://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2018&mcparam=en532888http://www.mips.com/products/cores/32-bit-cores/mips32-m4k/
  • 8/3/2019 Unit 2 new

    9/42

    Technologies M4K 32-bit core. The device can be programmed using the Microchip C32

    compiler, a variant of the gcc compiler.

    THE PIC CPU REGISTERS

    The PIC MCU has a group of registers, from 0xFD8 to 0xFFF (listed in Table 1.2), in

    the data memory space that are dedicated to the general control of the CPU operation. This

    group of registers can be referred to as CPU registers. Each of these CPU registers is

    discussed in an appropriate chapter of this book.

    Address Name Description

    0xFFF TOSU Top of stack (upper)

    0xFFE TOSH Top of stack (high)

    0xFFD TOSL Top of stack (low)

    0xFFC STKPTR Stack pointer

    0xFFB PCLATU Upper program counter latch

    0xFFA PCLATH High program counter latch

    0xFF9 PCL Program counter low byte

    0xFF8 TBLPTRU Table pointer upper byte

    0xFF7 TBLPTRH Table pointer high byte

    0xFF6 TBLPTRL Table pointer low byte

    0xFF5 TABLAT Table latch

    0xFF4 PRODH High product register

    0xFF3 PRODL Low product register

    0xFF2 INTCON Interrupt control register

    0xFF1 INTCON2 Interrupt control register 2

    0xFF0 INTCON3 Interrupt control register 3

    0xFEF INDF0 (1) Indirect file register pointer 0

    0xFEE POSTINC0 (1) Post increment pointer 0 (to GPRs)

    0xFED POSTDEC0 (1) Post decrement pointer 0 (to GPRs)

    0xFEC PREINC0 (1) Preincrement pointer 0 (to GPRs)

    0xFEB PLUSW0 (1) Add WREG to FSR0

    0xFEA FSR0H File select register 0 high byte

    http://www.mips.com/products/cores/32-bit-cores/mips32-m4k/http://microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2615&dDocName=en532454http://microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2615&dDocName=en532454http://www.mips.com/products/cores/32-bit-cores/mips32-m4k/http://microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2615&dDocName=en532454http://microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2615&dDocName=en532454
  • 8/3/2019 Unit 2 new

    10/42

    0xFE9 FSR0L File select register 0 low byte

    0xFE8 WREG Working register

    0xFE7 INDF1 (1) Indirect file register pointer 1

    0xFE6 POSTINC1 (1) Post increment pointer 1 (to GPRs)

    0xFE5 POSTDEC1 (1) Post decrement pointer 1 (to GPRs)

    0xFE4 PREINC1 (1) Preincrement pointer 1 (to GPRs)

    0xFE3 PLUSW1 (1) Add WREG to FSR1

    0xFE2 FSR1H File select register 1 high byte

    0xFE1 FSR1L File select register 1 low byte

    0xFE0 BSR Bank select register

    0xFDF INDF2 (1) Indirect file register pointer 2

    0xFDE POSTINC2 (1) Post increment pointer 2 (to GPRs)

    0xFDD POSRDEC2 (1) Post decrement pointer 2 (to GPRs)

    0xFDC PREINC2 (1) Preincrement pointer 2 (to GPRs)

    0xFDB PLUSW2 (1) Add WREG to FSR2

    0xFDA FSR2H File select register 2 high byte

    0xFD9 FSR2L File select register 2 low byte

    0xFD8 STATUS Status register

    Table: PIC CPU registers

    The STATUS register, shown in Figure 1.6, contains the arithmetic status of the ALU.

    As with any other register, the STATUS register can be the destination of any instruction. If

    the STATUS register is the destination for an instruction that affects the Z, DC, C, OV, or N

    bits, then the write to these five bits is disabled. These bits are set or cleared according to the

    device logic. Therefore, the result of an instruction with the STATUS register as the

    destination may be different than intended. It is recommended, therefore, that only BCF,

    BSF, SWAPF, MOVFF, and MOVWF instructions be used to alter the STATUS register

    because these instructions do not affect the Z, C, DC, OV, or N bits of the STATUS register.

    N OV Z DC C

    N: Negative bit

    1 = arithmetic result is negative

  • 8/3/2019 Unit 2 new

    11/42

    0 = arithmetic result is positive

    OV: Overflow bit

    1 = Overflow occurred for signed arithmetic

    0 = No overflow occurred

    Z: Zero flag

    1 = The result of an arithmetic or logic operation is zero.

    0 = The result of an arithmetic or logic operation is not zero.

    DC: Digit carry/borrow bit

    For ADDWF, ADDLW, SUBLW, SUBWF instructions.

    1 = A carry-out from the 4th low-order bit of the result occurred.

    0 = No carry-out from the 4th low-order bit of the result occurred.

    For borrow, the polarity is reversed. For rotate (RRF, RLF)

    instructions, this bit is loaded with either the bit 4 or bit 3 of the

    source register.

    C: Carry/borrow bit

    For ADDWF, ADDLW, SUBLW, SUBWF instructions.

    1 = A carry-out from the most significant bit of the result occurred.

    0 = No carry-out from the most significant bit of the result has

    occurred.

    For borrow, the polarity is reversed. For rotate (RRF, RLF)

    instructions, this bit is loaded with either the high or low order bit

    of the source register.

    7 6 5 4 3 2 1 0

    The WREG register (referred to as working register) is a special register that is involved in

    the execution of many instructions and can be the destination of many instructions.

    The PIC Pipelining

    The PIC designer divided the execution of most of the PIC instructions into two

    stages (instruction fetch and instruction execution) and then overlapped the execution of two

  • 8/3/2019 Unit 2 new

    12/42

    consecutive instructions. Each stage takes one instruction clock cycle to complete. The result

    of the overlap of instruction execution is that most instructions take one instruction clock

    cycle to complete. This scheme is called instruction pipelining. An example of instruction

    pipelining is illustrated in Figure 1.7.

    MOVLW 55h

    MOVWF PORTB

    BRA sub_1

    BSF PORTA,BIT3

    Instruction @address sub_1

    fetch 1 execute 1

    fetch 2 execute 2

    fetch 3 execute 3

    fetch 4 flush

    fetch sub_1 execute sub_1

    TCY0 TCY1 TCY2 TCY3 TCY4 TCY5

    Note: All instructions are single cycle, except for any program branches.

    Figure 1.7 _ An example of instruction pipeline flow

    There are two problems caused by instruction pipelining: data dependency hazardand

    control hazard. In a program, it is common for one instruction to perform further operation

    on the result produced by the previous instruction. If the pipeline is designed in a way that the

    earlier instruction cannot write the result back to the register or memory location before it is

    used by the following instruction(s), then the data-dependency hazard has occurred. Most of

    the datadependency hazards can be solved by result forwarding. However, if an instruction

    reads from a memory location (e.g., a load instruction) whereas the following instruction will

    use the returned value to perform certain operation, then result forwarding cannot resolve the

    hazard. This problem is usually solved by rearranging the instruction sequence to avoid this

    type of data dependency or inserting a no-op instruction. The dependency hazard problem

    will occur on pipelined processors with more than two stages. The PIC18 instruction pipeline

    has only two stages and does not have data-dependency hazard problems. Control hazard is

    caused by branch instructions. Whenever a branch instruction reaches the execution stage and

    the branch is taken, then the following instructions in the pipeline need to be flushed because

    they are not allowed to take any effect by the program logic. In Figure 1.7, the instruction

    BSF PORTA, BIT3 is flushed when it reaches the execution stage for this reason. There are

  • 8/3/2019 Unit 2 new

    13/42

    several options to deal with control hazards in a pipelined processor. However, this issue is

    beyond the scope of this text.

    The PIC MCU needs to access program memory during the instruction fetch stage and needs

    to access data memory during the instruction execute stage. When pipelining the execution of

    instructions, the PIC18 MCU needs to access the program memory and the data memory in

    the same clock cycle. This requirement is satisfied by separating the program memory from

    the data memory and providing separate buses to them. The pipelined processor is explained

    clearly in Patterson and Hennessys book Computer Organization published by Morgan

    Kaufman.

    PIC Instruction Format

    It was mentioned in Section 1.5.2 that data memory is divided into banks. Why would the

    banking scheme be used to control the access of data memory? The instruction format must

    be defined in order to understand this issue.

    The instruction set is grouped into five basic categories:

    1.Byte-oriented operations.The format of byte-oriented instructions is shown in Figure 1.8.

    The 6-bit field opcode specifies the operation to be performed by the ALU.

    opcode d a f

    0 7 8 9 10 15

    d = 0 for result destination to be WREG register.

    d = 1 for result destination to be file register (f)

    a = 0 to force Access Bank

    a = 1 for BSR to select bank

    f = 8-bit file register address

    Figure 1.8 _ Byte-oriented file register operations (redraw with permission of Microchip)

    2.Byte-to-byte operations (two-word).The format of the instruction in this category is shown

    in Figure 1.9. There is only one instruction that uses this format: movff f1, f2. This

    instruction allows one to move data from one file register to another.

    opcode f (source file register)

    0 12 15 11

    1111 f (destination file register)

    0 12 15 11

    f = 12-bit file register address

  • 8/3/2019 Unit 2 new

    14/42

    Figure 1.9 _ Byte-to-byte move operations (2 words) (redraw with permission of Microchip)

    3.Bit-oriented file register operations.The format of instructions in this category is shown

    in Figure 1.10. This format uses an 8-bit field (f) to specify a file register as the operand.

    opcode b a f

    0 7 8 11 15

    b = 3-bit position of bit in the file register (f).

    a = 0 to force Access Bank

    a = 1 for BSR to select bank

    f = 8-bit file register address

    12 9

    Figure 1.10 _ Bit-oriented file register operations (redraw with permission of Microchip)

    4.Literal operations.Instructions in this category specify a literal(a number) as an operand.

    The format of instructions in this category is shown in Figure 1.11.

    opcode k

    0 7 8 15

    k = 8-bit immediate value

    Figure 1.11 _ Literal operations (redraw with permission of Microchip)

    opcode n (literal)

    0 7 8 15

    1111 n (literal)

    0 7 8 15

    n = 20-bit immediate value

    GOTO label

    opcode n (literal)

    0 7 8 15

    1111 n (literal)

    0 7 8 15

    S = fast bit

    S

    CALL funct_name

    opcode n (literal)

    0 10 11 15

    opcode n (literal)

    0 7 8 15

  • 8/3/2019 Unit 2 new

    15/42

    BRA func_name

    BC func_name

    Figure 1.12 _ Control operations (redraw with permission of Microchip)

    5. Control operations.The format of instructions in this category is shown in Figure 1.12.

    The notation n stands for the bit 7 to bit 0 of the number n, whereas the notation

    n stands for the bit 19 to bit 8 of the number n. The notation n means that the

    number n is an 11-bit number. There are four different variations in their formats. As shown

    in Figures 1.8 to 1.12, all the PIC18 instructions use eight bits to specify the data register

    operand. A data register (excluding WREG) is also called afile register. Only 256 different

    registers can be specified by eight bits. However, all the PIC18 devices have more than 256

    file registers, and hence additional information is needed to pinpoint the exact register to be

    operated on. This additional information is stored in the BSR register. The designer of the

    PIC18 MCU divided data memory into 16 (maximum) banks, with each bank having 256

    data registers. The BSR register specifies the bank, and the f field in the instruction specifies

    the register number within the bank.

    The banking scheme has been used in the PIC12, the PIC14000, the PIC16, and the PIC17

    MCUs. This scheme allows a PIC MCU to incorporate more than 256 data registers on the

    CPU. However, it also adds a significant amount of overhead to the software because of the

    need to switch from one bank to another. In addition, it is easy to forget about bank

    switching, which will cause the software to fail.

    In order to solve the problem caused by the banking scheme, the designers of the PIC18

    MCU incorporated the access bank. The access bank consists of the lowest 96 GPRs and the

    highest 160 SFRs. As long as an instruction specifies a data register in the access bank,

    banking is ignored, and bank switching is unnecessary. All SFRs except a subset in the CAN

    module are in the access bank (CAN stands for controller area network). This makes bank

    switching unnecessary in many cases.

    When bank switching is needed, the movlb kinstruction can be used. This instruction places

    the value of k in the lower four bits of the BSR register. The result of the execution of this

    instruction is that it caused the data registers in bank k to become active. In Figures 1.8 and

    1.10, the a field in the PIC18 instruction allows the user to select the access bank. When

    writing program in assembly language, the assembler (MPASM) allows the user to use the

    letter A (a = 0) to specify the access bank. When the access bank is not chosen, one should

    use the word BANKED (a = 1) to allow the BSR register to do the bank selection.

  • 8/3/2019 Unit 2 new

    16/42

    The d field in Figure 1.8 allows the user to choose either the WREG or the file register as the

    destination of the instruction. The assembler allows the user to use the letter F (d = 1) to

    specify a file register and use the letter W (d = 0) to specify the WREG register as the

    destination.

    For example,

    addwf sum, F, A ; sum is a GPR

    adds the WREG register and sum in the access bank and places the result in sum.

    addwf sum,W, A

    performs the same operation but leaves the result in the WREG register.

    Addressing Modes

    All MCUs use addressing modes to specify the operand to be operated on. The PIC18 MCU

    provides register direct, immediate, inherent, indirect, and bit-direct addressing modes for

    specifying instruction operands. As discussed in Chapter 2, assembler directives allow the

    user to use symbols to refer to memory locations. Using symbols to refer to memory locations

    makes the user program more readable. During the following discussion, symbols are used to

    refer to memory locations when appropriate.

    Register Direct

    The PIC18 device uses an 8-bit value to specify a data register as an operand. The register

    may be in the access bank or other banks. In the first case, the 8-bit value is used to select a

    register in the access bank, and the bank value in the BSR register is ignored. If the access

    bank is not selected, then the access is completed from the memory of the bank specified in

    the BSR register. The following instructions illustrate the register direct addressing mode:

    movwf 0x1A, BANKED

    copies the contents of the WREG register to the memory location 0x1A in the bank specified

    by the BSR register. The word BANKED (must be in uppercase) informs the assembler that

    the BSR register must be included in specifying the data register to be operated on.

    movwf 0x45, A

    copies the contents of the WREG register to the memory location 0x45 in the access bank.

    movff reg1, reg2

    copies the contents of the register reg1 to the register reg2. Both reg1 and reg2 are 12-bit

    values. The value of BSR is ignored.

  • 8/3/2019 Unit 2 new

    17/42

    Immediate Mode

    In the immediate addressing mode, the actual operand is provided in the instruction. There is

    no need to access any memory location. The following instructions illustrate the immediate

    addressing mode:

    addlw 0x20

    adds the hex value 20 to the WREG register and places the sum in the WREG register.

    movlw 0x15

    loads the hex value 15 into the WREG register.

    movlb 3

    places the decimal value 3 in the lower four bits of the BSR register. The lower four bits

    become 0011. This instruction makes bank 3 the active bank. The value to be operated on

    directly is often called literal.

    Inherent Mode

    In the inherent mode, the operand is implied in the opcode field. The instruction opcode does

    not provide the address of the implied operand. The following instructions illustrate the

    inherent mode:

    movlw 0x20

    places the hex value 20 (decimal 32) in the WREG register. In this example, the value 0x20 is

    specified in the instruction machine code. The destination WREG is implied in the opcode

    field. No other address information for the WREG register is supplied.

    andlw 0x13

    performs an AND operation on the corresponding bits of the hex number 13 and the WREG

    register (i.e., bit i of WREG and with bit i of the value 0x13; i = 0 . . . 7). In this example,

    only the immediate value 0x13 is specified in the instruction machine code. The address of

    the WREG register 0xFE8 is not specified.

    Indirect Mode

    In this mode, a special function register is used as a pointer to the data memory location that

    is to be read and written. Since this register is in SRAM, the contents can be modified by the

    program. This can be useful for data tables in data memory and forsoftware stacks. The

    software stack will be explained in Chapter 4.

  • 8/3/2019 Unit 2 new

    18/42

    There are three indirect addressing registers: FSR0, FSR1, and FSR2. To address the entire

    data memory space (4096 bytes), 12 bits are required. To store the 12-bit address

    information, two 8-bit registers are used. These indirect addressing registers are the

    following:

    1. FSR0: composed of FSR0H and FSR0L

    2. FSR1: composed of FSR1H and FSR1L

    3. FSR2: composed of FSR2H and FSR2L

    After placing the address of the data in one of the FSR registers, one needs to read from or

    write into one of the three registers that are not physically implemented in order to activate

    indirect addressing. These three registers are INDF0, INDF1, and INDF2.

    If an instruction writes a value to INDF0, the value will be written to the data register with

    the address indicated by the register pair FSR0H:FSR0L. A read from INDF1 reads the data

    from the data register with the address indicated by the register pair FSR1H:FSR1L. INDFn

    can be used in a program anywhere an operand can be used. The process of indirect

    addressing is illustrated in Figure 1.13.

    11 8 7 0

    FSRnH FSRnL

    Data memory

    Location select

    0x000

    0xFFF

    Accessing INDFn

    Figure 1.13 _ Indirect addressing

    Each FSR register has an INDF register associated with it plus four additional register

    addresses. Performing an operation on one of these five registers determines how the FSR

    will be modified during indirect addressing:

    1. Do nothing to FSRn after an indirect access. This access is specified by using the register

    INDFn (n = 0 . . . 2).

    2. Auto-decrement FSRn after an indirect access (postdecrement). This access is specified by

    using the register POSTDECn (n = 0 . . . 2).

    3. Auto-increment FSRn after an indirect access (postincrement). This access is specified by

    using the register POSTINCn (n = 0 . . . 2).

  • 8/3/2019 Unit 2 new

    19/42

    4. Auto-increment FSRn before an indirect access (preincrement). This access is specified by

    using the register PREINCn (n = 0 . . . 2).

    5. Use the value in the WREG register as an offset to FSRn. The signed value in WREG is

    added to the value in FSR to form an address before performing an indirect access. Neither

    the WREG nor the FSRn is modified after the access. This access is specified by using the

    register PLUSWn.

    The following examples illustrate the usage of indirect addressing modes:

    movwf INDF0

    copies the contents of the WREG register to the data memory location specified by the FSR0

    register. After the execution of this instruction, the contents of the FSR0 register are not

    changed.

    movwf POSTDEC0

    copies the contents of the WREG register to the data memory location specified by the FSR0

    register. The contents of FSR0 are decremented by 1 after the operation.

    movwf PREINC0

    first increments the FSR0 register by 1 and then copies the contents of the WREG register to

    the data memory location specified by the FSR0 register.

    clrf PLUSW0

    clears the memory location at the address equal to the sum of the value in the WREG register

    and that in the FSR0 register.

    In the previous examples, one does not need to specify whether the register is in the access

    bank because the complete 12-bit data register address is taken from one of the FSR registers.

    Bit-Direct Addressing Mode

    The PIC18 MCU has five instructions to deal with an individual bit. These instructions use

    three bits to specify the bit to be operated on. For example,

    BCF PORTB,3,A ; integer 3 specifies the bit to be cleared clears bit 3 of the data register

    PORTB, which will then pull the port B pin RB3 to low.

    BSF PORTA,4,A ; integer 4 specifies the bit to be set sets bit 4 of the data register PORTA,

    which will then pull the port A pin RA4 to high.

    A Sample of PIC Instructions

  • 8/3/2019 Unit 2 new

    20/42

    The PIC has 77 instructions. Four of these are 32-bit instructions, whereas the others

    are all 16 bits. A subset of the PIC instructions is examined in this section.

    Data Movement Instructions

    Memory data must be placed in appropriate registers before useful operations can be

    performed. Data movement instructions are provided for this purpose. A subset of the data

    movement instructions is listed in Table 1.3.

    Mnemonic Description 16-bit instruction word Status affected

    lfsr f, k load FSR 1110 1110 00ff k11kkk None

    1111 0000 k7kkk kkkk

    movf f, d, a Move f 0101 00da ffff ffff Z, N

    movff fs, fd Move fs (source) to f 1100 ffff ffff ffff None

    1111 ffff ffff ffff

    movwf, f,a Move WREG to f 0110 111a ffff ffff None

    swapf f, d, a Swapp nibbles in f 0011 10da ffff ffff None

    movlb k Move literal to BSR 0000 0001 kkkk kkkk None

    movlw k Move literal to WREG 0000 1110 kkkk kkkk None

    Note. Both LFSR f, kand MVFF fs, fd are 32-bit instructions

    Table 1.3 _ A sample of PIC18 data movement instructions

    The instruction lfsr f, k, a 32-bit instruction, allows the user to place a 12-bit value in the

    FSR register specified by the value f. Two bits are provided for selecting the FSR registers

    (FSR0FSR2). A 12-bit value (k) is contained in the instruction. The upper four bits

    (represented as k11kkk in Table 1.3) of k are contained in the first word of the instruction,

    whereas the lower eight bits (represented as k7kkk kkkk in Table 1.3) are contained in the

    second word. The instruction movf f, d, a in Table 1.3 is provided for easy migration from

    the PIC16 family to the PIC18 family because the PIC16 family also has the same instruction.

    By setting the d field to 0 (represented by the letter W), this instruction will copy the contents

    of a file register to the WREG register. For example, the instruction

    movf 0x20,W,A

    will copy the contents of the data register at 0x20 to the WREG register.

    The movff instruction, a 32-bit instruction, can copy a file register in one bank to a file

    register in another bank without referring to the BSR register. Both the source and the

  • 8/3/2019 Unit 2 new

    21/42

    destination registers are specified in 12 bits. The movlb kinstruction sets the bank k as the

    active bank. The movlw kinstruction places the value k in the WREG register.

    Example 1.1

    Write a PIC18 instruction (or instruction sequence) to transfer data from (a) WREG to data

    register at 0x30, (b) the data register at 0x30 to the data register at 0x40, (c) the data register

    at 0x40 to WREG, and (d) load the value 0x200 into FSR0.

    Solution:

    (a) movwf 0x30,A ; force access bank

    (b) movff 0x30, 0x40 ;

    (c) movf 0x40,W,A ; force access bank and copy register 0x40 to WREG

    (d) lfsr FSR0, 0x200 ; load the value 0x200 into FSR0

    ADD Instructions

    ADD is the generic name of a group of instructions that perform the addition operation. The

    ADD instruction may have two or three operands. A three-operand ADD instruction includes

    the carry flag in the STATUS register as one of the operand. The PIC18 MCU has 3 ADD

    instructions:

    addwf f, d, a ; add WREG and f

    addwfc f, d, a ; add WREG, carry bit, and f

    addlw k ; add literal k to WREG

    Example 1.2

    Write an instruction to perform the following operations:

    (a) Add the content of WREG and that of the data register at 0x40 (in access bank) and leave

    the sum in WREG.

    (b) Increment the WREG register by 5.

    (c) Add the WREG register, the register with the name of sum, and carry and leave the result

    in sum. The variable sum is in access bank.

    Solution:

    (a) addwf 0x40,W,A

    (b) addlw 5

    (c) addwfc sum, F, A

  • 8/3/2019 Unit 2 new

    22/42

    Example 1.3

    Write an instruction sequence to increment the contents of three registers 0x300x32 by 3.

    Solution: The procedure for incrementing the value of a register by 3 is as follows:

    Step 1

    Place the value 3 in the WREG register.

    Step 2

    Execute the addwf f, d, a instruction.

    The following instruction will increment the specified three registers by 3:

    movlw 0x3

    addwf 0x30, F, A ; increment the register at 0x30 by 3

    addwf 0x31, F, A ; increment the register at 0x31 by 3

    addwf 0x32, F, A ; increment the register at 0x32 by 3

    Example 1.4

    Write an instruction sequence to add the contents of three data registers located at 0x400x42

    and store the sum at 0x50.

    Solution: The required operation can be achieved by the following procedure:

    Step 1

    Load the contents of the register at 0x40 into the WREG register.

    Step 2

    Add the contents of the register at 0x41 into the WREG register.

    Step 3

    Add the contents of the register at 0x42 into the WREG register.

    Step 4

    Store the contents of the WREG register in the register at 0x50.

    The following instructions will perform the desired operation:

    movf 0x40, W, A ; WREG [0x40]

    addwf 0x41, W, A ; add the contents of the register at 0x41 to WREG

    addwf 0x42, W, A ; add the contents of the register at 0x42 to WREG

    movwf 0x50, A ; 0x50 [WREG]

    Example 1.5

  • 8/3/2019 Unit 2 new

    23/42

    Write an instruction sequence to add 10 to the data registers at 0x3000x303 using the

    indirect postincrement addressing mode.

    Solution: The procedure for solving this problem is as follows:

    Step 1

    Load the value 0x300 into the FSR0 register.

    Step 2

    Load the value 10 into the WREG register.

    Step 3

    Add the value in WREG to the data register pointed by FSR0 using the indirect

    postincrement mode.

    Step 4

    Repeat Step 3 three more times.

    The instruction sequence that carries the operations from Step 1 to Step 3 is as follows:

    movlw 0x0A

    lfsr FSR0,0x300 ; place 0x300 in FSR0

    addwf POSTINC0,F

    addwf POSTINC0,F

    addwf POSTINC0,F

    addwf POSTINC0,F

    SUB Instructions

    SUB is the generic name of a group of instructions that perform the subtraction operation.

    The SUB instruction may have two or three operands. A three-operand SUB instruction

    includes the carry flag in the STATUS register as one of the operands. The PIC18 MCU

    provides four SUB instructions:

    subfwb f, d, a ; subtract f from WREG with borrow

    subwf f, d, a ; subtract WREG from f

    subwfb f, d, a ; subtract WREG from f with borrow

    sublw k ; subtract WREG from literal

    Example 1.6

    Write an instruction sequence to subtract 9 from the data registers located at 0x500x53.

  • 8/3/2019 Unit 2 new

    24/42

    Solution: This operation can be implemented by placing 9 in the WREG register and then

    executing the subwf f,F,A instruction. The following instruction sequence will implement the

    required operation:

    movlw 0x09 ; place 9 in the WREG register

    subwf 0x50,F,A ; decrement the contents of the register at 0x50 by 9

    subwf 0x51,F,A ; decrement the contents of the register at 0x51 by 9

    subwf 0x52,F,A ; decrement the contents of the register at 0x52 by 9

    subwf 0x53,F,A ; decrement the contents of the register at 0x53 by 9

    Example 1.7

    Write an instruction to perform each of the following operations:

    Subtract the WREG register from the file register at 0x30 and leave the difference in the file

    register at 0x30.

    Subtract the file register at 0x30 and borrow from the WREG register.

    Subtract the WREG register from the file register at 0x50 and leave the difference in WREG.

    Solution: The following instructions will perform the specified operations:

    (a) subwf 0x30, F, A

    (b) subfwb 0x30, W, A

    (c) subwf 0x50,W,A

  • 8/3/2019 Unit 2 new

    25/42

  • 8/3/2019 Unit 2 new

    26/42

    SERIAL PROTOCOLS: I2C

    I2C (Inter-IC)

    Two-wire serial bus protocol developed by Philips Semiconductors nearly 20

    years ago

    Enables peripheral ICs to communicate using simple communication hardware

    Data transfer rates up to 100 kbits/s and 7-bit addressing possible in normal

    mode

    3.4 Mbits/s and 10-bit addressing in fast-mode

    Common devices capable of interfacing to I2C bus:

    EPROMS, Flash, and some RAM memory, real-time clocks, watchdog

    timers, and microcontrollers

    SCL

    SDA

    Micro-controller

    (master)

    EEPROM(servant)

    Temp.

    Sensor(servant)

    LCD-

    controller(servant) < 400 pF

    Addr=0x01 Addr=0x02 Addr=0x03

    D

    CS

    T

    AR

    T

    A

    6

    A

    5

    A

    0

    R/

    w

    AC

    K

    D

    8

    D

    7

    D

    0

    AC

    K

    S

    T

    O

    P

    FromServant

    From

    receiver

    Typical read/write cycle

    SDA

    SCL

    SDA

    SCL

    SDA

    SCL

    SDA

    SCL

    Start condition Sending 0 Sending 1 Stop condition

  • 8/3/2019 Unit 2 new

    27/42

    ANALOG TO DIGITAL CONVERTORS.

    The usual method of bringing analog inputs into a microprocessor is to use an analog-

    to-digital converter (ADC). Here are some tips for selecting such a part and calibrating

    it to fit your needs.

    In analog-to-digital converter (ADC) accepts an analog input-a voltage or a current-and

    converts it to a digital value that can be read by a microprocessor. Figure 1 shows a simple

    voltage-input ADC. This hypothetical part has two inputs: a reference and the signal to be

    measured. It has one output, an 8-bit digital word that represents the input value.

    The reference voltage is the maximum value that the ADC can convert. Our example 8-bit

    ADC can convert values from 0V to the reference voltage. This voltage range is divided into

    256 values, or steps. The size of the step is given by:

    Vref/256

    http://img.cmpnet.com/embedded/gifs/2001/0105/0105feat1fig1.gifhttp://img.cmpnet.com/embedded/gifs/2001/0105/0105feat1fig1.gif
  • 8/3/2019 Unit 2 new

    28/42

    where Vref is the reference voltage. The step size of the converter defines the converter's

    resolution. For a 5V reference, the step size is:

    5V/256 = 0.0195V or 19.5mV

    Our 8-bit converter represents the analog input as a digital word. The most significant bit of

    this word indicates whether the input voltage is greater than half the reference (2.5V, with a

    5V reference). Each succeeding bit represents half the range of the previous bit

    Our 8-bit converter represents the analog input as a digital word. The most significant bit of

    this word indicates whether the input voltage is greater than half the reference (2.5V, with a

    5V reference). Each succeeding bit represents half the range of the previous bit.

    A universal asynchronous receiver/transmitter (usually abbreviated UART and

    pronounced/jurt/) is a type of "asynchronous receiver/transmitter", a piece of computer

    hardware that translates data between parallel and serial forms. UARTs are commonly used

    in conjunction with other communication standards such as EIARS-232.

    A UART is usually an individual (or part of an) integrated circuit used for serial

    communications over a computer or peripheral device serial port. UARTs are now commonlyincluded in microcontrollers. A dual UART orDUART combines two UARTs into a single

    chip. Many modern ICs now come with a UART that can also communicate synchronously;

    these devices are called USARTs

    Transmitting and receiving serial data

    Bits have to be moved from one place to another using wires or some other medium. Over

    many miles, the expense of the wires becomes large. To reduce the expense of long

    communication links carrying several bits in parallel, data bits are sent sequentially, one after

    another, using a UART to convert the transmitted bits between sequential and parallel form at

    each end of the link. Each UART contains a shift registerwhich is the fundamental method of

    conversion between serial and parallel forms.

    The UART usually does not directly generate or receive the external signals used between

    different items of equipment. Typically, separate interface devices are used to convert the

    logic level signals of the UART to and from the external signalling levels.

    http://en.wikipedia.org/wiki/Help:Pronunciationhttp://en.wikipedia.org/wiki/Computerhttp://en.wikipedia.org/wiki/Hardwarehttp://en.wikipedia.org/wiki/Electronic_Industries_Alliancehttp://en.wikipedia.org/wiki/RS-232http://en.wikipedia.org/wiki/Integrated_circuithttp://en.wikipedia.org/wiki/Serial_communicationshttp://en.wikipedia.org/wiki/Serial_communicationshttp://en.wikipedia.org/wiki/Serial_porthttp://en.wikipedia.org/wiki/Shift_registerhttp://en.wikipedia.org/wiki/Help:Pronunciationhttp://en.wikipedia.org/wiki/Computerhttp://en.wikipedia.org/wiki/Hardwarehttp://en.wikipedia.org/wiki/Electronic_Industries_Alliancehttp://en.wikipedia.org/wiki/RS-232http://en.wikipedia.org/wiki/Integrated_circuithttp://en.wikipedia.org/wiki/Serial_communicationshttp://en.wikipedia.org/wiki/Serial_communicationshttp://en.wikipedia.org/wiki/Serial_porthttp://en.wikipedia.org/wiki/Shift_register
  • 8/3/2019 Unit 2 new

    29/42

    External signals may be of many different forms. Voltage is by far the most common kind of

    signalling used. Examples of standards for voltage signalling are RS-232, RS-422 and RS-

    485 from the EIA. Historically, the presence or absence of current (in current loops) was used

    in telegraph circuits.

    Some signalling schemes do not use electrical wires. Examples of such are optical fiber,

    infrared, and (wireless) Bluetooth in its Serial Port Profile (SPP). Some signalling schemes

    use modulation of a carrier signal (with or without wires). Examples are modulation of audio

    signals with phone line modems, RF modulation with data radios, and the DC-LIN forpower

    line communication.

    Communication may be "full duplex" (both send and receive at the same time) or "halfduplex" (devices take turns transmitting and receiving).

    As of 2006, UARTs are commonly used with RS-232 for embedded systems

    communications. It is useful to communicate between microcontrollers and also with PCs.

    Many chips provide UART functionality in silicon, and low-cost chips exist to convert logic

    level signals (such as TTL voltages) to RS-232 level signals (for example, Maxim's MAX232

    Asynchronous receive and transmit

    In asynchronous transmitting, teletype-style UARTs send a "start" bit, five to eight data bits,

    least-significant-bit first, an optional "parity" bit, and then one, one and a half, or two "stop"

    bits. The start bit is the opposite polarity of the data-line's idle state. The stop bit is the data-

    line's idle state, and provides a delay before the next character can start. (This is called

    asynchronous start-stop transmission). In mechanical teletypes, the "stop" bit was often

    stretched to two bit times to give the mechanism more time to finish printing a character. A

    stretched "stop" bit also helps resynchronization.

    The parity bit can either make the number of "one" bits between any start/stop pair odd, or

    even, or it can be omitted. Odd parity is more reliable because it assures that there will

    always be at least one data transition, and this permits many UARTs to resynchronize.

    Insynchronous transmission, the clock data is recovered separately from the data stream and

    no start/stop bits are used. This improves the efficiency of transmission on suitable channels

    since more of the bits sent are usable data and not character framing. An asynchronous

    http://en.wikipedia.org/wiki/RS-232http://en.wikipedia.org/wiki/RS-422http://en.wikipedia.org/wiki/RS-485http://en.wikipedia.org/wiki/RS-485http://en.wikipedia.org/wiki/Electronic_Industries_Alliancehttp://en.wikipedia.org/wiki/Current_loophttp://en.wikipedia.org/wiki/Fiber_opticshttp://en.wikipedia.org/wiki/Infraredhttp://en.wikipedia.org/wiki/Bluetoothhttp://en.wikipedia.org/wiki/Modemhttp://www.yamar.com/DC-LIN.htmlhttp://en.wikipedia.org/wiki/Power_line_communicationhttp://en.wikipedia.org/wiki/Power_line_communicationhttp://en.wikipedia.org/wiki/RS-232http://en.wikipedia.org/wiki/Transistor-transistor_logichttp://en.wikipedia.org/wiki/Maxim_Integrated_Productshttp://en.wikipedia.org/w/index.php?title=MAX232&action=edithttp://en.wikipedia.org/wiki/Teletypehttp://en.wikipedia.org/wiki/Asynchronous_start-stophttp://en.wikipedia.org/wiki/RS-232http://en.wikipedia.org/wiki/RS-422http://en.wikipedia.org/wiki/RS-485http://en.wikipedia.org/wiki/RS-485http://en.wikipedia.org/wiki/Electronic_Industries_Alliancehttp://en.wikipedia.org/wiki/Current_loophttp://en.wikipedia.org/wiki/Fiber_opticshttp://en.wikipedia.org/wiki/Infraredhttp://en.wikipedia.org/wiki/Bluetoothhttp://en.wikipedia.org/wiki/Modemhttp://www.yamar.com/DC-LIN.htmlhttp://en.wikipedia.org/wiki/Power_line_communicationhttp://en.wikipedia.org/wiki/Power_line_communicationhttp://en.wikipedia.org/wiki/RS-232http://en.wikipedia.org/wiki/Transistor-transistor_logichttp://en.wikipedia.org/wiki/Maxim_Integrated_Productshttp://en.wikipedia.org/w/index.php?title=MAX232&action=edithttp://en.wikipedia.org/wiki/Teletypehttp://en.wikipedia.org/wiki/Asynchronous_start-stop
  • 8/3/2019 Unit 2 new

    30/42

    transmission sends nothing over the interconnection when the transmitting device has nothing

    to send; but a synchronous interface must send "pad" characters to maintain synchronism

    between the receiver and transmitter. The usual filler is the ASCII "SYN" character. This

    may be done automatically by the transmitting device.

    USART chips have both synchronous and asynchronous modes.

    Serial to Parallel Algorithm

    A data communicationpulse can only be in one of two states but there are many names for

    the two states. When on, circuit closed, low voltage, current flowing, or a logical zero, the

    pulse is said to be in the "space" condition. When off, circuit open, high voltage, current

    stopped, or a logical one, the pulse is said to be in the "mark" condition. A character code

    begins with the data communication circuit in the space condition. If the mark condition

    appears, a logical one is recorded otherwise a logical zero

    LOOP TIMING.

    One of the most important tasks a microcontroller can do is...

    ...measure time.

    The microcontroller can easily do this as it operates using a fixed frequency clock oscillator.

    The clock oscillator sets the speed of the microcontroller operation - this can either be an

    external crystal (up to 20MHz) or for modern PIC devices it can be an internal RC oscillator

    (from 4MHz to 8MHz).

    Assembler code loop timing

    By creating a routine containing an assembler code loop and knowing the clock speed you

    can create exact delay times since you know the time taken for each instruction to execute

    (from the datasheet). If you repeatedly executed this routine and kept a count of the number

    of times it's called then you can measure time in multiples of the execution time of the

    routine.

    http://en.wikipedia.org/wiki/ASCIIhttp://en.wikipedia.org/wiki/Data_communicationhttp://en.wikipedia.org/wiki/Pulse_(signal_processing)http://en.wikipedia.org/wiki/Character_codehttp://en.wikipedia.org/wiki/Data_communicationhttp://en.wikipedia.org/wiki/ASCIIhttp://en.wikipedia.org/wiki/Data_communicationhttp://en.wikipedia.org/wiki/Pulse_(signal_processing)http://en.wikipedia.org/wiki/Character_codehttp://en.wikipedia.org/wiki/Data_communication
  • 8/3/2019 Unit 2 new

    31/42

    There's two problems to this method.

    1.The microcontroller is not doing useful work while it is executing the delay routine.

    2.Measuring the delay time of the code is not always easy (especially for complex loops).

    Internal Timer Peripherals

    The advantage of the timer peripherals is that they make it a trivial task to measure time.

    They are hardware modules that operate separately from the CPU part of the microcontroller.

    This also means that they are capable of very high speed operation (you can make a 50MHz

    frequency counter using a timer (even for the obsolete 16F84 device).

    In the modern microcontrollers there are three timers; Timer0 Timer1 and Timer2 and each

    has different operations and capabilities. You can use the timers to count periods of the

    internal clock or you can count periods of an external clock (for a signal connected to the

    correct pin of the microcontroller) i.e. a timer input- for Timer 0 this would be T0CKI -

    Timer0 ClocK Input)

    There are two ways to use a timer polled or interrupt.

    Polling

    You can continuously read the timer values until you detect a value you want to measure e.g.

    to count to 1000 compare the timer registers to 1000 then do something.

    Although it's simple the disadvantage is that the microcontroller can do nothing else while

    polling (or can do very little as it has to keep going back and looking at the timer registers).

    Interrupt

    When a timer overflows (passes from its maximum value to zero) it generates an interrupt

    signal which you can use to interrupt the CPU to tell it something has happened.

  • 8/3/2019 Unit 2 new

    32/42

    This means the CPU can go and do other processing tasks while the timer hardware is

    running in the background.

    Although more complex to set up and use an interrupt driven timer is the better way to use a

    timer if you need to do other processing tasks.

    When you add in other peripherals interrupts are essential e.g. measuring time while

    servicing a serial interface.

    Timer 0,1,2 summary

    Timer 0

    Timer 0 is an 8 bit timer with an 8 bit prescaler - in total it looks like a 16 bit timer and it was

    the original peripheral (actually the only peripheral in the 16F84!). Its slightly tricky to use

    when starting out as you can not read the prescaler value (there are ways around this).

    So lets just look at the next timer:

    Timer 1

    Timer1 is a 16bit timer with a prescaler that can be set to 1,2,4 or 8 and it can take an input

    clock from a pin or use the internal oscillator (Fosc/4).

    A prescaler is just a divider so if you had a clock frequency of 8MHz and the prescaler as set

    to 8 the output from the prescaler would be 1MHz.

    Timer 2

    Timer 2 is an 8 bit timer that can only count periods of the internal clock Fosc/4. It has a 2

    bit prescaler and a 4 bit postscaler - these make the range out output periods (or frequency)

    flexible.

    In addition it has a period counting register that resets the counter when the counter reaches a

    programmed count (programmed by you). This means Timer 2 can generate a wide range of

    output frequencies easily and this is used to generate the baud clock for the internal USART.

  • 8/3/2019 Unit 2 new

    33/42

    Timers

    most RISC operations take one machine cycle but jumps take two cycles because of the need

    to refresh the pipeline. Start with a simple loop subroutine such as...

    . . .

    call delay

    . . .

    delay

    movlw n_times ;set to loop n times

    movwf ncntr ;into a counter register

    lp1 decfsz ncntr,f ;decrement and test counter

    goto lp1 ;keep looping until done

    return

    This routine uses 2 [initialize] + ((n-1) + 2) [dec] + 2(n-1) [goto] + 4 [call/return] machine

    cycles which reduces to (3n+1)+4 for a simple loop.

    This simple loop can delay for a maximum of 256*3+5 or773 cycles.

    For a crystal frequency of 20 MHz, the internal operating frequency is 5 MHz. The loop

    delay for a simple loop is 773/5Mhzor approximately 155 s.

    This delay is often not enough so a nesting loop can be added as in...

    . . .

    call delay

    . . .

  • 8/3/2019 Unit 2 new

    34/42

    delay

    movlw m_times ;set outside to loop m times

    movwf mcntr ;into a counter register

    lp2 movlw n_times ;set inside to loop n times

    movwf ncntr ;into a counter register

    lp1 decfsz ncntr,f ;decrement and test counter

    goto lp1 ;keep inside looping until done

    decfsz mcntr,f;decrement and test counter

    goto lp2 ;keep outside looping until done

    return

    This routine uses ((3n+1)*m)+(3m+1)+4 machine cycles which reduces to 3nm+4m+5 for a

    nested loop.

    Now the maximum number of cycles is 197,633

    And the maximum duration is 196857/5MHz = 39.52 ms.

    And of course another nesting extends the time interval even more!

    . . .

    call delay

    . . .

    delay

    movlw p_times ;set outside to loop p times

    movwf pcntr ;into a counter register

  • 8/3/2019 Unit 2 new

    35/42

    lp3 movlw m_times ;set middle to loop m times

    movwf mcntr ;into a counter register

    lp2 movlw n_times ;set inside to loop n times

    movwf ncntr ;into a counter register

    lp1 decfsz ncntr,f ;decrement and test n_counter

    goto lp1 ;keep inside looping until done

    decfsz mcntr,f;decrement and test m_counter

    goto lp2 ;keep outside looping until done

    decfsz pcntr,f ;decrement and test p_counter

    goto lp3 ;keep outside looping until done

    return

    This routine uses (3nm+4m+1)*p + (3p+1) + 4 machine cycles which reduces to 3nmp +

    4mp + 4p + 1.

    Often you will need a delay of a set time, say 0.5 seconds. Assuming the internal frequency is

    5 MHz, the required number of cycles is (F*t) = 2,500,000. Compute k, m and n values to

    give this timing.

    Engineering figure is .5sec/40ms = 12.5 outer loops. Oops, you can't take the easy way out of

    maxing the two inner loops. Do we write a linear programming algorithm or start random

    guessing numbers to get a close count?

    Use the comments button at the bottom of the page to request source code for the algorithm.

    Don't forget to mention the language you want source in (Java, JavaScript, Basic, C,

    PASCAL, FORTH, etc.)

  • 8/3/2019 Unit 2 new

    36/42

    I/O Expansion

    To cost-effectively expand the general I/O capability of standard products, a high number of

    low-cost I/O pins becomes a key requirement for many system-level designs. The low-cost,

    flexible I/O capability of MAX II devices is an ideal complement to todays I/O pin-

    constrained ASSPs and microcontrollers. Table 1 describes some of the MAX II device

    features that ease I/O expansion design challenges.

    Table 1. MAX II Application Solutions: I/O Expansion

    Features Benefits

    Lowest Cost per I/O Pin The MAX II devices cost per I/O pin is the lowest in the market.

    Second Time Fitting MAX II devices enable high-performance and flexible routing,

    even with locked pin assignments

    Flexible I/OBanks Multiple I/O banks support multiple I/O voltages. Programmable

    drive strength, Schmitt triggers, and an output enable (OE) per pin

    are all available on MAX II devices to satisfy a broad range of

    I/O requirements.

    Re-Programmability Provides flexibility to solve system-specific problems and

    supports last minute changes

    Figure 1 shows how a microcontroller with limited I/O capability can control many devices in

    a system by using only a two-wire serial bus. In this application example, the MAX II device

    interfaces to the serial bus input and then distributes instructions to control multiple devices

    (in this case, the fan motor controllers). The MAX II devices on-board user flash memory

    can store information, such as the frequency or the duty cycle of the motors.

    Data can also be converted from parallel to serial, such as taking information from the

    analog-to-digital converters (ADC) in parallel and communicating it to the microcontroller

    via the two-wire serial bus.

    Figure 1. Control Signal Distribution Using MAX II Devices

  • 8/3/2019 Unit 2 new

    37/42

    Note:

    UFM: User Flash Memory

    Many micro-processors are limited in I/O capability but need to distribute control signals to

    multiple devices around the system. Figure 2 shows how MAX II devices can control a large

    number of devices on the board with only a minimal number of inputs from the host

    processor, thereby reducing I/O overhead support on the processor.

    The MAX II devices, with the lowest cost per I/O pin, provide the best cost optimization for

    these I/O-intensive applications.

    Figure 2. Address Decoding Using MAX II Devices

    BAUD RATE:

    A microcontroller provides an asynchronous serial port with a serial clock derived from the

    processor clock. Although the serial clock cannot be exactly programmed to yield an ideal

  • 8/3/2019 Unit 2 new

    38/42

    frame length at a particular baud rate, an additional register is provided for tuning the frame

    length. Each transmitted asynchronous serial frame is stretched by a number of either serial

    clock phases or processor clocks defined in the tuning register. This provides for improved

    reception of the asynchronous data, because the frame length more nearly matches the ideal

    baud rate frame length.

    SERIAL PROGRAMMING

    1. serial program means for normally programming the microcontroller prior to use thereof,

    said serial program means includingserial interface control means adapted for serial

    communication among said microprocessor means, said data memory means, and devices

    peripheral to said microcontroller, and for serially programming the microcontroller when inend-use in the battery pack, said serial interface control means having a plurality of pins,

    and being adapted for such end-use programming by having at least some of its plurality of

    pins coupled to corresponding ones of said plurality of pins of the battery pack connector

    including first and second pins for respective first and second bi-directional inputs for

    transmitting and receiving signals to and from the microcontroller. and further including a

    third pin for energization to enable programming the microcontroller via said first and second

    bidirectional inputs while in said end-use, and precluding said serial communication when

    programming is taking place, and wherein said serial interface control means comprises an

    inter-integrated circuit (I2 C) interface and wherein said first and second bidirectional inputs

    are used for transmitting a serial data signal and a clock signal, respectively.

    2. serial program means for normally programming the microcontroller prior to use thereof,

    said serial program means including serial interface control means adapted for serial

    communication among said microprocessor means, said data memory means, and devices

    peripheral to said microcontroller, and for serially programming the microcontroller when in

    end-use in the battery pack, said serial interface control means having a plurality of pins, and

    being adapted for such end-use programming by having at least some of its plurality of pins

    coupled to corresponding ones of said plurality of pins of the battery pack connector

    including first and second pins for respective first and second bidirectional inputs for

    transmitting and receiving signals to and from the microcontroller, and further including third

    pin for energization to enable programming the microcontroller via said first and second

    bidirectional inputs while in said end-use, and precluding said serial communication when

  • 8/3/2019 Unit 2 new

    39/42

    programming is taking place, wherein said serial interface control means includes:

    status register means for indicating whether data is to be read from or written to the

    microcontroller; shift register means, coupled to said first and second bidirectional inputs, for

    shifting data into or out from the microcontroller; and

    buffer register means coupled to said shift register means for storing data that is read from or

    to be written to the microcontroller.

    3. A method for programming a microcontroller when installed in a battery pack for end-use

    in battery charging and battery monitoring applications, to permit the battery pack and said

    applications to be calibrated and customized according to specific battery technology used

    therein, prior to shipment to end-users thereof and while in end-use in said applications, the

    battery pack including a multi-pin connector for receiving a plurality of signals for use in

    programming the microcontroller, the microcontroller being fabricated on a semiconductor

    chip to execute programs and instructions and to generate control signals in response to such

    execution for selectively controlling a system external to the chip, the microcontroller

    including microprocessor means for executing instructions, program memory means for

    storing programs to be executed by the microcontroller, data memory means for storing data,

    and pin-outs for inputs and outputs provided in connection with the microcontroller functions

    including serial programming thereof and serial communication with devices peripheral to

    said microcontroller the method comprising the steps of:

    coupling a first pin of the battery pack connector to a first pin-out of the microcontroller for

    use in supplying a programming voltage signal to the microcontroller for enabling the

    microcontroller to be serially programmed while installed in the battery pack;

    coupling a second pin of the battery pack connector to a second pin-out of the microcontroller

    for use in supplying serial data signals to and from the microcontroller for use in serial

    communication between said microcontroller and internal devices and said peripheral deviceswhen no said programming voltage signal is supplied to the microcontroller, and for

    precluding said serial communication and supplying said microcontroller with programming

    data while the microcontroller is enabled for serial programming by application of said

    programming voltage signal; and coupling a third pin of the battery pack connector to a third

    pin-out of the microcontroller for use in supplying a clock signal to the microcontroller to

    clock said serial data signal into the microcontroller during both serial communication and

    serial programming of the microcontroller.

  • 8/3/2019 Unit 2 new

    40/42

    4. A method for programming a microcontroller when installed in a battery pack for end-use

    in battery charging and battery monitoring applications, to permit the battery pack and said

    applications to be calibrated and customized according to specific battery technology used

    therein, prior to shipment to end-users thereof and while in end-use in said applications the

    battery pack including a multi-pin connector for receiving a plurality of signals for use in

    programming the microcontroller, the microcontroller being fabricated on a semiconductor

    chip to execute programs and instructions and to generate control signals in response to such

    execution for selectively controlling a system external to the chip, the microcontroller

    including microprocessor means for executing instructions, program memory means for

    storing programs to be executed by the microcontroller, data memory means for storing data,

    and pin-outs for inputs and outputs provided in connection with the microcontroller functions

    including serial programming thereof and serial communication with devices peripheral to

    said microcontroller, the method comprising the steps of:

    coupling a first pin of the battery pack connector to a first pin-out of the microcontroller for

    use in supplying a programming voltage signal to the microcontroller for enabling the

    microcontroller to be serially programmed while installed in the battery pack; coupling a

    second pin of the battery pack connector to a second pin-out of the microcontroller for use in

    supplying serial data signals to and from the microcontroller for use in serial communication

    between said microcontroller and internal devices and said peripheral devices when no said

    programming voltage signal is supplied to the microcontroller, and for precluding said serial

    communication and supplying said microcontroller with programming data while the

    microcontroller is enabled for serial programming by application of said programming

    voltage signal; and coupling a third pin of the battery pack connector to a third pin-out of the

    microcontroller for use in supplying a clock signal to the microcontroller to clock said serial

    data signal into the microcontroller during both serial communication and serial

    programming of the microcontroller; further including the step of providing an interface

    circuit between the connector of the battery pack and the program memory of the

    microcontroller for said serial communication when said programming voltage signal is not

    supplied, and for receiving said serial data signal to be written to the microcontroller when

    said programming voltage signal is supplied.

    5. A system for controlling the charging and monitoring of a battery, the system incorporating

    a battery and a microcontroller in a battery pack, the battery pack including a multi-pin

    connector for receiving a plurality of signals, the microcontroller being fabricated on a

  • 8/3/2019 Unit 2 new

    41/42

    semiconductor chip to execute programs and instructions and to generate control signals in

    response to such execution for selectively controlling the charging and monitoring of the

    battery, the microcontroller including microprocessor means for executing instructions,

    program memory means for storing programs to be executed by the microcontroller and data

    memory means for storing data, the system further including:

    means coupled to the multi-pin connector of the battery pack for selectively enabling the

    microcontroller to enter into a serial programming mode; and

    serial interface control means for allowing the microcontroller to engage in serial

    communication when not in the serial programming mode, and to be serially programmed

    when in the serial programming mode, said serial interface control means having first and

    second bi-directional inputs and being adapted to allow the microcontroller to be serially

    programmed in end-use after installation in the battery pack by coupling of said bi-directional

    inputs to the battery pack multi-pin connector for use in supplying signals to the

    microcontroller via the connector and said inputs for programming the microcontroller when

    the microcontroller is in the serial programmingmode.

    6. A system for controlling the charging and monitoring of a battery, the system incorporating

    a battery and a microcontroller in a battery pack, the battery pack including a multi-pin

    connector for receiving a plurality of signals, the microcontroller being fabricated on a

    semiconductor chip to execute programs and instructions and to generate control signals in

    response to such execution for selectively controlling the charging and monitoring of the

    battery, the microcontroller including microprocessor means for executing instructions,

    program memory means for storing programs to be executed by the microcontroller and data

    memory means for storing data, the system further including:

    means coupled to the multi-pin connector of the battery pack for selectively enabling the

    microcontroller to enter into a serial programming mode; and

    serial interface control means for allowing the microcontroller to engage in serial

    communication when not in the serial programming mode, and to be serially programmed

    when in the serial programming mode, said serial interface control means having first and

    second bi-directional inputs and being adapted to allow the microcontroller to be serially

    programmed in end-use after installation in the battery pack by coupling of said bi-directional

    inputs to the battery pack multi-pin connector for use in supplying signals to the

    microcontroller via the connector and said inputs for programming the microcontroller when

    the microcontroller is in the serial programming mode, wherein said serial interface control

  • 8/3/2019 Unit 2 new

    42/42

    means comprises an inter integrated circuit (I2 C) interface and wherein said first and second

    bi-directional signals are a serial data signal and a clock signal, respectively, normally used

    for said serial communication, but alternatively usable for said serial programming of the

    microcontroller when in the serial programming mode after installation in the battery pack.

    7. A system for controlling the charging and monitoring of a battery, the system incorporating

    a battery and a microcontroller in a battery pack, the battery pack including a multi-pin

    connector for receiving a plurality of signals, the microcontroller being fabricated on a

    semiconductor chip to execute programs and instructions and to generate control signals in

    response to such execution for selectively controlling the charging and monitoring of the

    battery, the microcontroller including microprocessor means for executing instructions,

    program memory means for storing programs to be executed by the microcontroller and data

    memory means for storing the data have to include the following: means coupled to the

    multi-pin connector of the battery pack for selectively enabling the microcontroller to enter

    into a serial programming mode; and serial interface control means for allowing the

    microcontroller to engage in serial communication when not in the serial programming

    mode, and to be serially programmed when in the serial programming mode, said serial

    interface control means having first and second bi-directional inputs and being adapted to

    allow the microcontroller to be serially programmed in end-use after installation in the

    battery pack by coupling of said bi-directional inputs to the battery pack multi-pin connector

    for use in supplying signals to the microcontroller via the connector and said inputs for

    programming the microcontroller when the microcontroller is in the serial programming

    mode,