Professional Documents
Culture Documents
8051
Intro
• The 8051 has two timers/counters, they can be
used as:
• Timers to generate a time delay
• Event counters to count events happening outside
the microcontroller
8051 Timers Important Registers and Bits
• Two timers/counters Timer0/Counter0, Timer1/Counter1
• Important registers
• TMOD reg (8-bit) Used for both timer0/timer1 mode settings
• Timer 0 registers
• TLO (8-bit) Timer 0 Low byte reg
• THO (8-bit) Timer 0 High byte reg
• Timer 1 registers
• TL1 (8-bit) Timer 1 Low byte reg
• TH1 (8-bit) Timer 1 High byte reg
• Flags
• TFO Timer 0 flag
• TF1 Timer 1 flag
• Timer Start Bit
• TRO Timer 0 start bit
• TR1 Timer 1 start bit
TLx/THx
Inside
TMOD
•Gate Control
0 = Timer enabled
1 = Timer enabled if INTx is high
•M1-M0:Mode Control
00-Mode 0, 13 bit count mode
01-Mode 1, 16 bit count mode
10-Mode 2, Auto reload mode
11-Mode 3, Split Timer mode
Inside
TMOD
16-Bit
mode
8-bit
Autorelo
adMode
TIMER0 formulas
• Step 2: • Step 2:
Value= 256 – n Value= 65536 – n
xx= binary of “Value” yyxx= binary of “Value”
TLx=xx TLx=xx
THx=yy
Example: Given: Delay needed=50ms , Xtal=11.0592Mhz … for 16-bit mode
calculations , find values for timer0 registers?
Solution::
n = (50*10-3) / [12÷11.0592*106)] = 37891
Value= 65536 – 37891 = 27645 = (0110101111111101)b = (FD4B)hex
TL0=0xFD, TH0=0x4B
Timer coding steps
Load TLx/THx
Load TMOD reg Wait till TFx flag
according to
according to Start timer using becomes high
required delay or #
required settings TRx bit
of counts
{
mybit=~mybit;
T1M2Delay();
}
}
Timer Module
as a Counter
• Clock from
external pins P3.4
or P3.5
Counter programming
Assume that a 1-Hz external clock is being fed into pin T0 (P3.4). Write a C
program for counter 0 in mode 1 (16-bit) to count the pulses and display
the state of the TH0 and TL0 register
Solution while (1)
{
#include <reg51.h> do
sbit T0=P3^4; {
TR0=1;
void main() P1=TL0;
P2=TH0;
{ }
while (TF0==0);
T0=1; // make p3.4 i/p TR0=0;
TF0=0;
TMOD=0x05; // counter 0 Mode 1 }
TL0=0; // initialize timer values to zero }
TH0=0;
TRY TO DO FOLLOWING CODE
Assume that a 1-Hz external clock is being fed into pin T1 (P3.5).
Write a C program for counter 1 in mode 2 (8-bit auto reload) to count
up and display the state of the TL1 count on P1. Start the count at 0H.