Many times we require precise internal time delays between two actions this can be accomplished using software techniques like Loop Technique but these delays keep the processor occupied because of which other important functions cannot be done. To relieve the processor of this burden we can use TIMERS provided by the controller. 8051 has two internal timers T0 and T1 (8052 has 3 timers T0, T1 and T2) these timers can be controlled individually.
The timers count increments by every MACHINE CYCLE. A single Machine Cycle consists of 12 crystal pulses. i.e.
1 MACHINE CYCLE = Crystal Time/12.
Crystal Time = 1/Crystal Frequency.
So if we use 12MHz crystal then the timer will increment by 1 in every 1µS. The Timer always COUNTS UP, doesn’t matter in which mode it is being used the timer value is always incremented and overflows when the count goes from 0ffffh to 0000h.
Algorithm for Delay using Timer.
Initialize Timer.
Start Timer.
Wait for Timer to overflow.
Stop
In the above algorithm you have seen how to generate delay using timer. Now let us write a small program for generating delay. Suppose we have to generate 0.05 seconds delay. So now we have to calculate the Value of TH0 and TL0.
Count for 0.05 Sec = 0.05/1µs = 50000
So we require Timer 0 to count 50000 (0C350h) internal clock pulses to generate 0.05 sec delay. Since the timer count's up, so it will be necessary to put the (ffffh - C350h = 3CAF) in timer and count’s Up until it over flows. TF0 is set when the timer overflows.
Program for Timer 0 Initialization.
ini_timer0:
MOV TMOD,#01h
mov TH0,#0C3h
mov TL0,#50h
ret
The above subroutine initializes TIMER 0 as 16 bit timer and loads TH0 and TL0 with values for 0.05 sec overflow duration.
Program for Delay using Timer
Delay:
Call ini_timer0
SETB TR0 // Start Timer 0
JNB TF0,$ // Wait till Timer 0 overflows
CLR TF0
CLR TR0 //Stop Timer
Ret
In the above program the first line initializes Timer 0. Then we Start the timer and wait for the timer to over flow. The instruction (JNB TF0,$) means "Jump if TF0 not set, back to the same instruction." The '$' operand means the address of the current instruction. Thus as long as the timer has not overflowed and the TF0 bit has not been set the program will keep executing this same instruction. After 0.05 second Timer 0 will overflow, set the TF0 bit, and program execution will then break out of the loop. Then we clear the TF0 flag and Stop the Timer.
In the above program we have waited till the timer has overflowed. Instead we can use Interrupts. If we use interrupts the controller will interrupt after the timer has overflowed i.e. after 0.05 seconds.[1]
---------- Post added at 12:50 ---------- Previous post was at 12:08 ----------
i will soon provide you the code too but i will ask you to refer the book 80511 embeded systems by mohammad ali mazizi
it is the best book in the market for microcontrollers
you will best understand the concept of timer from that book