Counter/Timer Programming in The 8051
Counter/Timer Programming in The 8051
Counter/Timer Programming in The 8051
8051
1
Timers /Counters
P2 P1 to
Set LCD
Timer 0 TH0
TL0
3
Counter
5
Basic Registers of the Timer
6
Timer Registers
TH0 TL0
Timer 0
TH1 TL1
Timer 1
7
TMOD Register
(MSB) (LSB)
GATE C/T M1 M0 GATE C/T M1 M0
Timer 1 Timer 0
8
TMOD Register
(MSB) (LSB)
GATE C/T M1 M0 GATE C/T M1 M0
Timer 1 Timer 0 9
C/T (Clock/Timer)
10
Gate
11
M1, M0
Indicate which mode and which timer are selected for each of the
following.
(a) MOV TMOD,#01H (b) MOV TMOD,#20H
(c) MOV TMOD,#12H
Solution:
timer 1 timer 0
XTAL
oscillator
÷ 12
Solution:
(MSB) (LSB)
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Timer 1 Timer0 for Interrupt
16
TCON Register (2/2)
(MSB) (LSB)
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Timer 1 Timer0 for Interrupt
17
Timer Mode 0
18
Mode 0 Programming
XTAL
oscillator
÷ 12 MC
C/T = 0
TH-8bit TL-5bit TF
Start timer
TF goes high overflow
TR when FFFF 0 flag
19
Timer Mode 1
XTAL
oscillator
÷ 12 MC
C/T = 0
22
Steps of Mode 1 (2/3)
TR0=1 TR0=0
Start timer TH0 TL0
Stop timer
TF = 0 TF = 0 TF = 0 TF = 0 TF = 1
• 8-bit timer.
– It allows only values of 00 to FFH to be loaded into TH0.
• Auto-reloading
• TL0 is incremented continuously when TR0=1.
25
Mode 2 programming
XTAL
oscillator
÷ 12
C/T = 0
overflow
TL TF flag
reload TF goes high
TR TH when FF 0
26
Steps of Mode 2 (1/2)
Solution:
(a) First notice that target address of SJMP. In mode 2 we do not
need to reload TH since it is auto-reload.
Half period = (FFH – 05 +1) × 1.085 s = 272.33 s
Total period = 2 × 272.33 s = 544.67 s
Frequency = 1.83597 kHz.
(b) To get the smallest frequency, we need the largest period and
that is achieved when TH = 00.
Total period = 2 × 256 × 1.085 s = 555.52 s
Frequency = 1.8kHz.
29
Section 2
Counter Programming
30
Counter
31
Table 9-1: Port 3 Pins Used For Timers 0 and 1
(MSB) (LSB)
GATE C/T=1 M1 M0 GATE C/T=1 M1 M0
Timer 1 Timer 0
32
Counter Mode 1
overflow
Timer 0 flag
external TH0 TL0 TF0
input
Pin 3.4
TF0 goes high
C/T = 1 TR0 when FFFF 0
34
Figure 9-5. (b) Timer 1 with External Input
(Mode 1)
overflow
Timer 1 flag
external TH1 TL1 TF1
input
Pin 3.5
TF1 goes high
C/T = 1 TR1 when FFFF 0
35
Counter Mode 2
• 8-bit counter.
– It allows only values of 00 to FFH to be loaded into TH0.
• Auto-reloading
• TL0 is incremented if TR0=1 and external pulse
occurs.
• See Figure 9.6, 9.7 for logic view
• See Examples 9-18, 9-19
36
Figure 9.6: Counter 0 with External Input
(Mode 2)
overflow flag
Counter
0 TL0 TF0
external
reload
input
Pin 3.4 TR0 TH0
37
Figure 9.7: Counter 1 with External Input
(Mode 2)
overflow flag
Counter
1 TL1 TF1
external
reload
input
Pin 3.5 TR1 TH1
38
Figure 8: Timer/Counter 0
XTAL
oscillator
÷ 12
C/T = 0
C/T = 1
T0 Pin
Pin 3.4 TR0
Gate
INT0 Pin
Pin 3.2
39
Figure 9: Timer/Counter 1
XTAL
oscillator
÷ 12
C/T = 0
C/T = 1
T1 Pin
Pin 3.5 TR1
Gate
INT1 Pin
Pin 3.3
40