Timers & Counters
Timers & Counters
Timers & Counters
Timers.4
Timer 0
Interrupt
bit 5 bit 2
bit 7
IR
PIC16F877
Timers.9
Timer 0
Example - Setup
org 0x000
goto INIT
org 0x004
goto T0_ISR
INIT: clrf STATUS ; access
bsf STATUS,5 ; bank 1 (for OPTION and TRIS)
clrf TRISB, F ; pin 0 (and others) of PORTB: output
movlw B’ 11011111’ ; setup the OPTION register
movwf OPTION_REG
bcf STATUS,5 ; access bank 0
movlw b’00100000’ ; enable the Timer 0 interrupt
movwf INTCON ; clears T0IF also
movlw D’158’ ; initialize the Timer 0 counter
movwf TMR0
bsf INTCON,7 ; enable global interrupts
…
Timers.11
Timer 0
Interrupt – Example – Step 2
MAIN: …
…
goto MAIN
Timers.11
Timer 0
Prescaler
Timers.12
Timer 0
Prescaler - Example
Suppose we want to change our earlier example’s interrupt rate
from 10kHz (= 0.1msec) to 2.5kHz (0.4msec).
Timers.14
Timer 0
Counter Mode of Operation
Timers.15
Timer 0
Counter Mode: Synchronization
Timers.16
Timer 0
Counter Mode of Operation
OPTION_REG
OSC1
CPU
Clock
T0SE = 0:
or PIC16F877
T0SE = 1:
T0CKI
External
Clock
Timers.17
Timer 0
Counter Mode Example
VDD
If button is pushed the
voltage on the T0CKI pin
goes from VDD to VSS.
T0CKI
Timers.18
Timer 0
Counter Mode Example
org 0x000
INIT: clrf TMR0,F ; clear the counter (2TCY inhibit)
clrf STATUS ; access
bsf STATUS,RP0 ; bank 1
movlw B’ 11111111’ ; setup the OPTION register
movwf OPTION_REG
bcf STATUS,RP0 ; access bank 0
MAIN: …
…
…
movf TMR0,W ; read the number of button pushes
…
…
…
Timers.20
Timer 0
Timers.21
Timer 1
• Timer mode:
– a register (TMR1H | TMR1L) will be incremented
every instruction cycle (without prescaler)
• Counter mode:
– a register (TMR1H | TMR1L) will be incremented
every time a rising edge occurs at pin T1CKI
Timers.23
Timer 1
Architecture
Timer Counter
Synchronous Asynchronous
Timers.24
Timer 1
What about reading out the Timer’s 2 Bytes
Oops Oops
Timers.27
Timer 1
Associated Registers
Timers.29
For PIC16F877
(See section 12 of DS)
Timers.30
Timer 1
Example with Interrupt
T1CON:
T1CON: B’ 0 0 1 1 0 1 0 0’
Timers.33
Timer 1
Interrupt – Example – Step 1
org 0x000
goto INIT
org 0x004
goto T1_ISR
INIT: clrf STATUS ; access
bsf STATUS,RP0 ; bank 1
bcf TRISB, 0 ; make pin 0 of PORTB: output
bcf STATUS,RP0 ; access bank 0
; Initialize Timer 1
movlw B’00110100’ ; setup the T1CON register
movwf T1CON ; leave Timer 1 off for now
movlw 0x0B ; Value to load into TMR1H
movwf TMR1H, F ; Write High byte
movlw 0xDC ; Value to load into TMR1L
movwf TMR1L, F
…
Timers.34
Timer 1
Interrupt – Example – Step 1 (Continued)
end
Timers.35
Timer 1
Interrupt – Example – Step 2
MAIN: goto MAIN
Timers.36
Timer 1
Timers.37
Timer 2
• Timer: 8-bit
• With prescaler and postscaler
• Shutdown during SLEEP
Timers.38
Timer 2
Architecture
Timers.39
Timer 2
In PIC16F877
Timers.40