slide04-1

download slide04-1

of 101

description

slide

Transcript of slide04-1

  • 1Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PIC

    Microcontroller

  • 2Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PICMicrocontroller(MCU)Widely used device from Microchip Technology

    Sold > 10 billion PIC controllersSeveral device families

    Many devices per familyCommon development environment

    Widely availableLarge user baseExtensive application notes

    Low costFree / low cost development tools

    Basic architectural featuresPipelined RISC microprocessor coreAccumulator execution modelData width 8 / 16 / 32 bitsInstruction width 12 / 14 / 16 / 32 bits

  • 3Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PICFamilies

    Data width8 / 16/ 32 bitsWider integer higher precision arithmetic

    Instruction width12 / 14 / 16 / 32 bitsWider instruction more complex instructions + higher precision arithmetic

    IntegratedDSP

    dsPIC30

    PIC24

    PIC18

    PIC10/PIC12/PIC16

    Family

    14bitsMidRange

    16bits

    32bits32bits32bitMCU

    16bits16bits16bitMCU

    12bits

    8bits

    Baseline

    8bitMCU

    InstructionWidth

    DataWidth

    Architecture

  • 4Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    TypicalApplicationsBaseline

    Replace discrete logic functions Gates, simple state machines, encoders/decoders, etc.

    Disposable electronics Drug / pregnancy testers, dialysis monitor, etc

    Mid-RangeDigital sensors, displays, controllers, telecom equipmentGlucose / blood pressure set

    PIC18 Integration with peripherals + networks

    USB, Ethernet, MCU-to-MCU, etc

    Higher level analog peripherals, industrial control, major appliancesPIC24 / dsPIC30

    16-bit ALU with integrated DSPPortable EGK

    PIC32General purpose RISC microprocessor + controller

    MRI

  • 5Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    LearningPICArchitecture

    Variety Hundreds of PIC devices in 3 families and several sub-families

    Updates Microchip Technology upgrades devices frequentlyFamiliar devices replaced with new model

    Instruction Set Architecture 8 and 16 bit devices share approximately uniform instruction setPIC32 implements MIPS ISA

    CaveatsCourse takes general pedagogical approach to PIC as typical MCU

    Focus on 8-bit devices Mid-Range + PIC18

    Many books + websites on PIC with general-sounding titlesEach device is uniqueFew statements are precisely true about each device

    Somegeneralobservations

  • 6Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    8BitPICMCUs

    8bitparallelports

    Synchronous/asynchronousserialports

    Timers+watchdogtimer

    A/D+D/Aconverters

    Pulsewidthmodulators

    I/Odevices

    Stores0(nostack)to31instructionaddresses

    Usedforfunctioncalls

    Stack

    PipelinedRISC

    33to77instructions

    Architecture

    Addressableunit=instructionword=12/14/16bits

    Smallest:2Kword (3KBof12bitinstructions)

    Largest:64Kword (128KBof16bitinstructions)

    Programmemory

    Organizedas8bitregisters

    SomedevicesalsostoredataonEEPROM

    16Bto4KB

    Datamemory

  • 7Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    8BitPICOperationModelALU sources

    Special WORKING register W Data register or immediate

    ALU destination Data register or W

    Transfer operations Data register W

    Status registerFlags produced by ALU operations

    ArithmeticLogicUnit(ALU)

    DataMemory

    Status

    DataBus

    W

  • 8Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PipelineOperation

    Branchinstructionsrequire2instructioncycles

    InstructionFetch

    InstructionMemory

    ExecuteDecode

    DataMemory

    Address Instruction Address Data

    W

    1 2 3 4 5I1 fetch execute I2 fetch execute I3 fetch execute I4 fetch execute

    InstructionCycles

    Instructioncycles(CY)

  • 9Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PipelineOperation

    Instruction Cycle4 cycles of external clock (oscillator)CY = Q1 Q2 Q3 Q4

    Instruction fetch

    Execution

    1 2 3 4 5 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4I1 fetch execute I2 fetch execute I3 fetch execute I4 fetch execute

    Instruction Cycles

    Clockcycles(OSC)

    Q2 Q3

    IR [PC]FetchQ4

    PC PC + 1UpdateProgramPointerQ1

    OperationdependentDecodeandExecuteQ1 Q4

    IR instructionregisterPC programcounter

  • 10Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ClockTypesRC oscillator

    Least expensive Can be used for non-critical frequency accuracy and stability Some devices have internal RC oscillator at 4 MHz

    Crystal oscillatorMost stable

    External clockProvided by external digital system

    Specific modes LP mode frequencies between 32 kHz and 200 kHzXT mode frequencies between 100 kHz and 4 MHzHS mode frequencies between 8 MHz and 20 MHz

  • 11Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SleepModeLow-power mode

    Main oscillator stoppedMost MCU functions stoppedWatchdog time continuesPower consumed < 1 mA for some models

    Instruction SLEEP MCU sleep modeData register values stable

    Pipeline lockedSleep instruction executes next instruction already fetched

    On wake upNext instruction executes Recommendation instruction after sleep = NOPWatchdog timer counter reset

  • 12Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    WakeUpEventsReset

    Fetch instruction from address 0

    Watchdog timer overflowNormal execution of instruction following sleep

    Interrupt Interrupt not enabled ignore interruptEnabledNormal execution of instruction following sleepPC jumps to address 4 in program memory Finds interrupt routine

  • 13Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    WatchdogTimerWDT oscillator (clock)

    Independent from main clockContinues in low power modeMay be disabled

    WDT timeout Timeout = 18 msNon-sleep mode

    MCU resets

    Sleep modeMCU wakes up executes instruction following sleep

    Reset WDTCLRWDT resets timeout = 18 ms

    PrescalerDivide time-base by 2k, k = 0, ... , 7Extend timeout up to 2300 ms

  • 14Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SomeTypical8bitPICDeviceFamilies

    FlashFlashFlashFlashFlashROM

    16 704 5412 3264I/Opins

    31levels8levels2levels2levels2levelsStack

    $1.20 $8.50$0.35 $2.50$0.50 $0.85$0.50$0.35Bulkprice

    2 52 3111Timers

    18 1006 6414 4086Pins

    int /extint/ext000Interrupts

    256 4K56 36825 13425 4116 24Datamemory

    (bytes)

    2 Kwords 64 Kwords

    256 8192words

    1024 2048words

    512 1024words

    256 512words

    Programmemory

    8335333333Instructions

    16bits14bits12bits12bits12bitsInstruction

    word

    PIC10F3xxPIC12F6xxPIC16F6xx

    PIC18F5xxPIC16F5xxPIC12F5xxPIC10F2xx

  • 15Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    TypicalBaselineMCUPIC16X5xxFamily

    12bitinstruction

    GeneralI/Oports

    8bitdata

    timer

    W+ALU

  • 16Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    TypicalMidRangeMCU PIC16F873

    14bitinstruction

    GeneralI/OportsExternalInterrupt

    8bitdata

    TimersA/DUARTCompareCapturePulsewidth (CCP)SynchronousSerialPort(SSP)

  • 17Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    TypicalPIC18MCU

    16bitinstruction

    8bitdata

    GeneralI/OportsExternalInterrupts

    TimersA/DUARTUSBCompareCapturePulsewidth (CCP)ControllerAreaNetwork(CAN)

  • 18Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    MidRangePICMCUs

  • 19Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    DataMemory/RegistersRegister

    Addressable location in data memory 8-bit word (byte)

    Data address space9 bit address memory 29 = 512 bytes = 0.5 KB

    Memory partitioned into banksBank = 27 = 128 = 80h registers (1/8 KB)7 bit file address

    Displacement in bank = 00h 7Fh

    Banks in address space 29-7 = 4 banks2 to 4 banks implemented in deviceUnimplemented banks

    Read as 0Write as NOP

    7bits2bits

    fileaddressbank

    dataaddress

    bank

    11100100

    00h

    7Fh

  • 20Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    Special/GeneralRegistersGPR

    General Purpose RegistersUser program data

    SFRSpecial Function Registers Reserved for

    Control / configurationPeripheral access Indirect addressingProgram counter

    Core SFRs Appear in every bank at

    same file address

    Typical SFRs

    AccesstoEEPROMandFlashmemory

    EEADRH,EEDATA,

    AccesstoA/DconverterADRESH,ADRESL,ADCON0,

    AccesstoserialportTXREG,TXSTA,RCREG,RCSTA,

    Timer0TMR0,OPTION,INTCON,

    AccesstoparallelportsPORTA,TRISA,

    Componentsofinterrupthandling

    INTCON,PIR1,PIE1,PIR2,PIE2

    FileSelectforindirectdataaddressing

    FSR

    Componentsofprogramcounter(PC)

    PCLATHPCL

    TimeroptionsOPTION

    Statusword+flagsSTATUS

  • 21Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    DataMemoryMapNotes

    (2,3)Notalllocationsimplementedonalldevices

    (4)CommonRAMaccessibleinallbanks(onapplicabledevices)

    (5)Notimplementedonsmallerdevices

  • 22Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    StatusRegister

    xxx11000Resetvalue

    Writable

    Name

    R/WR/WR/WROROR/WR/WR/W

    CDCZPD#T0#RP0RP1IRP01234567

    DirectRegisterPointerRP1, RP0IndirectRegisterPointer

    BankSelectIRP

    C 1 oncarry(Addition)C 0 onborrow(Subtraction)

    DC 1 oncarry(Addition)DC 0 onborrow(Subtraction)

    Z 1 onALUzeroZ 0 onnonzero

    PD# 0 onSLEEPPD# 1 onCLRWDTandpoweronreset

    TO# 0 onWDToverflowTO# 1 onpoweronreset,CLRWDT,SLEEP

    CarryoutC

    Halfbytecarry(bits3,4)

    DC

    ZeroflagZ

    LowpowerPD#

    StateofWDTTO#

    CoreSFRaccessibleatfileaddress03h ineverybank

  • 23Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    AddressingDataMemory

    Direct addressing Program specifies data addressBank selection

    STATUS bits RP1 and RP0On reset

    RP1 = RP0 = 0 bank 0 selectedBank switching

    Write to STATUSFile Address

    Literal field in instruction

    RP0 7bitsfrominstructionRP1

    fileaddressbank

    012345678

    ConcatenationofA andB(A bitsfollowedbyB bits)A.BBitsa tob inregisterREGREGBitb inregisterREGREGNotation

  • 24Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    AddressingDataMemoryIndirect addressing

    Program writes to Special Function Registers (SFRs)Address formed from SFRs

    Instructions can increment/decrement SFR valuesSimilar to pointer arithmetic

    File Select Register (FSR )Core SFR accessible at file address 08h in all banksFile Address

    FSRBank

    IRP.FSRSTATUS bit IRP (Indirect Register Pointer)

    On small devices1 or 2 banks = 128 or 256 bytes of data memory8 bit FSR address covers 2 banksIRP not implemented (read 0 / write = NOP)

    8bitsofFSRIRP

    fileaddressbank

    012345678

  • 25Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    INDFRegisterINDF

    Core SFR accessible at file address 00h in all banksVirtual pointer not physical registerTracks contents of FSRSimplifies pointer arithmetic

    Example In register file,

    [05] = 10h[06] = 0Ah

    Load FSR 05 ; FSR points to file address 05[INDF] = 10h ; INDF points to file address 05FSR++ ; increment FSR FSR = 06[INDF] = 0Ah ; INDF points to file address 06

  • 26Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionMemorySpace

    Instruction addressn bit location addressLocation = instruction 2n instructionsInstruction width

    12 / 14 / 16 bits

    PagePartition of instruction

    memory space2k instructions / pagek bit offset

    instruction 11 111 Page

    instruction 11 000

    instruction 01 111

    instruction 01 011instruction 01 010instruction 01 001

    Page1

    instruction 01 000instruction 00 111

    instruction 00 011instruction 00 010instruction 00 001

    Page0

    instruction 00 000 page offset

    MemoryLocation Address

    k bitsn k bitsoffsetpage

    n bitaddress

    All8bitMCUs

  • 27Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionMemorySpaceMid-Range instruction memory

    14-bit instruction wordn = 13

    213 = 8192 instruction wordsk = 11

    Page = 211 = 2048 = 800h words

    Program counter (PC)PC = page number 4 pagesPC = offset

    Reserved addressesAddress 0h

    Reset vector pointer to reset routine Address 4h

    Interrupt vector pointer to interrupt service routine

    11 bits2 bitsoffsetpage

    13 bitPC

    0101112

  • 28Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PCAccessPC register details

    PC low (PCL) = PCAccessible by instruction reads/writes

    PC high (PCH) = PCNot directly accessible to instructions

    PC latch high (PCLATH) Core SFR accessible at file address 0Ah in all banks PCH = PC = PCLATHPCLATH not implemented

    PC 0123456789101112

    offsetpage

    PCLPCH

    PCLATH01234

  • 29Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PCUpdatesReset

    PC 0Non-branch instruction

    PC PC + 1Branch types

    Direct branchGOTO instruction PCH PCLATHOffset = PC literal from instruction

    Indirect branchComputed GOTOWrite to PCL as registerCopies PCL ALU resultForces PCH PCLATH

    PC 0123456789101112

    offsetpage

    PCLPCH

    PCLATH01234

    012345678910literal

    PC 0123456789101112

    PCLATH01234

    PC 0123456789101112

    PCL ALUPCH

    PCLATH01234

  • 30Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    Call/ReturnStack

    8 level FILO bufferHolds 13 bit instruction addresses on CALL/RETURN

    Function entryCALL instruction

    STACK PC PCL literal from instructionPCH PCLATH

    Function exitRETURN instruction

    PC STACKPCLATH not updated

    May be different from PCH after RETURN

    012345678910literal

    PC 0123456789101112

    PCLATH01234

    STACKCALL

    RETURN

  • 31Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionFormat

    CALL / GOTOk = 11 bit literal (immediate)

    General literalk = 8 bit literal (immediate)

    Bit orientedb = bit position in registerf = 7 bit file address

    Byte orientedd = 0 destination = Wd = 1 destination = ff = 7 bit file address

    011 1013kopcode

    08 713kopcode

    7 010 6913fbopcode

    08 6713fdopcode

  • 32Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionSetDatatransfer

    Clear WClear f

    Move literal to WMove W to f

    d = f

    d = WMove f to d

    Comment

    ZW 0CLRW Zf 0CLRF f W kMOVLW k f WMOVWF f

    Zf fMOVF f, 1MOVF f, fMOVF f

    ZW fMOVF f, 0 MOVF f, W

    Zd fMOVF f, d FlagsOperationMnemonic

    destination= W , d =0f , d = 1

    Operands

    literalkdestinationdname / address of registerf

  • 33Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionSetArithmeticandLogic 1

    ZAnd k with WW k and WANDLW kAnd w with fDec f to dInc f to dSub W from kSub W from fAdd k to WAdd w to fComment

    Zd f and WANDWF f, d Zd f 1DECF f, d Zd f + 1INCF f, d

    C, DC, ZW k WSUBLW k C, DC, Zd f WSUBWF f, d C, DC, ZW k + WADDLW k C, DC, Zd f + WADDWF f, d

    FlagsOperationMnemonic

    destination= W , d =0f , d = 1

    Operands

    literalkdestinationdname / address of registerf

  • 34Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionSetArithmeticandLogic 2

    nibble swap(nibble=halfbyte)

    d fL fHSWAPF f, d

    compliment f to d

    XOR W with kXOR W with fOR k with WOR w with f

    Comment

    Cd #f (not f)COMF f, d Cd right rotate f,CRRF f, d Cd left rotate f,CRLF f, d ZW k xor WXORLW k Zd f xor WXORWF f, d ZW k or WIORLW k Zd f or WIORWF f, d

    FlagsOperationMnemonic

    destination= W , d =0f , d = 1

    Operands

    literalkdestinationdname / address of registerf

  • 35Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionSetControl

    return from subroutine with k in WRETLW kinterrupt returnRETFIE subroutine returnRETURN

    call subroutine in address aCALL a d f - 1, skip one if result = 0DECFSZ f, d d f + 1, skip one if result = 0INCFSZ f, d skip one instruction if f = 1BTFSS f, b skip one instruction if f = 0BTFSC f, b

    branch to addressGOTO a OperationMnemonic

    bit location11 bit address

    ba

    Operands

    literalkdestinationdname / address of registerf

  • 36Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InstructionSetOther

    TO#, PD#TO#, PD#

    Flags

    go to low power consumptionSLEEP WDT 0CLRWDT

    no operation NOPf 1 BSF f, b f 0 BCF f, b OperationMnemonic

    Operands

    bit locationbname / address of registerf

  • 37Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    CLRF STATUS ; STATUS 0MOVLW 0x20 ; W 1st address in GPR bank 0MOVWF FSR ; Indirect address register W

    Bank0_LPCLRF INDF0 ; address in GPR 0INCF FSR ; FSR++ (next GPR address)BTFSS FSR, 7 ; skip if (FSR == 1) FSR = 80hGOTO Bank0_LP ; continue

    ; ** IF DEVICE HAS BANK1 **MOVLW 0xA0 ; W 1st address in GPR bank 1MOVWF FSR ; Indirect address register W

    Bank1_LPCLRF INDF0 ; address in GPR 0INCF FSR ; FSR++ (next GPR address)BTFSS STATUS, C ; skip if (STATUS == 1) FSR = 00hGOTO Bank1_LP ; continue

    SampleProgramFragmentsRAMInitialization

  • 38Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SampleProgramFragments

    Prog:movlw HIGH Prog10 ; W Prog10

    ; operator HIGH reads bits of pointermovwf PCLATH ; PCLATH Wgoto Prog10 ; PC Prog10

    ; PC PCLATH

    Prog10:;; Prog10 labels some address in program memory;

    Branchtoaddressinnewpage

  • 39Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SampleProgramFragments

    movlw HIGH Prog20 ; W Prog10movwf PCLATH ; PCLATH Wmovlw LOW Prog20 ; W Prog10movwf PCL ; PCL Prog10

    ; PCH PCLATH Prog20:;; Prog10 labels some address in program memory;

    Computedgoto

  • 40Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SampleProgramsFragments

    btfss f,b ; skip one instruction if; bit b in register f = 1

    goto Action2Action1:; instructions for Action1goto Action3Action2:; instructions for Action2Action3:; instructions for Action3

    ifelsebranch

  • 41Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SampleProgramsFragments

    movlw times ; W timesmovwf COUNTER ; COUNTER W (times)

    Loop:;; loop instructions;decfsz COUNTER, f ; COUNTER--

    ; COUNTER = 0 skip nextinstruction

    goto Loop ; next iterationEnd:;;

    Staticloop

  • 42Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SampleProgramsFragments

    ; Function call returns data at Table.INDEXmovlw HIGH Table ; W Tablemovwf PCLATH ; PCLATH Wmovf INDEX, W ; W INDEXcall Table ; Call to subroutine table;Table:addwf PCL, f ; PCL PCL + W = PCL + INDEX

    ; computed gotoretlw 'A' ; return with W 'A' retlw 'B'retlw 'C'retlw 'D'retlw 'E'

    Datatableininstructionmemory

  • 43Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PICMCUandtheOutsideWorldOscillator

    Generates device clockFour device clock periods per instruction cycle

    PortsData I/O pins

    Electrical connections to external circuits

    Configured to function as Digital I/O Analog inputs to A/D converter

    Peripheral ModulesShare data pins with general ports

    Samples analog level converts to digital representationA/D

    Capture/Compare/PWM (Pulse Width Modulation)CCPBit-parallel bit-serial converter for communicationsSamples 2 analog levels outputs bit (A1 > A2)

    Counts clock cycles interrupt on preset count

    USART

    Comparator

    Timer

    PICOSC

    Ports

    Controls

    ControlsDevicedependentPower+groundInterrupt(INT)Externalclock

  • 44Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ConfigurableOscillatorModesQuartz crystal time base

    Crystal connected between PIC pins OSC1 and OSC2Vibrates in electric field piezoelectric resonance in voltageModes

    LP Low Frequency / Low Power Crystal 32 kHz to 200 kHzXT Crystal/Resonator 100 kHz to 4 MHzHS High Speed Crystal/Resonator 8 MHz to 20 MHz

    Resistor/Capacitor time baseCapacitor discharges through resistor in time = 2RCOscillator frequency f = 1 / (2RC)Modes

    EXTRC External RC connected between PIC pin OSC1 and groundINTRC Internal 4 MHz RCCLKOUT

    EXTRC or INTRC with instruction clock (= f/4) output on OSC2

  • 45Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InterruptsInterrupt

    Instruction at current PC executes Instruction at current PC+1 fetchedStack PC+2PC interrupt pointerOn return from interrupt PC stack

    Interrupt sourcesExternal interrupt pin

    Pin RB0 on some PIC devices (separate pin on other devices)

    Peripheral modulesGeneral internal interruptA/DTimerComparatorUSARTCCP

  • 46Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InterruptControlRegisterInterrupt Control Register (INTCON)

    01234567RBIFINTFT0IFRBIEINTET0IEPEIEGIE

    1=AtleastoneofRB7:RB4pinschangedstate0=NoneofRB7:RB4pinshavechangedstate

    1=INTexternalinterruptoccurred0=INTexternalinterruptdidnotoccur

    1=TMR0registerhasoverflowed0=TMR0registerdidnotoverflow

    1=EnablesRBportchangeinterrupt0=DisablesRBportchangeinterrupt

    1=EnablesINTexternalinterrupt0=DisablesINTexternalinterrupt

    1=EnablesTMR0overflowinterrupt0=DisablesTMR0overflowinterrupt

    1=Enablesallunmaskedperipheralinterrupts0=Disablesallperipheralinterrupts

    1=Enablesallunmaskedinterrupts0=Disablesallinterrupts

    RBPortChangeInterruptFlagRBIF

    ExternalInterruptFlagINTF

    OverflowInterruptFlagT0IF

    RBPortChangeInterruptEnableRBIE

    ExternalInterruptEnableINTE

    OverflowInterruptEnableT0IE

    PeripheralInterruptEnablePEIE

    GlobalInterruptEnableGIE

  • 47Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PeripheralInterruptEnable(PIE)Number of PIE registers device dependent

    ComparatorCMIELCDLCDIEEEWriteCompleteEEIEParallelSlavePortRead/WritePSPIESlopeA/DTMROverflowOVFIESlopeA/DConverterComparatorTripADCIEA/DConverterADIEUSARTTransmitTXIEUSARTReceiveRCIESynchronousSerialPortSSPIECCP2CCP2IECCP1CCP1IETMR2toPR2MatchTMR2IETMR1OverflowTMR1IE

    1=enabledeviceinterrupt0=disabledeviceinterrupt

  • 48Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PeripheralInterruptRegister(PIR) 1Number of PIR registers device dependent

    1=Transmission/receptioncomplete

    0=Waitingtotransmit/receive

    SSPIE

    1=USARTreceivebufferRCREG full0=USARTreceivebufferisempty

    RCIE

    SameasCCP1IECCP2IE

    CCP1InterruptFlagbit

    CaptureMode1=TMR1 registercaptureoccurred0=NoTMR1 registercaptureoccurredCompareMode1=ATMR1 registercomparematchoccurred0=NoTMR1 registercomparematchoccurredPWMMode

    Unusedinthismode

    CCP1IESameasTMR1IETMR2IE

    1=TMR1 registeroverflowed0=TMR1 registerdidnotoverflow

    TMR1IE

  • 49Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PeripheralInterruptRegister(PIR) 2Number of PIR registers device dependent

    1=Comparatorinputchanged

    0=Comparatorinputnotchanged

    CMIE

    1=LCDinterruptoccurred

    0=LCDinterruptdidnotoccur

    LCDIE

    1=DataEEPROMwriteoperationcomplete

    0=DataEEPROMwriteoperationnotcomplete

    EEIE

    1=Readorwriteoperationoccurred

    0=Readorwritedidnotoccur

    PSPIE

    1=SlopeA/DTMRoverflow

    0=SlopeA/DTMRdidnotoverflow

    OVFIE

    1=A/Dconversioncomplete

    0=A/Dconversionnotcomplete

    ADCIE

    1=A/Dconversioncomplete

    0=A/Dconversionnotcomplete

    ADIE

    1=USARTtransmitbufferTXREGempty

    0=USARTtransmitbufferisfull

    TXIE

  • 50Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InterruptLatencyOn interrupt

    1. Current instruction execution completes 2. Current instruction fetch completes 3. PC interrupt pointerLatency ~ 3 to 4 instruction cycles

    1 2 3

  • 51Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InterruptInitialization+EnablingPIE1_MASK1 EQU B01101010 ; Interrupt Enable

    ; Register mask (device; dependent)

    ;;CLRF STATUS ; Bank0CLRF INTCON ; Disable interrupts during

    ; configurationCLRF PIR1 ; Clear flagsBSF STATUS, RP0 ; Bank1MOVLW PIE1_MASK1 ; set PIE1 via WMOVWF PIE1BCF STATUS, RP0 ; Bank0BSF INTCON, GIE ; Enable Interrupts

  • 52Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    MacrosforRegisterSave/RestorePUSH_MACRO MACRO ; Save register contentsMOVWF W_TEMP ; Temporary register WSWAPF STATUS,W ; W swap STATUS nibblesMOVWF STATUS_TEMP ; Temporary register STATUS

    ENDM ; End this Macro

    POP_MACRO MACRO ; Restore register contentsSWAPF STATUS_TEMP,W ; W swap STATUSMOVWF STATUS ; STATUS WSWAPF W_TEMP,F ; W_Temp swap W_TempSWAPF W_TEMP,W ; W swap W_Temp s

    ; no affect on STATUSENDM ; End this Macro

  • 53Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    TypicalInterruptServiceRoutine(ISR) 1org ISR_ADDR ; store at ISR addressPUSH_MACRO ; save context registers W, STATUSCLRF STATUS ; Bank0

    ; switch implementation in PIC assembly languageBTFSC PIR1, TMR1IF ; skip next if (PIR1 == 1)GOTO T1_INT ; go to Timer1 ISRBTFSC PIR1, ADIF ; skip next if (PIR1 == 1)GOTO AD_INT ; go to A/D ISRBTFSC PIR1, LCDIF ; skip next if (PIR1 == 1)GOTO LCD_INT ; go to LCD ISRBTFSC INTCON, RBIF ; skip next if (PIR1 == 1)GOTO PORTB_INT ; go to PortB ISRGOTO INT_ERROR_LP1 ; default ISR

  • 54Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    TypicalInterruptServiceRoutine(ISR) 2T1_INT ; Timer1 overflow routine

    :BCF PIR1, TMR1IF ; Clear Timer1 overflow interrupt flagGOTO END_ISR ; Leave ISR

    AD_INT ; Routine when A/D completes:BCF PIR1, ADIF ; Clear A/D interrupt flagGOTO END_ISR ; Leave ISR

    LCD_INT ; LCD Frame routine: BCF PIR1, LCDIF ; Clear LCD interrupt flagGOTO END_ISR ; Leave ISR

    PORTB_INT ; PortB change routine:

    END_ISR ; Leave ISRPOP_MACRO ; Restore registersRETFIE ; Return and enable interrupts

  • 55Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    TimersWatchdog timer (WDT)

    Normal program resets timer before timeout (18 ms)Timeout

    Non-sleep mode MCU resetsSleep mode MCU wakes up executes instruction following sleep

    Configured in OPTION_REG SFRTimer0

    Generic programmable 8-bit timer/counterShares prescaler (divide by 2k, k = 0,...,8) with WDTConfigured in OPTION_REG SFR

    Timer1Generic programmable 16-bit timer/counter Read / write two 8-bit registers

    Timer2Generic programmable 8-bit timer/counterTime base for PWM mode

  • 56Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    WatchdogTimer(WDT)Time base

    Internal RC oscillator Timer0 clock source

  • 57Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    OPTION_REGSFR(FileAddress081h)

    01234567PS0PS1PS2PSAT0SET0CSINTEDGRBPU

    1=PrescalerisassignedtotheWDT (watchdog)0=PrescalerisassignedtotheTimer0module

    1=IncrementonhightolowtransitiononT0CKIpin

    0=IncrementonlowtohightransitiononT0CKIpin

    1=TransitiononT0CKIpin

    0=Internalinstructioncycleclock(CLKOUT)

    1=InterruptonrisingedgeofINTpin

    0=InterruptonfallingedgeofINTpin

    1=Weakpullupsaredisabled

    0=Weakpullupsareenabledbyportlatchvalues

    Underline active=0/inactive=1

    PrescalerRateSelectPS2:PS0

    PrescalerAssignmentPSA

    TMR0SourceEdgeSelectT0SE

    TMR0ClockSourceSelectT0CS

    InterruptEdgeSelectINTEDG

    WeakPullupEnableRBPU

    WDT1:1

    1:2

    1:4

    1:8

    TMR01:2

    1:4

    1:8

    1:16

    PS2:PS0 000

    001

    010

    011

    WDT1:16

    1:32

    1:64

    1:128

    TMR01:32

    1:64

    1:1281:256

    PS2:PS0 100

    101

    110111

  • 58Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    Timer08-bit timer/counter

    Readable / writable at TMR0 SFR (File Address 081h)8-bit software programmable prescaler

    Divide input pulse train (slows time scale)Scale by 1:1 , 1:2, 1:4, ... , 1:128

    Selectable clock source External / internal

    Interrupt on overflow FFh 00hEdge select (phase synchronization with external clock)

  • 59Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    Timer0OperationTimer mode

    T0CS = 0TMR0++ on every instruction cycle (without prescaler)Write to TMR0 register no increment for two instruction cycles

    Counter mode T0CS = 1TMR0++ on every rising or falling edge of T0CKI (external clock)

    Edge determined by T0SE bitPrescaler

    Set by PSA control bitsTMR0 Interrupt

    Generated on overflow FFh 00hSets bit T0IF (INTCON)Timer0 interrupt service routine

    Clear T0IF Re-enable interrupt

  • 60Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InitializeTimer0withInternalClockSourceCLRF TMR0 ; Clear Timer0 registerCLRF INTCON ; Disable interrupts and clear T0IFBSF STATUS, RP0 ; Bank1MOVLW 0xC3 ; Disable PortB pull-ups

    ; C3 = 11000011MOVWF OPTION_REG ; Interrupt on rising edge of RB0

    ; Timer0 increment from internal clock; Prescale = 1:16.

    BCF STATUS, RP0 ; Bank0T0_OVFL_WAITBTFSS INTCON, T0IF ; poll overflow bitGOTO T0_OVFL_WAIT ; on timer overflow

  • 61Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    Timer116-bit timer/counter

    TMR1 pair TMR1H:TMR1LReadable and writable 8-bit registers

    Counter 0000h to FFFFh with rollover to 0000hGenerate Timer1 interrupt on rollover (if enabled)

    ModesSynchronous timer

    TMR1++ on every instruction cycle (FOSC / 4)Asynchronous counter

    TMR1++ on rising edge of input pinSynchronous counter

    TMR1++ on rising edge of sampled input pinSynchronized to internal clock TOSC

    Sample input pin on rising edge of TOSCInput must be high / low for at least 2TOSC

    Input

    SampleClock

    SampledInput

  • 62Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    T1CONSFR

    01234567TMR1ONTMR1CST1SYNCT1OSCENT1CKPS0T1CKPS1

    01=1:2Prescalevalue

    00=1:1Prescalevalue

    1=EnablesTimer1

    0=StopsTimer1

    1=CounterMode(countexternalclock)

    0=TimerMode(countinternalclockFOSC /4)

    TMR1CS = 1 (CounterMode)1=AsynchronousCounterMode

    0=SynchronousCounterMode

    TMR1CS = 0 (TimerMode)Ignored

    1=Oscillatormodeenabled

    0=Oscillatormodedisabled

    11=1:8Prescalevalue

    10=1:4Prescalevalue

    Timer1OnTMR1ON

    Timer1ClockSourceSelect

    TMR1CS

    Timer1ExternalClockInputSynchronizationSelect

    T1SYNC

    Timer1OscillatorEnableT1OSCEN

    Timer1InputClockPrescaleSelect

    T1CKPS1T1CKPS0

  • 63Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    Timer1Operation

    TimerMode

    CounterMode

    OscillatorMode T1CKI T1OSI

    Sampling

    CLKIn/OSCout

    AsyncInput

  • 64Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ReadingTimer1; All interrupts disabled

    MOVF TMR1H, W ; W high byteMOVWF TMPH ; TMPH WMOVF TMR1L, W ; W low byteMOVWF TMPL ; TMPL W

    ; TMR1L can roll-over between reads of high and low bytesMOVF TMR1H, W ; W high byte againSUBWF TMPH, W ; Verify high byteBTFSC STATUS,Z ; bad read (Z = 0 not equal) re-doGOTO CONTINUE

    ; New reading good value.MOVF TMR1H, W ; W high byteMOVWF TMPH ; TMPH WMOVF TMR1L, W ; W low byteMOVWF TMPL ; TMPL W; Re-enable interrupts (if required)

    CONTINUE; Continue

  • 65Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    WritingTimer1

    ; All interrupts are disabledCLRF TMR1L ; Clear Low byte

    ; Prevents rollover to TMR1HMOVLW HI_BYTE ; W HI_BYTEMOVWF TMR1H, F ; TMR1H WMOVLW LO_BYTE ; W LO_BYTEMOVWF TMR1L, F ; TMR1L W

    ; Re-enable interrupts (if required)CONTINUE; Continue

  • 66Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    Timer2Readable / writable 8-bit timer

    PrescalerPeriod register PR2

    Readable / writable TMR2 = PR2 reset (TMR2 0)

    Postscaler Counts TMR2 = PR2 resets Triggers TMR2IF interrupt flag

  • 67Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    T2CONSFR

    01234567T2CKPS0T2CKPS1TMR2ONTOUTPS0TOUTPS1TOUTPS2TOUTPS3

    00=Prescaleris1

    01=Prescaleris4

    1x=Prescaleris16

    1=Timer2ison

    0=Timer2isoff

    0000=1:1Postscale

    0001=1:2Postscale

    0010=1:3Postscale

    0011=1:4Postscale

    :

    1111=1:16Postscale

    Timer2ClockPrescaleSelect

    T2CKPS1:0

    Timer2OnTMR2ON

    Timer2OutputPostscale Select

    TOUTPS3:0

  • 68Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PortsI/O pins

    Electrical connections to external circuits

    Configurable in SFR ADCON1 as Digital I/O Analog inputs to A/D converter

    Mid-Range PIC configurationsMinimal Port A (6 pins) + Port B (8 pins)Maximal Port A (6 pins), Port B (8 pins), ... , Port G (8 pins)

    Special Function RegistersData

    PORTA , ... , PORTGPORTi = data bit on pin x of port i

    DirectionTRISA, ... , TRISGTRISi = 1 pin x of port i is Input TRISi = 0 pin x of port i is Output

    PICOSC

    Ports

    Controls

  • 69Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PortAccessOutput

    Set TRISi = 0Write data bit to PORTi

    InputSet TRISi = 1Read data bit from PORTi

    Order of operationsRead

    Reads levels on physical I/O pins (not data register file)

    WriteImplemented as read modifyCauses update of all input data registers from physical I/O pinsProgram must read all required inputs before any write

  • 70Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PORTA5 general purpose I/O pins

    RA5 and RA3:RA0Standard electrical behavior

    TTL input levels and CMOS output drivers

    Special input RA4Schmitt trigger input

    Threshold decision converts input to binary (RA4 > threshold)Open drain output

    Permits specialize electrical functions on outputWired-OR, analog weighting, ...

  • 71Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InitializingPORTACLRF STATUS ; Bank0CLRF PORTA ; Initialize PORTABSF STATUS, RP0 ; Select Bank1MOVLW 0xCF ; Initialize data directions

    ; CFh = 11001111; = x x Out Out In In In In

    MOVWF TRISA ; PORTA = inputs ; PORTA = outputs; TRISA always read 0

  • 72Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PORTB8 general purpose I/O pins

    RB7:RB0Standard electrical behavior

    TTL input levels and CMOS output drivers

    Interrupt on changeInput pins RB7:RB4Inputs compared with previous read of PORTBOR(compare bits) = 1 RB Port Change Interrupt Can wake device from SLEEP

    Example wake-up on key press

    Clear interruptRead or write PORTBClear flag bit RBIF

  • 73Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PortsCtoGPorts C to E

    8 binary I/O pinsRi7:Ri0, i = C, D, E

    Schmitt trigger on each input pin

    Ports F and GRi7:Ri0, i = F, G8 binary inputs

    Schmitt trigger on each input

    8 LCD driver outputsDirect connection to 7-segment display

  • 74Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    AnalogtoDigital(A/D)ConverterModuleConverts analog input signals

    Sample and hold One of 8 analog inputs (channels)Conversion to 8-bit binary number

    Analog reference voltage Software selectable

    Device supply voltageVoltage level on VREF pin

    Can operate in sleep mode

    Three registersA/D Result Register (ADRES)A/D Control Register0 (ADCON0)A/D Control Register1 (ADCON1)

  • 75Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ADCON0SFR

    01234567ADONResvGO/DONECHS0CHS1CHS2ADCS0ADCS1

    0=deactivated1=activated

    0=notinprogress

    A/D Conversion Status

    011=channel3(AN3)

    :

    111=channel7(AN7)

    Analog Channel Select

    10=fOSC/32

    11=fRC (internalA/DRCosc)

    A/D Conversion Clock Select

    A/D OnADON

    0Reserved1=inprogress

    GO/DONE

    000=channel0(AN0)

    001=channel1(AN1)

    010=channel2(AN2)

    CHS2:CHS0

    00=fOSC/2

    01=fOSC/8

    ADCS1:ADCS0

  • 76Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ADCON1SFR

    01234567PCFG0PCFG1PCFG2

    DDDDDDDD11x AADVREFDDDD101 AADADDDD100 AAAVREFAADD011 AAAAADDD010 AAAVREFAAAA001 AAAAAAAA000

    AN0AN1AN2AN3AN4AN5AN6AN7PCFG2:PCFG0

    ConversioncomparestoreferencevoltageVREF=devicesupplyvoltageAN3=D

    ConversioncomparestoreferencevoltageVREF=voltageonAN3AN3=VREF

    PortpinconfiguredfordigitalI/OD

    PortpinconfiguredforanaloginputA

  • 77Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    OperationofA/DConverterConfigure A/D module

    Analog pins + voltage reference + digital I/O in ADCON1Select A/D input channel (ADCON0)Select A/D conversion clock (ADCON0)Activate A/D module (ADCON0)

    Configure A/D interrupt (optional)Clear ADIFSet ADIE + GIE

    Start conversionSet GO/DONE bit (ADCON0)

    Wait for A/D conversion to completePoll GO/DONE until cleared or wait for A/D interrupt

    Read resultA/D Result register (ADRES)

    Repeat

  • 78Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    A/DConversionBSF STATUS, RP0 ; Bank1CLRF ADCON1 ; Configure inputs as analogBSF PIE1, ADIE ; Enable A/D interruptsBCF STATUS, RP0 ; Bank0MOVLW 0xC1 ; C1h = 11000001MOVWF ADCON0 ; Internal RC, A/D active, Channel 0BCF PIR1, ADIF ; Clear A/D interrupt flagBSF INTCON, PEIE ; Enable peripheral interruptsBSF INTCON, GIE ; Enable all interrupts

    ;; Wait required sampling time for selected input;

    BSF ADCON0, GO ; ADCON0 1 Start conversion; On completion ADIF bit 1 and GO/DONE 0

  • 79Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ComparatorTwo analog comparators

    Inputs shared with I/O pinsAccess via CMCON SRF (device-dependent file address)

    Operation Analog input at VIN+ < VIN output = binary 0Analog input at VIN+ > VIN output = binary 1

    CMCON SFR

    responsetime

    01234567CM0CM1CM2CISC1OUTC2OUT

    SeetableonfollowingslidesComparatorInputSwitch

    CISCM2:CM0

    1 = VIN+ > VIN0 = VIN+ > VIN

    ComparatorOutputs

    C2OUTC1OUT

  • 80Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ComparatorModes 1

  • 81Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    ComparatorModes 2

  • 82Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    InitializeComparatorFLAG_REG EQU 0x20 ; FLAG_REG points to address 20h

    CLRF FLAG_REG ; flag register 0CLRF PORTA ; PORTA 0ANDLW 0xC0 ; Mask comparator bits W 0IORWF FLAG_REG,F ; FLAG_REG FLAG_REG OR WMOVLW 0x03 ; Init comparator modeMOVWF CMCON ; CM = 011 (2 common reference)BSF STATUS,RP0 ; Bank1MOVLW 0x07 ; Initialize data directionMOVWF TRISA ; Set RA as inputs

    ; RA as outputs; TRISA read 0

    BCF STATUS,RP0 ; Bank0CALL DELAY 10 ; 10ms delayMOVF CMCON,F ; Read CMCON (enter read mode)BCF PIR1,CMIF ; Clear pending interruptsBSF STATUS,RP0 ; Bank1BSF PIE1,CMIE ; Enable comparator interruptsBCF STATUS,RP0 ; Bank0BSF INTCON,PEIE ; Enable peripheral interruptsBSF INTCON,GIE ; Global interrupt enable

  • 83Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    USARTUniversal Synchronous / Asynchronous Receiver / Transmitter

    Serial Communications Interface (SCI)PC serial port / modem

    TransmitParallel serialData byte as 8 serial bits

    Receive Serial parallelAssemble 8 bits as data byte

    ModesAsynchronous

    Full duplex simultaneous transmit + receive

    SynchronousHalf duplex transmit or receiveMaster synchronize data to internal clock Slave synchronize data to external clock

  • 84Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    USARTTransmitOperationData

    Byte TXREG framing TSR bit FIFO TX pinFraming add start bit / parity bit

    TSRfull/emptyPortEnable

    ParitybitTransmitSpeed

    InterruptonemptyTXREG

  • 85Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    USARTReceiveOperationData

    RX pin bit FIFO RSR RCREG byte Framing

    Identify data between stop bitsCheck for parity error

    PortEnable

    Sample+FIFO

    RCREGfull

    Paritybit

    OverrunError FramingErrorContinuousReceiveEnable

  • 86Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    SFRsCCP control register (CPCON)CCPR High byte / Low byte (CCPRH / CCPRL)

    I/O pinCPP pin (CPPx) device-dependent pin configured in TRIS SFR

    Capture ModeCaptures 16-bit value of register TMR1 on CCPx event

    Every falling edge / rising edge / 4th rising edge / 16th rising edge

    Triggers interruptCompare mode

    Compare 16-bit (CCPR == TMR1)Configurable response on match

    CCPx 0 / 1Interrupt with no change on CPPx

    Pulse Width Modulation (PWM) modeGenerates duty cycle waveform on CCPx

    Capture/Compare/PWM(CCP)Module

    Period

    Dutycycle

  • 87Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    CCPxCONSFR

    01234567CCPxM0CCPxM1CCPxM2CCPxM3DCxB0DCxB1

    0000=Capture/Compare/PWMoff(resets CCPx module)

    0100=Capturemode,everyfallingedge

    0101=Capturemode,everyrisingedge

    0110=Capturemode,every4thrisingedge

    0111=Capturemode,every16thrisingedge

    1000=Comparemode,CCPlowtohigh

    1001=Comparemode,CCPhightolow

    1010=Comparemode,softwareinterruptonmatch

    1011=Comparemode,Triggerspecialevent

    11xx=PWMmode

    DCx1:DCx0of10bitPWMdutycycle

    DCx9:DCx2inCCPRxL

    CCPx ModeSelectbits

    CCPxM3:CCPxM0

    PWMDutyCyclebit1andbit0

    DCxB1:DCxB0

  • 88Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    CaptureModeEvent

    Input pin CCPx divided by prescaler sampled on rising / falling edge

    ConfigurationCCPcontrolregister,x=1,2

    16bitvalueinTimer1

    CCPxR =CCPRxH:CCPRxL,x=1,2

    Interruptflag,x=1,2

  • 89Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    CompareMode16-bit compare

    (CCPRx == TMR1), x = 1, 2

    16bitvalueofTimer1

    16bitpresetvalueinCCPRx

    Interrupt

    ResetTimer1

  • 90Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PulseWidthModulation(PWM)modeGenerates duty cycle waveform

    Period

    Dutycycle

    Period=(PR2+1) 4 prescale TOSCDutycycle=DC prescale TOSC

    Setperiod

    Setdutycycle

    0 PR2 2550 DC 1023

  • 91Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    DutyCycle

    PWM OSCT 4 (PR2 1) P T= +

    ON OSCT DC P T=

    PWM OSCT 4 P T=

    ON OSCT P T=

    ( ) ( )( )

    ( ) ( )

    ( ) ( ) ( )( )( )

    ON OSC

    PWM OSC

    ON

    PWM

    ON OSC

    PWM OSC

    r ON

    OSC

    T DC P T DCT 4 PR2 1 P T 4 PR2 1

    T1 DC 4 PR2 1

    T

    T P T 1T 4 PR2 1 P T 4 PR2 1

    log 4 PR2 1 PTDC 4 PR2 1 2 4 PR2 1 P r

    T log 2

    = = + + +

    = = + +

    + + = + =

    DutyCycle

    Controllability

    Resolution

  • 92Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    DutyCycleExample

    ( )

    ( )

    ( )( )

    -

    -

    1

    OSC OSC

    PWM

    1

    PWM

    ON

    ON

    PWM

    ON

    PWM

    r ON

    OSC

    f 20MHz T 20MHz 50ns

    P 1

    PR2 63 T 4 64 50ns 12.8 s

    f 12.8 s 78.125kHz

    DC 32 T 32 50ns 1.6ms

    T 320.125 12.5%

    T 4 64

    T 1 10.00390625

    T 4 64 256

    log 256T2 4 64 r 8

    T log 2

    = = === = =

    = =

    = = == = =

    = = =

    = = =

    Frequencyanddutycyclefromgivenparameters

  • 93Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PWMExample

    Internal oscillator fOSC =4MHz TOSC =0.25s

    PWM frequency

    TPWM =1ms=4 (PR2+1) P 0.25s=(PR2+1) P 1sRequire(PR2+1) P=1000

    Preset and PR2

    P=4 PR2+1=250 PR2=249=0xF9TON =P TOSC =1s

    Duty cycle = 10%

    TON =0.10 1ms=100sDC=0.10 4 (PR2+1) =100 =0x064 DCH =0x19=25DCL=0

    Choosingparameters

    Oscillatorfrequency=4MHzProduceoutputwith

    1kHzfrequency(TPWM =1ms)10%dutycycle

  • 94Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PWMExampleCode List p = 16F873 include "P16F873.INC" Init_pwm: movlw 0x01 ; Stop Timer2 movwf T2CON ; Prescaler 4 clrf CCP1CON ; Reset module CCP1 clrf TMR2 ; Timer2 0 movlw .25 ; 10% duty cycle movwf CCPR1L ; DC1B9:DC1B2 bsf STATUS, RP0 ; Bank 1 movlw .249 ; Timer2 movwf PR2 bcf PIE1, TMR2IE ; Disable Timer2 interrupt bcf PIE1, CCP1IE ; Disable CCP1 interrupt bcf TRISC, 2 ; Pin CCP1 = output bcf STATUS, RP0 ; Bank 0 clrf PIR1 ; Clear interrupt flags movlw 0x0C ; CCP1 in PWM mode movwf CCP1CON ; DC1B1:DC1B0 0 bsf T2CON, TMR2ON ; Start Timer2 return TON_pwm: movwf CCPR1L ; Call to change return ; Duty cycle end

  • 95Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    DataEEPROMAdditional long term data memory

    Internal EEPROMIndirect addressing

    Not directly mapped in register file spaceAccess through SFRs

    EECON1Control bits

    EECON2Initiates read / write operationVirtual register not physically implemented

    EEDATA8-bit data for read / write

    EEADRAccess address in EEPROM8-bit address 256 EEPROM locations

  • 96Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    EECON1SFR

    01234567RDWRWRENWRERREEIF

    1=Initiateswritecycle0=WritecycletodataEEPROMiscomplete(clearedbyhardware)

    WriteControlWR

    1=Initiatesread0=DoesnotinitiateanEEPROMread(clearedbyhardware)

    ReadControlRD

    1=Allowswritecycles0=InhibitswritetodataEEPROM

    1=Writeoperationprematurelyterminated0=Writeoperationcompleted

    1=Writeoperationcompleted0=Writeoperationnotcomplete/notstarted

    WriteEnableWREN

    ErrorFlagWRERR

    WriteOperationInterruptFlag

    EEIF

  • 97Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    EECON2SFRNot physical register

    Read EECON2 0SFR access to EEPROM write hardware

    Data EEPROM write sequenceEEDATA dataEEADR address_for_writeW 55hEECON2 WW AAhEECON2 W ; EECON2 55AAhEECON1 1 ; initiate(writecontrolbitset)

  • 98Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    EEPROMRead/Write/Verify 1Read

    BCF STATUS, RP0 ; Bank0MOVLW CONFIG_ADDR ; Address in Data EEPROMMOVWF EEADR ; Set read addressBSF STATUS, RP0 ; Set Bank1BSF EECON1, RD ; Initiate EEPROM ReadBCF STATUS, RP0 ; Set Bank0MOVF EEDATA, W ; W EEDATA

    WriteBSF STATUS, RP0 ; Bank1BCF INTCON, GIE ; Disable INTsBSF EECON1, WREN ; Enable writeMOVLW 55h ; W 55hMOVWF EECON2 ; EECON2 WMOVLW AAh ; W AAhMOVWF EECON2 ; EECON2 WBSF EECON1,WR ; Set WR bit (initiates write)BSF INTCON, GIE ; Enable INTs

  • 99Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    EEPROMRead/Write/Verify 2Verify

    BCF STATUS, RP0 ; Bank0MOVF EEDATA, W ; copy write request data to WBSF STATUS, RP0 ; Bank1

    READBSF EECON1, RD ; Initiate readBCF STATUS, RP0 ; Bank0SUBWF EEDATA, W ; W write request read BTFSS STATUS, Z ; Skip next if (Z == 1)GOTO WRITE_ERR ; Handle write error

  • 100Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PICConfigurationBits 1Determines certain device modes

    Oscillator mode, WDT reset, copy protectionSets device state on power-up

    Configured during EEPROM programmingMapped to program memory location 2007h

    Not accessible at run time

    1=Pinfunction=MCLR0=Pinfunction=digitalI/O

    MCLR (masterclear)PinFunctionMCLRE

    1=PWRT disabled0=PWRT enabled

    PowerupTimerEnablePWRTE

    1=BORenabled0=BORdisabled

    BrownoutResetEnableBODEN

    1=Codeprotectionoff0=DataEEPROMMemorycodeprotected

    DataEEPROMCodeProtectionDP

    11=Codeprotectionoff10=devicedependent01=devicedependent00=memorycodeprotected

    CodeProtectionCP1:CP0

  • 101Dr. Martin LandPIC MicrocontrollerEmbedded Systems Hadassah College Spring 2012

    PICConfigurationBits 2

    111=EXTRCoscillator,withCLKOUT

    110=EXTRCoscillator

    101=INTRCoscillator,withCLKOUT

    100=INTRCoscillator

    011=Reserved

    010=HSoscillator

    001=XToscillator

    000=LPoscillator

    OscillatorSelection

    FordeviceswithinternalRCFOSC2:FOSC0

    11=RCoscillator

    10=HSoscillator

    01=XToscillator

    00=LPoscillator

    OscillatorSelection

    FordeviceswithnointernalRCFOSC1:FOSC0

    1=WDTenabled0=WDTdisabled

    WatchdogTimerEnableWDTE