Upload
mim-fauzi
View
628
Download
0
Embed Size (px)
Citation preview
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 1201ASP v8.0 January 2007
201ASPMid-Range Family Peripheral Configuration and Assembly
Programming
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 2201ASP
ObjectivesAt the end of this class you will:– Understand the basic PICmicro peripherals
and their associated registers
– Have “HANDS ON” experience initializing Mid-Range peripherals
– Be able to implement peripherals not covered here
– Understand interrupts and polling
– Write your own application code from “scratch”
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 3201ASP
To get the most from this Class
Ideally you should be familiar with the following:– Assembler programming– Basic Mid-Range family Instruction set– Data and Program memory organization– MPLAB Integrated Development Environment– Microchip ICD2 debugger
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 4201ASP
201ASP AgendaBrief review of Mid-Range Architecture, Instruction Set and ToolsInterrupts on the Mid-Range PICmicro– Interrupts Lab
Peripheral discussion:– Input/Output Ports– Timers
Timer0Timer1– Timer1 Lab
Timer2– Timer2 Lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 5201ASP
201ASP Agenda (cont.)
Capture / Compare / PWM Module (CCP)– PWM and Output Compare Labs
Analog Comparator
Analog to Digital Converters (ADC)– ADC Lab
Addressable Universal Asynchronous & Synchronous Receiver & Transmitter (AUSART)
I2C with the Master Synchronous Serial Port– I2C Based Temp Sensor Lab
Wrap-Up and additional questions
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 6201ASP v8.0 January 2007
Mid-Range Family Basic Architecture and
Development Tools
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 7201ASP
Mid-Range PIC Block Diagram
ADC
TIMER0
MUX
ALU
AUSART
MSSP
PERIPHERALS
WORKING REGISTER
STATUS REGISTERPages of Program Memory
Banks of Data Memory
INSTRUCTION REGISTER
8-bit value from instruction
14-bits
PROGRAM COUNTER
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 8201ASP
Program Memory
Maximum 8K words– (8K x 14 bits/word)/1 byte
= 14Kbytes of memory
Reset Vector at 0000h– Program Counter (PC) will
go to this address on reset
Interrupt Vector at 0004h– Program Counter (PC) will
go to this address upon any Interrupt
Reset Vector
Interrupt Vector
Page 0
Page 1
Page 2
Page 3
0000h
0004h
0005h07FFh
0800h0FFFh
1000h17FFh
1800h1FFFh
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 9201ASP
Program Counter (PC) and Stack
13-bit PC – PCL ALU result (8-bits) or
OPCODE(11-bits)– PCH Paging bits
Updated from PCLATHSpecifies page in program memory
8 Level Deep Stack– Stores the contents of the PC
PUSHES– CALL/Interrupt
POPS– RETURN, RETFIE,RETLW
PCLATH
PCH<12:8> PCL
Stack Level 1
Stack Level 8
Program Memory
PC<12:0>CALL, RETURN, RETFIE, RETLW
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 10201ASP
Data Memory Map
128 Bytes
SharedShared SharedShared SharedShared
Bank 0 Bank1 Bank2 Bank3
000h
01Fh020h
07Fh
080h
09Fh0A0h
0FFh
100h
110h
17Fh
180h
190h
1FFh
0EFh 16Fh 1EFh
10Fh 18FhSpecialFunctionRegistersRegisters
SFR SFR
GeneralPurposePurposeRegistersRegisters
GeneralGeneralPurposePurposeRegistersRegisters
SpecialFunctionFunctionRegistersRegisters
GeneralGeneralPurposeRegistersRegisters
GeneralPurposePurposeRegistersRegisters
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 11201ASP
Special Function Registers (SFRs)
06hPORTBPORTC 07h
PORTD 08h
PORTE 09h
PCLATH 0Ah
INTCON 0Bh
PIR1 0Ch
PIR2 0Dh
86hTRISBTRISC 87h
TRISD 88h
TRISE 89h
PCLATH 8Ah
INTCON 8Bh
PIE1 8Ch
PIE2 8Dh
Bank0 Bank1
Register File ConceptAccessed like any other registerSome registers carry across all banks (PCLATH, INTCON, etc.)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 12201ASP
Status Register
Contains:– Arithmetic status of the
ALU– The RESET status– Bank select bits for data
memory
RP1 RP0RP1 RP00 0
0 11 01 1
BANK0BANK1BANK2BANK3
IRP RP1 RP0 TO PD Z DC C
Indirect Register Bank Select bit:(used for indirect addressing)
1 = Bank 2,3
0 = Bank 0,1
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 13201ASP
PIC16 Instruction Set35 single word instructionsAll are single cycle except for program branches
Byte Oriented OperationsByte Oriented Operations Bit Oriented OperationsBit Oriented Operationsaddwf f,daddwf f,dandwf f,dandwf f,dclrf fclrf fclrw -clrw -comf f,dcomf f,ddecf f,ddecf f,ddecfsz f,ddecfsz f,dincf f,dincf f,dincfsz f,dincfsz f,diorwf f,diorwf f,dmovf f,dmovf f,dmovwf fmovwf fnop -nop -rlf f,drlf f,drrf f,drrf f,dsubwf f,dsubwf f,dswapf f,dswapf f,dxorwf f,dxorwf f,d
Add W and fAdd W and fAND W with fAND W with fClear fClear fClear WClear WComplement fComplement fDecrement fDecrement fDecrement f, Skip if 0Decrement f, Skip if 0Increment fIncrement fIncrement f, Skip if 0Increment f, Skip if 0Inclusive OR W with fInclusive OR W with fMove fMove fMove W to fMove W to fNo OperationNo OperationRotate Left f through CarryRotate Left f through CarryRotate Right f through CarryRotate Right f through CarrySubtract W from fSubtract W from fSwap nibbles in fSwap nibbles in fExclusive OR W with fExclusive OR W with f
bcf f,bbcf f,bbsf f,bbsf f,bbtfsc f,bbtfsc f,bbtfss f,bbtfss f,b
Bit Clear fBit Clear fBit Set fBit Set fBit Test f, Skip if ClearBit Test f, Skip if ClearBit Test f, Skip if SetBit Test f, Skip if Set
Literal and Control OperationsLiteral and Control Operationsaddlw kaddlw kandlw kandlw kcall kcall kclrwdt -clrwdt -goto kgoto kiorlw kiorlw kmovlw kmovlw kretfie -retfie -retlw kretlw kreturn -return -sleep -sleep -sublw ksublw kxorlw kxorlw k
Add literal and WAdd literal and WAND literal with WAND literal with WCall subroutineCall subroutineClear Watchdog TimerClear Watchdog TimerGo to addressGo to addressInclusive OR literal with WInclusive OR literal with WMove literal to WMove literal to WReturn from interruptReturn from interruptReturn with literal in WReturn with literal in WReturn from SubroutineReturn from SubroutineGo into standby modeGo into standby modeSubtract W from literalSubtract W from literalExclusive OR literal with WExclusive OR literal with W
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 14201ASP v8.0 January 2007
PICmicro Development Tools
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 15201ASP
MPLAB® IDE
MPLABMPLAB®® IDE (Integrated Development IDE (Integrated Development Environment)Environment)Integrates different Microchip and third Integrates different Microchip and third party toolsparty tools–– Code Editor Code Editor –– Cross CompilersCross Compilers–– AssemblersAssemblers–– Simulators, InSimulators, In--Circuit Debuggers, Emulators Circuit Debuggers, Emulators –– ProgrammersProgrammers
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 16201ASP
MPLAB® IDE
MPLABMPLAB®® IDE (IDE (IIntegrated ntegrated DDevelopment evelopment EEnvironment)nvironment)Integrates different Microchip and third Integrates different Microchip and third party toolsparty tools–– Code Editor Code Editor –– Cross CompilersCross Compilers–– AssemblersAssemblers–– Simulators, InSimulators, In--Circuit Debuggers, Emulators Circuit Debuggers, Emulators –– ProgrammersProgrammers
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 17201ASP
ICD 2 (In Circuit Debugger)
MPLABMPLAB® ICD 2 is a low cost, realICD 2 is a low cost, real--time time debugger and programmer.debugger and programmer.–– Reading/Writing memory space and Reading/Writing memory space and
EEDATA areas of the PICEEDATA areas of the PIC–– Programs configuration bitsPrograms configuration bits–– Real time debuggingReal time debugging–– Erase of program memory Erase of program memory
space with verificationspace with verification
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 18201ASP
18, 28 and 40-pin DIP sockets
9V to 5V regulator
ICD Connecto
r
RS232 Connector
Push button Switches
PICDEM® 2 Plus Board
Analog Pot
LEDs 16 x 2 LCD Module
PiezoBuzzer
I2C Based Temp Sensor
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 19201ASP v8.0 January 2007
Interrupts
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 20201ASP
Often we would like the processor to perform a task if a specific event occurs
Two methods to check if this event has occurred:– Polling:
Continuously check for event at various points in the code
– Interrupts:“INTERRUPTS” the Main program and starts an Interrupt Service Routine when an event occurs
Polling and Interrupts
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 21201ASP
Pollingbsf PORTA,1 ;Set bit 1 of
;PORTA
btfss INTCON,TMR0IF ;Check Timer0;interrupt flag;in “INTCON”;register and;skip the next;instruction if;it is set
goto $-1 ;Go to;previous;instruction
bcf PORTA,1 ;Clear bit 0 of;PORTA
RA<1> = 1RA<1> = 1
TMR0IF = 1??
TMR0IF = 1??
RA<1> = 0RA<1> = 0
YES
NO
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 22201ASP
Reset code 000hgoto Start
;=========================int_vector code 004h
retfie ;return from ;interrupt
;=========================
main_prog code
Start ;start label for main code
end
Interrupts
Main program
execution
Main program
execution
no interrupt
Execute ISR at address 004h
Execute ISR at address 004h
interrupt flag set
retfieinstruction
Interrupt ServiceRoutine (ISR)
Main programcode
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 23201ASP
Enabling Interrupts
Processor must be told that interrupts will be used– A number of registers with interrupt enable
bits do this:Interrupt Control (INTCON)Peripheral Interrupt Enable 1 (PIE1)Peripheral Interrupt Enable 2 (PIE2)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 24201ASP
Interrupt Logic
INTEINTF
RBIERBIF
TMR2IETMR2IF
ADIEADIF
PEIE
GIE
Interrupt
Other peripherals
TMR0IETMR0IF
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 25201ASP
GIE
INTCON Register(Core Interrupts)
PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF
Flags will set even if interrupts aren’t enabled!
Global Interrupt EnableGIEPeripheral Interrupt EnablePEIETimer0 Interrupt EnableTMRIEExternal Interrupt EnableINTEPORTB change Interrupt EnableRBIE
DescriptionEnable Bits
Timer0 Overflow Interrupt FlagTMR0IFRB0/INT External Interrupt FlagINTFPORTB Change Interrupt FlagRBIF
DescriptionFlag Bits
Must be set to use any Interrupts
Must be set to useany PeripheralInterrupts
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 26201ASP
Enabling a Core Interrupt
INTCON
GIE
Interrupt detected on “RB0/INT” Pin!!
0
“goto $” address
Stack
0 0 0 0 0 0 011INTE INTF
1
Int_vect CODE 004h;clear external interrupt;flag to enable;further interruptsbcf INTCON,INTF
<ISR code>retfie
Main CODEStart
<code to set up PORTB >
; initialize INTCONclrf INTCON
;enable an external ;interrupt on the INT pinbsf INTCON,INTE
;enable global interrupts bsf INTCON,GIE; sit here and loop forevergoto $
Program Counter
“goto $” address
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 27201ASP
Peripheral InterruptsTwo registers ENABLE interrupts for peripherals– Peripheral Interrupt Enable 1 (PIE1)– Peripheral Interrupt Enable 2 (PIE2)
Two registers display peripheral REQUESTS for an interrupt (Flags)– Peripheral Interrupt Request 1 (PIR1)– Peripheral Interrupt Request 2 (PIR2)
*Flags will set even if interrupts are not enabled!!
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 28201ASP
PIE1 and PIR1 Registers*
ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE
PIE1 Register (Peripheral Interrupt Enables)
ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IFPIR1 Register (Peripheral Interrupt Requests)
ADC conversion completeADIFADIEAUSART receive buffer is fullRCIFRCIEAUSART transmit buffer is fullTXIFTXIEI2C or SPI InterruptSSPIFSSPIETimer1 register capture or compare matchCCP1IFCCP1IETimer2 value and PR2 period value matchTMR2IFTMR2IETimer1 register has overflowedTMR1IFTMR1IE
ConditionFlagEnable
*Check individual datasheets for bit locations
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 29201ASP
PIE2 and PIR2 Registers*
C2IE C1IE EEIE BCLIE ULPWUIE CCP2IEOSCFIE
PIE2 Register (Interrupt Enables)
C2IF C1IF EEIF BCLIF ULPWUIF CCP2IFOSCFIFPIR2 Register (Interrupt Flags)
Comparator2 output changedC2IFC2IEComparator1 output changedC1IFC1IEWrite operation completedEEIFEEIEBus collision occurred in MSSP I2C modeBCLIFBCLIEWake-up condition occurredULPWUIFULPWUIETimer1 Capture or Compare match occurredCCP2IFCCP2IE
System Oscillator FailedOSCFIFOSCFIE
ConditionFlagEnable
*Check individual datasheets for bit locations
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 30201ASP
Enabling a Peripheral (Timer 1) Interrupt
1 1INTCON
GIE PEIEPIE1
PIR1TMR1IE
TMR1IF
1
0
Timer1 Overflow!
1
0
“goto $” address
“goto $” address
Int_vect CODE 004h
banksel PIR1bcf PIR1, TMR1IF
<ISR code>retfie
Main CODEStart
banksel PIR1bcf PIR1,TMR1IFbanksel PIE1bsf PIE,TMR1IE
bsf INTCON,PEIEbsf INTCON,GIE
<code to set up Timer1>
; sit here and loop forevergoto $
Stack
Program Counter
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 31201ASP
Interrupt Latency
Interrupt Latency:– Time from interrupt event to execution of
instruction at address 0004h– Synchronous interrupts (typically internal)
latency is 3 instruction cycles (Tcy)– Asynchronous interrupts (typically external)
latency is 3 – 3.75 instruction cycles
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 32201ASP
Context SavingDuring an interrupt:– Only the PC value is saved (on the stack)– Registers changed in the Interrupt Service
Routine (ISR) are permanently changed
Key registers you may want saved:– Working register– Status – PCLATH (Program Counter Latch High)– User defined registers
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 33201ASP
Interrupt Priority
Mid-Range PIC microcontrollers treat all Interrupts with the same priority
The user must do the following:– Determine source of interrupt– Determine the order in which the interrupts
are serviced.
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 34201ASP
Interrupt Priority ExampleINT_VECTOR CODE 0x004 ;interrupt vector location
;Save contextmovwf temp_w ;save WREGswapf STATUS,w ;movf affects Z bit,
;use swapf insteadmovwf temp_status ;save STATUS register
;Check flags in order of prioritybtfsc INTCON,RBIF ;PORTB change?call PORTB_ISRbtfsc PIR1,TMR2IF ;Timer2 interrupt?call Timer2_ISRbtfsc PIR2,TMR1IF ;Timer1 interrupt?call Timer1_ISR
Restore_context:swapf temp_status,wmovwf STATUS ;restore STATUS regmovf temp_w,w ;restore WREGretfie ;return from interrupt
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 35201ASP v8.0 January 2007
Interrupt Hands on Lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 36201ASP
Interrupt
The objective of this is to:– Learn how to set up and enable an
interrupt on the Mid-Range PIC
– Become more familiar with the MPLAB IDE, the PICdem2 Plus and the ICD2
Building a ProjectUsing the ICD to set a break point
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 37201ASP
Interrupt Lab Overview
Enable Interrupts
Initialize PORTB (RB0) for S3 input
Clear Variables
“No Operation” NOP
Call debounce
delay function
Increment Count variable
Clear IF
Return to Main
Interrupt Vector Main Program
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 38201ASP
Lab Specifics
Code is located in C:\RTC\201_ASP\Lab1-INT
The S3 switch is connected to the “RBO/INT” pin on PORTB
The “push_count” register will display the # of times S3 has been pushed.
Use MPLAB and the ICD to set a “breakpoint” in the code to view the changing value of the register named “push_count”
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 39201ASP
What you need to knowThe function of the INTCON register bits
Jumper J6 must be removed in order for the INTE pin to work
A subroutine called “debounce” is given– masks the mechanical bouncing of S3
How to setup break points and a “Watch Window” in MPLAB
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 40201ASP
Interrupt Lab Solution
bsf STATUS,RP0 ; point to BANK1
bsf TRISB,0 ; ### initialize PORTB<0> as input
bsf INTCON,INTE ; ### enable INTE interrupts
bsf INTCON,GIE ; ### Enable global interrupts
bcf STATUS,RP0 ; return to BANK0
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 41201ASP v8.0 January 2007
Peripherals
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 42201ASP
Mid-Range Family Peripherals
I/O PortsTimers (0, 1, 2)Capture/Compare/PWMComparatorsAnalog-to-Digital ConverterAUSARTI2C and SPI SerialInterface
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 43201ASP
I/O OverviewUp to 35 bi-directional Input/Output pins– some multiplexed with peripheral functions
High drive capability– 25mA source or sink
Direct, single cycle bit manipulation
Most I/O’s have ESD protection
After Reset:– Analog capable pins come up as Analog– Digital I/O pins come up as Input
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 44201ASP
PORTx and TRISx RegistersEvery PORT (A, B, C, D, E) will have a corresponding direction register TRISx
RB7RB7 RB6RB6 RB5RB5 RB4RB4 RB3RB3 RB2RB2 RB1RB1 RB0RB0
PORTB Register
TRISB7TRISB7 TRISB6TRISB6 TRISB5TRISB5 TRISB4TRISB4 TRISB3TRISB3 TRISB2TRISB2 TRISB1TRISB1 TRISB0TRISB0
PORTB Tri-State Register (TRISB)
1 = corresponding PORTB pin is an INPUT0 = corresponding PORTB pin is an OUTPUT
DataConfigures Data Direction
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 45201ASP
Configuring Analog Inputs for DigitalI/O’s with digital and analog capabilities default to analog on reset
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 46201ASP
Two ways to configure Analog inputs as Digital:1) Analog Select Registers (ANSEL and ANSELH)
For devices with > 8 analog pinsOR
2) ADC Control register 1 (ADCON1)For devices with 8 or less analog pins
ANS7ANS7 ANS6ANS6 ANS5ANS5 ANS4ANS4 ANS3ANS3 ANS2ANS2 ANS1ANS1 ANS0ANS0
ANS13ANS13 ANS12ANS12 ANS11ANS11 ANS10ANS10 ANS9ANS9 ANS8ANS8
Analog Select Register (ANSEL)
Analog Select High Register (ANSELH)
1 = Pin assigned as Analog Input0 = Digital I/O
Configuring Analog Inputs for Digital
ADFMADFM ADCS2ADCS2
ADC Control Register 1 (ADCON1)
PCFG3PCFG3 PCFG2PCFG2 PCFG1PCFG1 PCFG0PCFG0
Port Configuration Bits
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 47201ASP
Configuring Analog Inputs for Digital
ADFMADFM ADCS2ADCS2
ADC Control Register 1 (ADCON1)
PCFG3PCFG3 PCFG2PCFG2 PCFG1PCFG1 PCFG0PCFG0
Port Configuration Bits
VddAN7 AN6 AN5 AN4 AN1 AN0AN3 AN2PCFG <3:0>
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 48201ASP
Initializing Digital I/O
Initialize PORTB– RB4 through RB7 as Digital Inputs– RB0 through RB3 as Digital Outputs
;------------configure PORTB for digital ----------------------banksel PORTB ;Go to bank containing PORTB registerclrf PORTB ;Initialize PORTB databanksel ANSELH ;Go to bank containing ANSELH registerclrf ANSELH ;Set as all digital
;-----------Set up direction of each PORTB pin-----------------banksel TRISB ;Go to bank containing TRISB registermovlw b’11110000’ ;Move value to set TRISB<7:4> high and
;TRISB<3:0> low into W registermovwf TRISB ;Move value in W into TRISB
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 49201ASP
PORTB Interrupt & Weak Pull-Up Options
All PORTB pins have Interrupt-on-Change and Weak Pull-Up options
RB3WPUB7 WPUB6 WPUB5 WPUB4 WPUB3 WPUB2 WPUB1 WPUB0
Weak Pull-Up PORTB Register (WPUB)
1 = Pull-up enabled0 = Pull-up disabled
1
IOCB7 IOCB6 IOCB5 IOCB4 ICOB3 IOCB2 IOCB1 IOCB0
RB4
Interrupt-On-Change PORTB Register (IOCB)
1 = Interrupt-on-change enabled0 = Interrupt-on-change disabled
GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIFInterrupt Control Register (INTCON)
RBIF
1
HIGHLOW
*PORTB must first be read/written and then RBIF can be cleared in software
Devices without WPUB register use RBPU bit in OPTION register
Devices without IOCB rely on RBIE bit in INTCON
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 50201ASP v8.0 January 2007
Timers
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 51201ASP
Timers are used for many functions:– timing reference to generate an event – count the number of events– waveform generation etc...
PIC16F877 has 3 timers– Timer0– Timer1– Timer2
Timers
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 52201ASP
Timer Comparison
TMR2 matches PR2
(TMR2IF in PIR2)
On overflow FFFFh 0000h
(TMR1IF in PIR1)
On overflow FFh 00h
(TMR0IF in INTCON)
INTERRUPT EVENT and FLAG
LOCATION
Prescaler (1:1,1:4,1:8)Postscaler (1:1 1:16)
Prescaler 3-bits (÷1,÷2,÷4,÷8)
Prescaler 8-bits (1:2 1:256)
CLOCK SCALING AVAILABLE(Resolution)
TIMER2TIMER1TIMER0
NOYESNOCAN WAKE PIC FROM SLEEP?
NoneT1CKI pin or Timer 1 oscillator
(T1OSC)
T0CKI pinCLOCK SOURCE(External )
Fosc/4Fosc/4Fosc/4CLOCK SOURCE(Internal)
8-bits (TMR2)16-bits (TMR1H:TMR1L)
8-bits (TMR0)SIZE OF REGISTER
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 53201ASP
Timer 0 Block Diagram
scaled clock TMR0T0CKIpin
Fosc/4
prescalerWatchdog Timer
synchronize
WDT out
OPTION registerRBPU INTEDG TOCS TOSE PSA PS2 PS1 PS0
TMR0 ClockSource Select1 = TOCK1, 0 = Fosc/4 Source Edge Select
1 = increment TMR0 on high-to-low transition0 = increment TMR0 on low-to-high transition
Prescaler Assignment1= prescaler assigned to WDT0= prescaler assigned to Timer 0
Prescaler Rate Select Bits
1:256111
1:128011
1:64101
1:32001
1:16110
1:8010
1:4100
1:2000
TMR0 RATEPS0PS1PS2
8
DATA BUS
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 54201ASP
scaled clock TMR0T0CKIpin
Fosc/4
prescalerWatchdog Timer
synchronize
8
DATA BUS
• Timer 0 is readable or writeable
TMR0IFINTCON register
• If the external clock source (TOCKI) is used it will be synchronized to the internal clock
•Timer 0 interrupt flag is set on TMR0 roll-over (FF to 00)
Timer 0 Block Diagram
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 55201ASP
Timer0 InitializationTMR00 0 0 0 0 0 0 0
INTCON0
OPTION_REG
0 0 0 0 0 0 1 1
TMR0IF
This interrupt flag will set on Timer0 overflow even if interrupts are disabled
PSAPS<2:0>
TOCS
Selects Timer 0 Clock Source
(External or Internal)
Prescaler Assignment
(WDT or TMR0)
Prescaler value = 1:16
1
;Make sure the Timer0 count;register (TMR0) is clearbanksel TMR0clrf TMR0
;Clear Timer0 interrupt flagbcf INTCON,TMR0IF
;Setup the Option register to;increment Timer0 from internal;clock with a prescaler of 1:16banksel OPTION_REGmovlw b’00000011’movwf OPTION_REG
;The TMR0 interrupt is disabled, do;polling on the flag bit (TMR0IF)btfss INTCON,TMR0IFgoto $-1
<continue>
1 1 1 1 1 1 0 01 110 0 0 0 0 0 0 0
Timer0 incrementing
Flag on overflow
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 56201ASP
Timer1 Block Diagram
T1CKIpin
T1 OSCT1OS0
T1OSI
prescaler synchronize
Timer1 Control Register (T1CON)
Clock Source Select1 = External (T1CKI)0 = Internal (FOSC/4)
LP Oscillator Enable1 = T1OSC selected0 = T1CKI can be used
Fosc/4
1:100
1:210
1:401
1:811
scaleT1CKPS0T1CKPS1Timer1 On 1 = Enable Timer1
T1GINV TMR1GE T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON
TMR1H TMR1L
Enable
TMR1ON
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 57201ASP
Timer1 External Clock Input Synchronization1 = do not synchronize external clock input0 = synchronize external clock input with
internal clock (Fosc/4)
Timer1 Block Diagram
T1CKIpin
T1 OSCT1OS0
T1OSI
prescaler synchronize
Timer1 Control Register (T1CON)
Fosc/4
TMR1H TMR1L
Timer1 Gate Enable and Timer1 Gate Invert are available on some devices
EnableTMR1ON
T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ONT1GINV TMR1GE
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 58201ASP
Main CodeStart;Start by clearing the Timer1 interrupt flag
banksel PIR1bcf PIR1, TMR1IF
;Enable Timer1 interruptbanksel PIE1bsf PIE1, TMR1IE
;Enable Global and Peripheral Interruptsbsf INTCON, PEIEbsf INTCON, GIE
Timer1 Interrupt Setup
INTCON
PIE1
1GIE PEIE
TMR1IE
1
1
PIR1
TMR1IF
0
TMR1H1 1 1 1 1 1 1 10 0 0 0 0 0 0 0
TMR1L1 1 1 1 1 1 0 11 1 1 1 1 1 1 01 1 1 1 1 1 1 10 0 0 0 0 0 0 0
1
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 59201ASP
Timer1 InitializationTMR1H0 0 0 0 0 0 0 0
T1CON (Timer1 Control)
Input clock prescale bits (T1CKPS<1:0>)
TMR1L0 0 0 0 0 0 0 0
PIR1 (Peripheral Interrupt Request)
TMR1IF
0000000 0
000000 11
Clock source select bit (TMR1CS)
TMR1ON
1
TMR1H:TMR1L INCREMENTING
1
OVERFLOW!!
;Make sure the TMR1 registers are clearbanksel TMR1Hclrf TMR1Hclrf TMR1L
;Make sure the TMR1IF flag in PIR1;is cleared
banksel PIR1bcf PIR1,TMR1IF
;Setup T1CON register for internal clock;with 1:8 prescaler, Timer1 is stopped;and T1 osc is disabled
movlw b’00110000’movwf T1CON
;Start Timer1 incrementingbsf T1CON, TMR1ON
;The TMR1 interrupt is disabled, do;polling on the Timer1 flag bit
btfss PIR1, TMR1IFgoto $-1
Timer1 oscillator enable bit (T1OSCEN)
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 60201ASP v8.0 January 2007
Timer1 Lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 61201ASP
Timer1 Lab
Objective of this lab is to become familiar with the operation of Timer1
AND
To gain experience enabling Peripheral Interrupts
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 62201ASP
Lab Overview
Initialize PORTB
Initialize Timer1 clocksource and pre-scaler:
Timer1 interrupts every 100,000 Instruction cycles
Enable Timer1, Globaland Peripheral Interrupts
NOP Main Loop
Main ProgramInterrupt VectorSave Context
Clear IF
Reload Timer1
Toggle LED 0
Toggle LED 3
Restore Context
Retfie
5th Int. ? NO
YES
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 63201ASP
Lab Specifics
The code for the lab is inC:\RTC\201_ASP\Lab2-TMR1
Within lab2.asm complete the following– Set Timer1 clock source to Fosc/4– Set Timer1 pre-scaler to 2– Load Timer1 with 0x3CB0 (65,536 – 50,000)
– Start Timer1– Enable Timer1, Global and Peripheral Interrupts
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 64201ASP
What you need to know
Register Operations of INTCON, T1CON, TMR1H, TMR1L and PIE1
With a value of 0x3CB0 and a pre-scaler of 2, Timer1 will overflow every 100,000 cycles
The interrupt vector code to toggle the LEDshas been provided
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 65201ASP
Timer1 LAB Solution;*******************************************************************;Set code to Select clock source, Set pre-scaler to 2, load hex 3CB0;into Timer1 and turn on Timer1;*******************************************************************
movlw 0x3C ; ### initialize TMR1L and TMR1Hmovwf TMR1H ; ###movlw 0xB0 ; ###movwf TMR1L ; ###bsf T1CON,T1CKPS0 ; ### configure prescaler to 1:2bsf T1CON,T1CKPS1 ; ###bcf T1CON,TMR1CS ; ### set clock source to Fosc/4bsf T1CON,TMR1ON ; ### turn TMR1 on
;;*******************************************************************;Enable Timer1 interrupts, Peripheral Interrupts and Global Interrupts;*******************************************************************
bsf STATUS,RP0 ; ### point to BANK1bsf PIE1,TMR1IE ; ### enable TMR1 interruptsbsf INTCON,GIE ; ### enable Peripheral interruptsbsf INTCON,PEIE ; ### enable Global interruptsbcf STATUS,RP0 ; ### return to bank0
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 66201ASP
Lab QuestionsQuestion:
Was Timer 1 still running during the time it took to service the Interrupt?
Answer:Yes
Question:What effect did this have on the value to be placed to reload TMR1L and TMR1H?
Answer: Everything – to be precise the latency of reloading Timer1 should be considered.
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 67201ASP
Timer2 Block Diagram
Prescaler1:1, 1:4, 1:16
COMPARATOR
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0
Postscaler1:1 1:16
Fosc/4
Timer2 ON1 = Timer2 enabled
1:16X11:4101:100
ScaleT2CKPS2T2CKPS1
TMR2
TMR2OUTPUT
PR2
Timer2 Control Register (T2CON)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 68201ASP
Timer2 Block Diagram
Prescaler1:1, 1:4, 1:16
COMPARATOR
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0
Postscaler1:1 1:16
Fosc/4
Timer2 ON1 = Timer2 enabled
1:16X11:4101:100
ScaleT2CKPS2T2CKPS1
TMR2
TMR2OUTPUT
PR2
1:161111
1:150111
1:141011
1:130011
1:121101
1:110101
1:101001
1:90001
1:81110
1:70110
1:61010
1:50010
1:41100
1:30100
1:21000
1:10000
SCALETOUTPS0TOUTPS1TOUTPS2TOUTPS3
Timer2 Control Register (T2CON)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 69201ASP
Prescaler1:1, 1:4, 1:16
COMPARATOR
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0
Postscaler1:1 1:16
Fosc/4
TMR2OUTPUT
1 1 1 1 0 1 1 01 1 1 1 1 0 0 01 1 1 1 0 1 1 11 1 1 1 0 1 0 1
1PIR1
TMR2IFTimer2 Control Register (T2CON)
TMR2
PR2
Timer2 Block Diagram
Load Period Register
Start Timer2 Counting
Flag set on first match with
postscaler = 1:1
1 1 1 1 1 0 0 0
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 70201ASP
Timer2 InitializationTMR2 (Timer2 Counter)
0 0 0 0 0 0 0 0
T2CON (Timer2 Control)
PIR1 (Peripheral Interrupt Request)
TMR2IF
PIE1 (Peripheral Interrupt Enable)
TMR2IE
0
0
100 00 111
;Disable the Timer2 interrupts in the PIE1;register. Make sure the Timer2 interrupt;flag in PIR1 is cleared.
banksel PIE1 bcf PIE1,TMR2IEbanksel PIR1bcf PIR1,TMR2IF
;Setup T2CON register for Postscaler = 1:15,;Prescaler = 1:16, Timer2 off
movlw b’01110010’movwf T2CON
;Make sure the TMR2 register is clearbanksel TMR2clrf TMR2
;Load the Period registerbanksel PR2movlw b’10000000’movwf PR2
;Start Timer2 incrementingbanksel T2CONbsf T2CON,TMR2ON
;The Timer2 interrupt is disabled, do;polling on the Timer2 interrupt flag
btfss PIR1,TMR2IFgoto $-1
1
Postscaler = 1:15 (TOUTPS<3:0>)
TMR2ON
Prescaler = 1:16 (T2CKPS<1:0>)
1
PR2 (Period Register Timer2)
0 0 0 0 0 0 01
Flag is set
Timer2 Incrementing
1 1 1 1 111 111 11
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 71201ASP v8.0 January 2007
Timer2 Lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 72201ASP
Timer2 LabThe Goal of Lab 3 is to become familiar with the following:– Timer2 Clock Source– Setting the Prescaler– Setting the Postscaler– Turning on Timer2– Setting the Interrupt Enable bits needed for
Timer2 to successfully generate an interrupt.
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 73201ASP
Lab OverviewMain Program
Initialize PORT B
Set up Timer2 Period,
Prescaler, Postscaler
Enable interrupts
NOP
Interrupt VectorSave Context
Increment counter thenumber of times
Timer2 has interrupted
Output 3 LSBs of countto LEDs
Restore context
retfie
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 74201ASP
Lab Specifics
Code for this lab is inC:\RTC\201_ASP\Lab3-TMR2
Complete the following sections of code– Set Timer2 prescaler to a value of 4– Set Timer2 postscaler to a value of 13– Turn Timer2 on– Configure the GIE and PEIE bits in the Interrupt
Control register (INTCON)– Configure the Timer2 Interrupt Enable bit in the
Timer2 Configuration register (T2CON)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 75201ASP
What you need to knowSpecial Function Registers (SFRs) needed for this lab are:– INTCON…(Interrupt Control)– PIE1……..(Peripheral Interrupt Enable 1) – PR2……...(Timer2 Period Register)– T2CON…..(Timer2 Control)
With the Period register (PR2) set to 250, the prescaler at 4, and the postscaler at 13, Timer2 will interrupt every 13 ms (about 1/80 second) with a 4Mhz oscillator (Fosc/4 = 1Mhz).
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 76201ASP
Timer2 Lab Solution;*****************************************************************; configure Timer2 prescaler of 4, PR2 of 250 and a postscaler; of 13 and turn timer2 on.;*****************************************************************;
BANKSEL T2CON ; point to bank containing T2CONmovlw 0x60 ; ### set TMR2 postscaler = 1:13movwf T2CON ; ###bsf T2CON,T2CKPS0 ; ### set TMR2 prescaler = 1:4bsf T2CON,TMR2ON ; ### turn on TMR2
;*****************************************************************;Enable Timer2 interrupts, Peripheral and Global Interrupts;*****************************************************************
bsf STATUS,RP0 ; point to BANK1bsf PIE1,TMR2IE ; ### enable TMR2 interruptsbsf INTCON,PEIE ; ### enable peripheral interruptsbsf INTCON,GIE ; ### enable global interruptsbcf STATUS,RP0 ; return to BANK0
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 77201ASP
Lab QuestionsQuestion:
Like Timer1, does Timer2 keep running during Interrupt latency?
Answer:Yes it does!
Question: Does the user have to account for the free running Timer2 in order to ensure a precise interrupt period?
Answer:No, Interrupt occurs on match not overflow
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 78201ASP v8.0 January 2007
Capture/Compare/PWM Module
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 79201ASP
Capture/Compare/PWM (CCP) Overview
Capture– Times the duration of an external event using an
input pinCompare– Changes an output pin or generates an interrupt
when a specific amount of time has passedPulse Width Modulation (PWM)– Creates a reconfigurable, steady duty-cycle, square
wave output at a defined frequency– Provides enhanced features for various bridge
connectivity
* Module interfaces with Timers 1 and 2
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 80201ASP
Capture/Compare/PWM (CCP) Overview
Capture– Times the duration of an external event using an
input pinCompare– Changes an output pin or generates an interrupt
when a specific amount of time has passedPulse Width Modulation (PWM)– Creates a reconfigurable, steady duty-cycle, square
wave output at a defined frequency– Provides enhanced features for various bridge
connectivity
* Module interfaces with Timers 1 and 2
Timer 2PWMTimer 1CompareTimer 1Capture
Timer ResourceCCP MODE
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 81201ASP
CCP Control Registers
These PWM output configuration bits are available for Enhanced CCP (ECCP) modules only. They provide half-bridge or full-bridge output steering control.
P1M<1:0>
PWM duty cycle 2 LSB’s (8 MSB’s located in CCPR1L)CCP1<X:Y>
CCP Mode Select Bits configure the module as Input Capture, Output Compare, or PWMCCP1M<3:0>
FUNCTIONBIT
CCP1 Control Register (CCP1CON)P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 82201ASP
These PWM output configuration bits are available for Enhanced CCP (ECCP) modules only. They provide half-bridge or full-bridge output steering control.
P1M<1:0>
PWM duty cycle 2 LSB’s (8 MSB’s located in CCPR1L)CCP1<X:Y>
CCP Mode Select Bits configure the module as Input Capture, Output Compare, or PWMCCP1M<3:0>
FUNCTIONBIT
CCP1 Control Register (CCP1CON)
PWM modexx11
Compare mode, trigger special event1101
Compare mode, generate software interrupt on match0101
Compare mode, clear output on match1001
Compare mode, set output on match0001
Capture mode, every 16th rising edge1110
Capture mode, every 4th rising edge0110
Capture mode, every rising edge1010
Capture mode, every falling edge0010
Unused (reserved)1100
Compare mode, toggle output on match0100
Unused (reserved)1000
Capture/Compare/PWM off (resets CCP module)0000
CCP Mode SelectedCCPxM0CCPxM1CCPxM2CCPxM3
P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0
CCP Control Register
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 83201ASP
CCPx
Capture Mode
TMR1H TMR1L
CCPRxH CCPRxL
Prescaler÷1, 4, 16
Edge Detectand
System Clock (Fosc)
P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0
CCPxCON
CCPxIF in PIRx
Single Buffered
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 84201ASP
CCPx
Capture Mode
TMR1H TMR1L
CCPRxH CCPRxL
Prescaler÷1, 4, 16
Edge Detectand
System Clock (Fosc)
P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0
CCPxCON
CCPxIF in PIRx
Single Buffered
MODECCPxM0CCPxM1CCPxM2CCPxM3
Capture every 16th rising edge1110Capture every 4th rising edge0110
Capture every rising edge1010
Capture every falling edge0010
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 85201ASP
Capture InitializationTMR1H
TMR1ON
CCP1IF
TMR1L0000000 0
0000000 0
PIR10
CCP1CON
T1CON
00000 0
1
TIMER1 INCREMENTING!!
00
0
CCPR1H
CCPR1L
11
1
Rising Edge Detected!!
Current Timer1 Value
Captured!
;Turn off CCP modulebanksel CCP1CONclrf CCP1CON
;Make sure Timer1 is offbcf T1CON,TMR1ON
;Clear Timer1 registersclrf TMR1Hclrf TMR1L
;Disable all interrupts for CCPbcf PIR1,CCP1IFbanksel PIE1bcf PIE1,CCP1IE
;Set CCP1 pin for inputbsf TRISC,2
;Set Capture for every 4th rising edgebanksel CCP1CONmovlw b’00000110’movwf CCP1CON
;Start Timer1 incrementingbsf T1CON,TMR1ON
;Test the interrupt flag for capturebtfss PIR1,CCP1IFgoto $-1
CCP1Pin011111st2nd3rd4th
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 86201ASP
YESYES CCPx
Special Event Trigger
Compare ModeCCPxIF in PIRx
OUTPUTLOGIC
OUTPUTLOGIC
P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0
TMR1H TMR1L
COMPARATORDoes TMR1H:TMR1L = CCPRxH:CCPRxL
??
COMPARATORDoes TMR1H:TMR1L = CCPRxH:CCPRxL
??
NO
CCPRxH CCPRxL
CCP1CON
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 87201ASP
YESYES CCPx
Special Event Trigger
Compare ModeCCPxIF in PIRx
OUTPUTLOGIC
OUTPUTLOGIC
P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0
TMR1H TMR1L
COMPARATORDoes TMR1H:TMR1L = CCPRxH:CCPRxL
??
COMPARATORDoes TMR1H:TMR1L = CCPRxH:CCPRxL
??
NO
CCPRxH CCPRxL
MODECCPxM0CCPxM1CCPxM2CCPxM3
Trigger special event (CCPxIF is set, CCP1 resets TMR1 or TMR2 and starts an A/D conversion if
enabled)
1101
Generate software interrupt on match (CCPxIF is set CCP1 pin unaffected)0101
Clear output on match (CCPxIF is set)1001
Set output on match (CCPxIF is set)0001
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 88201ASP
Compare InitializationTMR1H
TMR1ON
CCP1IF
TMR1L0000000 0
0000000 0
PIR10
CCP1CON
T1CON
00000 0 0
TIMER1 INCREMENTING!!CCPR1H
CCPR1L0000000 0
000000 0
0
0
1
1
1
TMR1H:TMR1L = 1000 0000 0000 0000(CCPR1H:CCPR1L Value)
1
;Turn off the CCP modulebanksel CCP1CONclrf CCP1CON
;Turn off Timer1bcf T1CON,TMR1ON
;Clear Timer1 result registersclrf TMR1Hclrf TMR1L
;Disable CCP1 interrupt and make sure ;its flag is clear
banksel PIE1bcf PIE1,CCP1IEbanksel PIR1bcf PIR1,CCP1IF
;Make CCP1 pin outputbanksel TRISCbcf TRISC,2
;Initialize Compare to set output on matchbanksel CCP1CONmovlw b’00001000’movwf CCP1CON
;Load Compare value into CCPR1H:CCPR1Lbanksel CCPR1Hmovlw b’10000000’movwf CCPR1Hclrf CCPR1L
;Start Timer1 incrementingbsf T1CON,TMR1ON
;Test CCP1IF for Timer1 match with CCPR1xbtfss PIR1,CCP1IFgoto $-1
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 89201ASP
PWM Mode
Generates a Pulse-Width Modulated (PWM) signal on the CCP1 and CCP2 pins
Duty cycle, period and resolution determined by the following registers
Period RegisterPR2Timer2 ControlT2CON2 Duty Cycle RegistersCCPRxL2 CCP Control RegistersCCPxCON
DescriptionRegister
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 90201ASP
PWM Block Diagram
CCPR1L CCP1<X:Y>
CCP1 pin
CCPR1H LATCH
TMR2 incrementing
PR2
Latch
CCP1 Output PinCOMPARATOR
COMPARATORTMR2 = PR2
DUTY CYCLE VALUE
TMR2 = CCPR1H
DOUBLEBUFFER
R
S
8
8
(1)
Note (1): TMR2 is concatenated with the2-bit FOSC, or 2-bits from Prescalerto create 10-bit time base
10
10
10
Period 1
10
Period Start
TMR2 Reset to 0’sTMR2 Reset to 0’s
TMR2 = PR2
DUTY CYCLE VALUE
TMR2 = CCPR1H
0
TMR2 = PR2
Period 2
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 91201ASP
PWM Initialization
PR210 1 1 1 1 1 1
CCP1CON
0 0 0 0 0PWM Mode
CCP1M <3:0>duty cycle
LSBsCCP1<X:Y>
CCPR1L10 0 0 1 1 1 1
TMR2
000 0 0000
111
T2CON
1
TMR2ON
0 0 0 0 0 0 0Prescaler bitsTOUTPS<3:0>
Prescaler bitsT2CKPS<1:0>
;Turn off CCP1 pin by setting TRISC bit HIGHbanksel TRISCbsf TRISC, 2 ;configure pin as input
;Clear Timer2banksel TMR2clrf TMR2
;Set up Period and Duty Cyclemovlw b’01111111’ ;movwf PR2 ;Load a Period Valuemovlw b’00011111’ ;movwf CCPR1L ;Load Duty Cycle Value
;Configure CCP module for PWM;and LSB’s of Duty Cycle = b’10’movlw b’00101100’movwf CCP1CON
;Turn CCP1 pin back on (make it an output)banksel TRISCbcf TRISC,2
;Start the PWM by turning on Timer2;Configure Prescaler and Postscaler to 1:1)movlw b’00000100’movwf T2CON
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 92201ASP v8.0 January 2007
Pulse Width Modulation(PWM) Lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 93201ASP
PWM Lab Objectives
Become familiar with the CCP module configuration and operation in PWM mode
Gain additional exposure to Timer2 configuration
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 94201ASP
PWM Lab Overview
The PWM waveform is output on the CCP1 pin (RC2) that will emit a tone on the PICdem2 plus onboard buzzer.
When the lab is completed, a 50% duty cycle at a period of 256/(Fosc/4) will drive the buzzer.
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 95201ASP
PWM Lab Overview
Load PR2 value
Set up RC2 as output pin
Load CCPR1L for 50% duty cycle
Configure CCP as 8-bit PWM
NOP
Turn on Timer2 w/ 1:1 pre scaler
Main Code
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 96201ASP
PWM Lab Specifics
Code for the lab is inC:\RTC\201_ASP\Lab4-PWM
Complete the following sections– Configure PORTC pin 2 ( CCP1) as an output– Set CCP in PWM mode– Clear CCP1X and CCP1Y (8-bit PWM)– Configure Timer2 with 1:1 pre-scaler
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 97201ASP
What you need to know
The code to load PR2 (Timer2) and to set a 50% duty cycle has been provided. These values can be seen in the code
The CCP1 pin is RC2 (Pin 2 of PORTC) on the PIC16F877
Registers needed to complete this lab are:– TRISC– T2CON– CCP1CON
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 98201ASP
PWM Lab Solution;*****************************************************************; Set CCP1 as an output;*****************************************************************
bcf TRISC,2 ; ### config CCP1 pin PORTC<2> as output
bcf STATUS,RP0 ; point to BANK0movlw 0x80 ; establish duty cycle @ 50%movwf CCPR1L
;*****************************************************************; Put CCP1 module in PWM mode.;*****************************************************************
movlw 0x0C ; ### configure CCP for PWMmovwf CCP1CON ; ###
;*****************************************************************; Configure Timer2 pre and post scale of 1:1 and turn Timer2 on;*****************************************************************
bsf T2CON,TMR2ON ; ### turn on TMR2
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 99201ASP
PWM Lab Questions
Question:Why didn’t we have to enable the interrupts for the PWM to work?
Answer:PWM will run concurrently with the PICmicro MCU without slowing the processor down
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 100201ASP v8.0 January 2007
Output Compare Lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 101201ASP
Output Compare Lab
Goals of the lab are to gain experience with the following:– Setting up the CCP for Output Compare– Configure the Special Event Flag to reset Timer1– Configure the CCP to generate an Interrupt on
Timer1 overflow– Using an Interrupt Vector to modify the interval
between Interrupts
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 102201ASP
Compare Lab OverviewThis lab configures the CCP into output compare mode driven by Timer1
An Interrupt is used to change the sound of the buzzer
During the Interrupt Service Routine (ISR):– The RC2/CCP1 pin (connected to buzzer) is toggled
– The ISR period is reduced:The Compare Register (CCPR1L) is decrementedThe Timer1 count registers are reset
The combination of a reduced period and the CCPR1L roll-over will cause the buzzer to emit a chirping sound
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 103201ASP
Compare Lab Overview
Save Context
Toggle CCP Output Pin
Clear IF
DecrementCCPR1L
Configure CCP as Output Compare
Initialize PORT C
Initialize Timer1
Turn on timer1
NOP
RETFIE
Interrupt Vector Main Program
ResetTimer1
Drives Buzzer
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 104201ASP
Compare Lab SpecificsThe code for this lab is inC:\RTC\201_ASP\Lab5-CCP
Complete the following sections:– Configure the CCP as an Output Compare
that sets the Special Event Flag and CCP1IF– Configure Timer1 with a clock source of
Fosc/4 and a pre-scaler of 1:8– Configure Special Function Registers to
allow the CCP interrupt to occur
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 105201ASP
What you need to know
The registers needed to complete this lab are:– INTCON (Interrupt Control)– T1CON (Timer1 Control)– CCP1CON (CCP1 Control)– PIE1 (Peripheral Interrupt Enable)
The Interrupt Vector has been provided
The Value of CCPR1L will “rollover” from 0 to 0xFF and continue to decrement
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 106201ASP
Compare Lab Solution;; Set CCP1CON to Output Compare mode with Special Event Trigger; to clear the Timer 1 register pair on a match;****************************************************************
movlw 0x0B ; ### value for CCP1CONmovwf CCP1CON ; move to CCP1CON
;; Configure Timer 1 for Fosc/4 operation. 8:1 Prescaler;;****************************************************************
movlw 0x30 ; ### value for TMR1movwf T1CON ; ### move to TMR1 control register
;; Enable Timer 1 interrupts, Peripheral Interrupts and; Global Interrupts;****************************************************************
bsf PIE1,CCP1IE ; ### enable CCP1 interruptbsf INTCON,PEIE ; ### enable peripheral interruptsbsf INTCON,GIE ; ### enable global interrupts
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 107201ASP
Lab QuestionQuestion:
The PWM did not require an interrupt in order to work. Do we need an interrupt to operate in output compare mode?
Answer:Not necessarily
– Peripherals always set their associated interrupt flag, so you have the choice of polling or directly responding to the interrupt.
– The choice is based on the need of your application.
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 108201ASP v8.0 January 2007
Comparators
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 109201ASP
Comparator OverviewComparator Module:– Compares analog input voltage to a reference
and outputs a digital result
Vin
Vout
Vref
Comp
Analog Input(Vin)
Reference Voltage(Vref)
Output(Vout)+
-
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 110201ASP
Comparator Reference VoltageVoltage Reference can be either:– External from a device pin– Internally generated with the Voltage Reference
ModuleProvides 16 selectable voltages from 0 to 75% of VDD
– Some devices can also scale VREF+ and VREF-
Some devices also have a fixed reference (0.6V)– Independent of VDD
VREF+
VDD
VREN
VREF-
8R R R R R
8R
CVREF
VROE
CVREF
To Comparatorsand ADC Module
4 VR<3:0>
15
0
VRSS = 1
VRSS = 0
VRSS = 1
VRSS = 0
VRR
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 111201ASP
Comparator Interrupts
An Interrupt occurs when the comparator output changes– Some devices share one flag for both
comparators– Some devices have independent flags
Must read the comparator output before clearing interrupt flags– Outputs found in the comparator control
register (CMCON or CMxCON0)– Resets the output mismatch condition
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 112201ASP
Comparators and Sleep Mode
Comparators remain active in Sleep– A Comparator output change will wake-up
core
After wake-up, the instruction following the SLEEP instruction or an Interrupt Service Routine (ISR) is executed
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 113201ASP v8.0 January 2007
Analog-to-Digital Converter (ADC)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 114201ASP
ADC Overview
Analog-to-Digital Converter Module– Converts analog input signal into an 8 or 10-bit
binary value– Selectable internal or external reference voltage– Interrupt can be generated after conversion is
completedThe interrupt can wake the PICmicro from SLEEP
ADCAnalogInput
DigitalOutput
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 115201ASP
ADCS1 ADCS0 CHS2 CHS1 CHS0 ADON
ADC Control RegistersThe ADC implements two control registers– ADCON0 and ADCON1– Devices with > 8 analog inputs do not have same bits
shown below
ADC Control Register 0 (ADCON0)
A/D Conversion Clock Select bitsUse with ADCS2 in ADCON1
ADCS<1:0>
Analog Channel Select bitsCHSx bits
1 = A/D Conversion in progress0 = A/D Conversion is completed
GO/DONE
Enables the ADC moduleADON
FUNCTIONBIT
GO/DONE
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 116201ASP
ADC Control Registers
ADC Result Registers Format bit 1 = Right Justified, 0 = Left Justified
ADFM
A/D Conversion Clock Select bitUse with ADCS<1:0> in ADCON0
ADCS2
Port Configuration BitsConfigures I/O as analog or digital
PCFG<3:0>
FUNCTIONBIT
ADC Control Register 1 (ADCON1)
The ADC implements two control registers– ADCON0 and ADCON1– Devices with > 8 analog inputs do not have same bits
shown below
ADFM PCFG3 PCFG0PCFG2 PCFG1ADCS2
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 117201ASP
ADC Result Registers
10 bit ADC result in is placed in two registers– ADRESH and ADRESL– Left or Right Justified
Determined by Format Select bit (ADFM) in ADCON1 register
MSB LSB
MSB LSBADRESH
Left Justified (ADFM = 0)
Right Justified (ADFM = 1)
ADRESL
ADRESH ADRESL
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 118201ASP
ADC
ADC Module Diagram
Holding Capacitor
Conversion clock scalerFosc
VREF+pin
VREF-pin
Vss
ADRESH ADRESL
ADCON0ADCS1 ADCS0 CHS2 CHS1 CHS0 ADONGO/DONE
ADCON1ADFM PCFG3 PCFG1 PCFG0PCFG2ADCS2
Conversion CompleteStart Conversion
AN0AN1AN2AN3AN4AN5AN6AN7
Left Justified Right Justified
0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 119201ASP
ADC
ADC Module Diagram
Holding Capacitor
Conversion clock scalerFosc
VREF+pin
VREF-pin
Vss
ADRESH ADRESL
ADCON0ADCS1 ADCS0 CHS2 CHS1 CHS0 ADONGO/DONE
ADCON1ADFM PCFG3 PCFG1 PCFG0PCFG2ADCS2
Conversion CompleteStart Conversion
0 0 0
AN0AN1AN2AN3AN4AN5AN6AN7
01
Left Justified Right Justified
Port Config Bits
10
0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1
VddAN7 AN6 AN5 AN4 AN1 AN0AN3 AN2PCFG <3:0>
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 120201ASP
Timing Considerations for ADC
When an A-to-D channel is selected time must be taken for the holding capacitor to charge
All 10 bit conversions take 11 cycles to complete
User must select the appropriate ADC clocking based on the system clock frequency
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 121201ASP v8.0 January 2007
Analog-to-DigitalConversion LAB
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 122201ASP
ADC Lab
This Lab will familiarize you with:– Setting up the ADC module
– Operating a peripheral from the “Main” program, not an interrupt vector
– Using the value read from one peripheral (ADC) to drive another peripheral (CCP in PWM mode)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 123201ASP
ADC Lab Overview
Configure Timer 2
Configure and Turn on ADC
Configure CCP forPWM
Configure PORT C
Enable interrupts
Main Program
Continued on next page
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 124201ASP
ADC Lab Overview (cont.)
Output 4 LSBs ofADC value to LEDs
Start ADC
Put ADC value inCCPR1L
ADC done?
TMR2IF=1Main Loop NO
YES
NO
YES
Continued fromPrevious Page
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 125201ASP
ADC Lab Specifics
Complete the following sections of code in the project C:\RTC\201_ASP\Lab6-ADC– Configure the ADC to return a left justified
value
– Set ADC Conversion Clock to FOSC/32
– Turn on ADC unit
– Complete the code to start an ADC and wait for the conversion to finish in the main control loop
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 126201ASP
What you need to know
This lab does not do the ADC conversion in an interrupt routine. We will use a polling method.
Writing the value of the ADC conversion into CCPR1L will change the duty cycle of the buzzer
ADCON1 and ADCON0 special function registers are used to complete this lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 127201ASP
ADC Solution;*************************************************************************; Configure ADC: Channel 0, left justified, Tad = 8 * Tosc, turn on ADC;*************************************************************************
clrf ADCON0 ; ### ensure default channel is set to channel 0bsf ADCON0,ADCS1 ; ### set Tad = Fosc/4bsf ADCON0,ADON ; ### turn on ADCbsf STATUS,RP0 ; ### point to BANK1movlw 0x0E ; ### left justify, configure AN0 analogmovwf ADCON1
;; Enable Timer 2 interrupts, Peripheral Interrupts and Global Interrupts;
bsf PIE1,TMR2IE bsf INTCON,GIEbsf INTCON,PEIEbcf STATUS,RP0 ; return to BANK0
;;*************************************************************************; add three lines of code to start the ADC conversion and wait for the; conversion to complete;*************************************************************************
bsf ADCON0,GO ; ### start ADC conversionbtfsc ADCON0,GO ; ### Is the conversion done?goto $-1 ; ### no: loop until done
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 128201ASP
ADC Lab Question
Question:Instead of waiting for TMR2IF to be set in the main program, could we start the ADC from within an interrupt routine?
Answer:YES
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 129201ASP v8.0 January 2007
ADDRESSABLE Universal Synchronous Asynchronous
Receiver Transmitter (AUSART)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 130201ASP
AUSART OverviewSerial I/O communications peripheral – Sometimes called Serial Communications
Interface (SCI)Main Functions:– Can be synchronous or asynchronous – Can receive and transmit
Full-duplex asynchronous transmit and receiveHalf-duplex synchronous master and slave
Most common use– RS-232 communications to a PC serial port
Needs driver for RS-232 level shifterEnhanced (EUSART) features allow interface with a Local Interconnect Network (LIN) bus system
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 131201ASP
AUSART RegistersBaud rate generator registers– SPBRG (8 bit for AUSART)– SPBRG and SPBRGH (16 bit for EUSART)
Transmit status and control– TXSTA
Receive status and control– RCSTA
Transmit data register– TXREG
Receive data register– RCREG
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 132201ASP
TXSTA Register
FunctionBitClock Source Select
1 = Master Mode (clock generated internally from BRG)0 = Slave Mode (clock from external source)
CSRC
CSRC TX9 TXEN SYNC SENB BRGH TRMT TX9D
Ninth bit transmission enableTX9
Transmit Enable bit, 1 = Tx enabled, 0 = Tx disabledTXENAUSART Mode , 1 = Synchronous Mode, 0 = Asynchronous ModeSYNCFor EUSART only
1 = Send sync break character bit0 = Sync break transmission is completed
SENB
Baud Rate Select, 1 = High Speed, 0 = Low SpeedBRGHTransmit Shift Register (TSR) status
1 = TSR empty, 0 = TSR is fullTRMT
Ninth bit of transmit dataTX9D
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 133201ASP
RCSTA Register
FunctionBitSerial Port Enable
1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins)0 = Serial port disabled
SPEN
SPEN RX9 SREN CREN ADDEN FERR OERR RX9D
1 = Enable 9-bit data reception, 0 = 8-bit dataRX9
Synchronous mode (Master), 1 = enable single Rx, 0 = disable single RxSRENContinuous Receive Enable, 1 = enable, 0 = disableCRENAddress Detect Enable bit
1 = enable (enable interrupt and load the Rx buffer when RSR<9> is set)0 = disable and use 9th bit for parity
ADDEN
1 = framing error occurred (Stop bit not detected)FERR
1 = Overrun error occurred (FIFO was still full when other data was loaded)
OERR
Ninth bit of received dataRX9D
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 134201ASP
TX9D
SPEN
Transmit Block Diagram
Baud RateGenerator
TXEN MSB LSB
TXREG
Transmit Shift Register (TSR)
TX9
DATA BUS
TXIFInterrupt
TXIE
Pin Bufferand Control
TRMT
Set TXIF Clear TXIF
Enables SerialPort
Set TRMT bitIndicates shift register is empty
Clear TMRT bitTSR has data in it
Ninth data bit
TX/DTpin
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 135201ASP
Receive Block Diagram
Pin Bufferand Control
SPEN
DataRecovery
Baud RateGenerator
STOP START
RX9
Data Bus
RX9DRCIE
Interrupt
RCREG
Receive Shift Register (RSR)RX/DTpin
FIFO
STOP START
Set RCIF flagClear RCIF flag
Enable Serial Port
RCIF
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 136201ASP v8.0 January 2007
MASTER SYNCHRONOUSSERIAL PORT (MSSP)
MODULE
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 137201ASP
MSSP OverviewThe MSSP module can operate in one of two modes:– SPI (Serial Peripheral Interface)
3 pins are used– Serial Data Out (SDO)– Serial Data In (SDI)– Serial Clock (SCK)
– I2C (Inter-Integrated Circuit)Full Master modeSlave mode (with general address call)2 pins are used
– Serial Clock (SCL)– Serial Data (SDA)
The MSSP Control Register (SSPCON) determines which mode you are in.
We will cover I2C mode only
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 138201ASP
Conditions :– START (S)
– STOP (P)
– ACKNOWLEDGE (A)
– RESTART (R)
– NEGATIVE or NOT-ACKNOWLEDGE (N)
I2C Conditions
SDA
SCL
SDA pulled LOWwhile SCL is still HIGH
SDA releasedwhile SCL is still HIGH
SDA goes LOW during9th clock pulse of SCL
Stop condition quickly followedby a Start conditionRecipient does not drive SDALOW
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 139201ASP
EEPROM
External IC EEPROM Read
PIC
SCL
SDA
LISTEN LISTEN LISTEN
READMODEGOTO
ADDRESSSTOPDATA
MASTER
SLAVESSTART DATASLAVEADDRESS
BUSY BUSY
WRITEMODE
ACKEEPROMMEMORYADDRESS
RESTARTNACKSTOP
+5V
ACK
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 140201ASP
MSSP Control Registers(I2C mode)
Slew Rate Control bitSMPNot used in I2C modeCKELast byte Rx/Tx was data or addressD/A
SMP CKE D/A P S R/W UA BF
CONTROL BITS DETECTION BITS (FLAGS)
Stop Condition DetectedPStart Condition DetectedSSlave :READ/WRITE or Master = transmit in progressR/WAddress needs to be updatedUAThe SSPBUF register is fullBF
FUNCTIONBIT
1 of 3: MSSP Status Register (SSPSTAT)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 141201ASP
MSSP Control Registers(I2C mode)
Slew Rate Control bitSMPNot used in I2C modeCKE
Last byte Rx/Tx was data or addressD/A
SMP CKE D/A P S R/W UA BF
CONTROL BITS DETECTION BITS (FLAGS)
Stop Condition DetectedPStart Condition DetectedS
Slave :READ/WRITE or Master = transmit in progressR/WAddress needs to be updatedUAThe SSPBUF register is fullBF
FUNCTIONBIT
1 of 3: MSSP Status Register (SSPSTAT)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 142201ASP
WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0
Write Collision DetectedWCOL
Enables clockCKP
A write to the SSPBUF before previous value processedSSPOVEnables MSSP moduleSSPEN
Mode Select BitSSPM3SSPM2SSPM1SSPM0
FUNCTIONBIT
Mode Select bits
MSSP Control Registers (I2C mode)
2 of 3: MSSP Control Register 1 (SSPCON)
CONTROL BITS DETECTION BITS (FLAGS)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 143201ASP
WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0
Write Collision DetectedWCOL
Enables clockCKP
A write to the SSPBUF before previous value processedSSPOVEnables MSSP moduleSSPEN
Mode Select BitSSPM3SSPM2SSPM1SSPM0
FUNCTIONBIT
Mode Select bits
MSSP Control Registers (I2C mode)
2 of 3: MSSP Control Register 1 (SSPCON)
CONTROL BITS DETECTION BITS (FLAGS)
I2C Slave mode, 10-bit address with Start and Stop bit interrupts enabled
1111
I2C Slave mode, 7-bit address with Start and Stop bit interrupts enabled
0111Reserved1011Reserved0011I2C firmware controlled Master mode (Slave idle)1101Reserved0101Reserved1001I2C Master mode, clock = FOSC / (4 * (SSPADD+1))0001I2C Slave mode, 10-bit address1110I2C Slave mode, 7-bit address0110
SPI Slave mode, clock = SCK pin, SS pin control disabled, SS can be used as I/O pin
1010SPI Slave mode, clock = SCK pin, SS pin control enabled0010SPI Master mode, clock = TMR2 output/21100SPI Master mode, clock = FOSC/640100SPI Master mode, clock = FOSC/161000SPI Master mode, clock = FOSC/40000ModeSSPM0SSPM1SSPM2SSPM3
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 144201ASP
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN
Generates an interrupt when a call is received (slave mode)GCEN
Initiate ACK/NACK condition (Transmits ACKDT bit) ACKEN
0 = Acknowledge received from slave (transmit mode)ACKSTAT0 = ACK 1 = NACK (receive mode)ACKDT
Enables receive modeRCENInitiates a STOP conditionPEN
Initates a START conditionSENInitiates a RESTART conditionRSEN
Initiates a START conditionSEN
FUNCTIONBIT
MSSP Control Registers(I2C mode)
3 of 3: MSSP Control Register 2 (SSPCON2)
CONTROL BITS DETECTION BITS (FLAGS)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 145201ASP
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN
Generates an interrupt when a call is received (slave mode)GCEN
Initiate ACK/NACK condition (Transmits ACKDT bit) ACKEN
0 = Acknowledge received from slave (transmit mode)ACKSTAT0 = ACK 1 = NACK (receive mode)ACKDT
Enables receive modeRCENInitiates a STOP conditionPEN
Initates a START conditionSENInitiates a RESTART conditionRSEN
Initiates a START conditionSEN
FUNCTIONBIT
MSSP Control Registers(I2C mode)
3 of 3: MSSP Control Register 2 (SSPCON2)
CONTROL BITS DETECTION BITS (FLAGS)
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 146201ASP
Tx/Rx Buffer (SSPBUF)
Buffer register containing Tx and Rx data– SSPBUF interfaces to a shift register (SSPSR) for
shifting data in or out
When full, the Buffer Full (BF) bit in the SSPSTAT register is set
Any write to the SSPBUF register during Tx/Rx of data will be ignored, and the write collision detect bit (WCOL) of the SSPCON register will be set
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 147201ASP
I2C Address Register (SSPADD)
Slave mode:– Contains the slave address of the PIC– Compared against the received value
Master mode:– Used to calculate the clock speed
(BAUD rate) of the I2C system.
)1(4 +× SPADDFosc
BAUD RATE =
*NOTE: FOSC is the frequency of the oscillator not the Instruction Clock TCY
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 148201ASP
MSSP Interrupts
The MSSP interrupt flag (SSPIF) is set in the PIR1 register with the following events:– START condition– STOP condition– Tx or Rx complete– Acknowledge transmit– RESTART condition
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 149201ASP v8.0 January 2007
I2C Based Temp Sensor Lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 150201ASP
I2C Based Temp Sensor Lab Objective
Configure some MSSP control registers to enable I2C communication to the I2C based Temp sensor on the PICDEM 2 Plus board.
Temperature reading (lowest 4 bits) will be displayed on the LEDs.
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 151201ASP
I2C Lab Overview
This lab configures the MSSP as an I2C Master
The TC74 Temperature Sensor is then read by the MSSP module
The temperature reading is then sent to PORTB to be displayed on the 4 LEDs
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 152201ASP
I2C Lab Overview
Configure I/0s
Configure MSSP
Initiate I2C start condition
Send Temp Sensor Address
Read Temperature
Main Code
Display Temp LSB on PORTB LEDs
Loop
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 153201ASP
I2C Lab SpecificsCode for the lab is inC:\RTC\201_ASP\Lab7-I2C
Complete the following sections:– Disable the slew rate control
We’ll be using I2C standard rate (100KHz)
– Configure the MSSP to operate as an I2C master and enable the data (SDA) and clock (SCL) pins
– Start the data transfer and check for when it has completed
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 154201ASP
What you need to knowSlew rate control is found in the SSPSTAT register
Registers needed to complete this lab are:– SSPSTAT– SSPCON– SSPCON2
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 155201ASP
I2C Lab Solution;--------------------------------------------------------------; set the slew rate and baud rate for 100 MHZ operation
BANKSEL SSPSTAT ; ### point to correct BANK for SSPSTATbsf SSPSTAT,SMP ; ### Set for standard speed slew rate
;--------------------------------------------------------------; Configure as I2C master with Fosc/4 Clock source
BANKSEL SSPCONbsf SSPCON,SSPM3 ; ### set to I2C master mode with
; Fosc/4 clock sourcebsf SSPCON,SSPEN ; ### Enable SDA and SCL pins to
; operate in I2C mode
;--------------------------------------------------------------
BANKSEL SSPCON2 ; Initiate a START conditionbsf SSPCON2,SEN ; ### set the SEN bitbtfsc SSPCON2,SEN ; ### is it finished?goto $-1 ; no: test again
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 156201ASP v8.0 January 2007
Multiple InterruptLab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 157201ASP
Multiple Interrupts Lab
This Lab involves:
– Dealing with 2 (or more) concurrent interrupts
– Determining the source of an interrupt
– Deciding which interrupt request will be serviced first
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 158201ASP
Lab Overview
Setup PORTB and enable External Interrupts on
“S3”as in Lab 1
Enable Timer1 and PORTC as In Lab 6
Set up CCP as Output Compare just as in Lab 6
Main Program
Continued on next slideNOP
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 159201ASP
Lab OverviewInterrupt Service Routines
Toggle variableCalled
“push_flag”
Clear IF
Clear IF
Call “debounce”Delay routine
Put -1 in WREG
Put 0 in WREG
Add WREG to CCPR1L
push_flagSet ?
INT_ISR CCP_ISR
Return to Main
Return to Main
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 160201ASP
Lab Overview (cont.)
Did CCP generate the interrupt?
Did INT generate the interrupt?
Go to CCP service routine Service External
Interrupt
Interrupt HandlerSave
context
YES
YES
NO
NO
Return to Main
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 161201ASP
Lab SpecificsLab is found in:– C:\RTC\201_ASP\Lab8-MXINT
The two Interrupt Service Routines (ISRs) are provided:– INT_ISR– CCP_ISR
Complete the following sections of code– When an interrupt occurs, determine the cause
and transfer control to the appropriate ISR– Set the Special Function Registers (SFRs) to
enable INT and CCP1 Interrupts to occur
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 162201ASP
What you need to know for Lab
INTCON, and PIR Special Function Registers are used in this lab
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 163201ASP
Lab Solution
Int_Service_Routine
call save_regs; ; save W, STATUS, & PCLATH
btfsc INTCON,INTF ; ### test for INTE interrupt request
goto INTE_ISR
btfsc PIR1,CCP1IF ; ### test for CCP interrupt request
goto CCP_ISR
Finish_Int ; restore W, STATUS & PCLATH
call Restore_Regs
retfie
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 164201ASP
Lab Solution ( cont.)
bsf PIE1,CCP1IE ;### enable CCP1 interrupt
bsf INTCON,INTE ;### enable INTE interrupt
bsf INTCON,GIE ;### enable global interrupts
bsf INTCON,PEIE ;### enable peripheral interrupts
bcf STATUS,RP0 ; return to BANK0
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 165201ASP
Lab QuestionsQuestion:
Why is there a noticeable silence when S3 is pushed?
Answer:Since “debounce” is called during an interrupt and the GIE bit is cleared, the CCP1 interrupt that toggles the buzzer is not allowed to operate. Therefore, the buzzer goes quiet.
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 166201ASP
Lab Questions (cont.)
Question: How can this silence be eliminated and the buzzer continue to run?
Answer:1. Capture S3 in “Main” and call “debounce”
while GIE is set2. Use a timer to accomplish the delay3. Re-enable interrupts during the INT ISR
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 167201ASP v8.0 January 2007
201ASP Wrap-Up
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 168201ASP
Peripherals Class Wrap-upToday we covered the following peripherals on the Mid-Range family– I/O ports– Interrupt structure and processing– Timers (timer0, timer1, timer2)– CCP Module ( Output Compare, Input Capture,
PWM)– Comparators and Analog-to-Digital Converters
Voltage Reference– AUSART – Serial Port– I2C using the MSSP module
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 169201ASP
Final WordThis discussion has followed the standard Microchip datasheet flow:
Overview of Peripheral
Register Description and Configuration
Enhanced or Special Features
*Packaging and Electrical Specifications are at the end of the datasheet
Use these sections to:• Develop logical flow charts or
pseudo-code (Avoid Spaghetti Programming!!)
Other Tips:• Comment your code thoroughly• Choose descriptive names
for user defined registers
© 2007 Microchip Technology Incorporated. All Rights Reserved. Slide 170201ASP
Resources
Visit www.microchip.com for:– 24/7 technical support– Application Notes– Web Seminars– Code examples– Datasheets– and Much More!
© 2006 Microchip Technology Incorporated. All Rights Reserved. Slide 171201ASP v8.0 January 2007
Thank You!!