8051 TIMER/ Counter
Programming
1
• The 8051 has two timers/counters used as
• Timers to generate a time delay
• Event counters to count events happening outside the
microcontroller
• Timer 0 and Timer 1 are 16 bits wide
• each 16-bit timer is accessed as two separate registers of low
byte and high byte.
2
Timer 0 registers
◦ Low byte register →TL0 and high byte register →TH0
◦ They can be accessed like any other register, such as A,
B, R0, R1, R2, etc.
3
❑ Both timers 0 and 1 use the same register,
called TMOD (timer mode), to set the various
timer operation modes
❑ TMOD is a 8-bit register
➢ The lower 4 bits are for Timer 0
➢ The upper 4 bits are for Timer 1
➢ In each case,
▪ The lower 2 bits are used to set the timer mode
▪ The upper 2 bits to specify the operation
4
TMOD Register
5
6
Clock source for timer
◦ Timer needs a clock pulse to tick
◦ If C/T = 0, the crystal frequency is the source of the
clock for the timer
◦ Frequency for the timer is always 1/12th the frequency
of the crystal attached to the 8051
◦ XTAL = 11.0592 MHz allows the 8051 system to
communicate with the PC with no errors
7
8
❑ Timers of 8051 do starting and stopping by
either software or hardware control
➢ In using software to start and stop the timer where
GATE=0
▪ The start and stop of the timer are controlled by way of
software by the TR (timer start) bits TR0 and TR1
– The SETB instruction starts it, and it is stopped
by the CLR instruction
– These instructions start and stop the timers as long
as GATE=0 in the TMOD register
➢ The hardware way of starting and stopping the
timer by an external source is achieved by making
GATE=1 in the TMOD register
9
Bit Addressable
TCON Register Register
10
Mode 1 programming
◦ 16-bit timer, values of 0000 to FFFFH
◦ TH and TL are loaded with a 16-bit initial value
◦ Timer started by "SETB TR0" for Timer 0 and "SETB TR1" for
Timer 1
◦ Timer count till FFFFH and rolls over from FFFFH to 0000H
◦ Sets TF (timer flag) in TCON
◦ When this timer flag is raised, the timer can be stopped with
"CLR TR0" or "CLR TR1“
◦ After the timer reaches its limit and rolls over, the registers TH
and TL must be reloaded with the original value and TF must
be reset to 0
11
12
13
14
15
16
17
18
19
20
21
22
Finding values to be loaded into the timer
23
24
25
26
27
Generating a large time delay
28
Mode 0 programming
• Mode 0 is exactly like mode 1 except that it is
a 13-bit timer instead of 16-bit.
• The 13-bit counter can hold values between
0000 to 1FFFH in TH - TL.
• When the timer reaches its maximum of
1FFH, it rolls over to 0000, and TF is raised.
29
Mode 2 programming
30
31
32
33
34
35
36
COUNTER PROGRAMMING
when C/T = 1, the timer is used as a
counter and gets its pulses from
outside the 8051.
37
Timer 1 as an event counter where it counts up as clock pulses are fed into pin 3.5
38
39
40
Write a program to continuously generate a square
wave of 2 kHz frequency on pin P1.5 using timer 1.
Assume the crystal oscillator frequency to be 12 MHz.
41
42