SPONSORED LINKS
 
 
Google
 
8051 TIMER/COUNTER PROGRAMMING

8051 TIMER/COUNTER PROGRAMMING

The 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions:

  • Keeping time and/or calculating the amount of time between events
  • Counting the events themselves
  • Generating baud rates for the serial port.

TIMER COUNT
A timer always counts up. It doesn't matter whether the timer is being used as a timer, a counter, or a baud rate generator: A timer is always incremented by the microcontroller. 

(Note: There are some 8051-compatible microcontroller that can counts down also.)

TIME MEASUREMENT USING TIMERS
When a timer is used to measure time it is also called an "interval timer" since it is measuring the time of the interval between two events.

COUNT TIME OF TIMER 
First, it's worth mentioning that when a timer is in interval timer mode (as opposed to event counter mode) and correctly configured, it will increment by 1 every machine cycle. As we know, a single machine cycle consists of 12 crystal pulses. Thus a running timer will be incremented:

11,059,000/12 = 921,583

921,583 times per second. Unlike instructions, some of which require 1 machine cycle, others 2, and others 4,the timers are consistent: They will always be incremented once per machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate:
50,000/921,583 = .0542
.0542 seconds have passed. In plain English, about half of a tenth of a second, or one -twentieth of a second. 

Obviously it's not very useful to know .0542 seconds have passed. If we wants to execute an event once per second we'd have to wait for the timer to count from 0 to 50,000 18.45 times.

Let's say we want to know how many times the timer will be incremented in .05 seconds. We can do simple multiplication:

.05 x 921,583 = 46,079.15.

This tells us that it will take .05 seconds (1I20th of a second) to count from 0 to 46,079. Actually, it will take it .049999837 seconds, so we're off by .000000163 seconds, however, that's close enough for government work. Consider that if one was building a watch based on the 8051 and made the above assumption watch would only gain about one second every 2 months.

Obviously, this is a little more useful. If we know it takes 1/20th of a second to count from 0 to 46,079 and wants to execute some event every second we simply wait for the timer to count from 0 to 46,079 twenty times; then we execute our event, reset the timers, and wait for the timer to count up another 20 times. In this manner we will effectively execute our event once per second, accurate to within thousandths of a second.

Thus, we now have a system with which to measure time. All we need to review is how to control the timers and initialize them to provide us with the information we need.

TIMER SFRS
The 8051 has two timers which each function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) that control the timers, and each timer also has two SFRs (special function registers) dedicated solely to itself (TH0/TL0 and TH1/TL1).

SFRs are given names to make it easier to refer to them, but in reality an SFR has a numeric address. It is often useful to know the numeric address that corresponds to an SFR name. The SFRs relating to timers are 

SFR Name Description  SFR Address
TH0 Timer 0 High Byte 8Ch
TL0 Timer 0 Low Byte 8Ah
TH1  Timer 1 High Byte 8Dh
TL1 Timer 1 Low Byte 8Bh
TCON  Timer Control  88h
TMOD Timer Mode 89h

When the name of an SFR is entered into an assembler, it internally converts it to a number.
For example, the command:

MOV TH0, #25H
moves the value 25h into the TH0 SFR. However, since TR0 is the same as SFR address 8Ch this command is equivalent to:

MOV 8CH, #25H 
TIMER 0
Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0 (the high and low byte of the timer). That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain 0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal) and TL0 will contain the low byte of the value (232 decimal). Reviewing low/high byte notation, recall that you must multiply the high byte by 256 and add the low byte to calculate the final value. That is to say:

THO x 256 + TLO = 1000 
3 x 256 + 232 = 1000

TIMER1
Timer 1 works the exactly same way as TIMER 0, but its SFRs are TH1 and TL1.

Since there are only two bytes devoted to the value of each timer it is apparent that the maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is subsequently incremented, it will reset, or overflow, back to 0.

THE TMOD SFR
Let's first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is used to control the mode of operation of both timers. Each bit of the SFR gives the microcontroller specific information concerning how to run a timer. The high four bits (bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform the exact same functions for timer 0.
The function of individual bits of TMOD is described below

TMOD (89H) SFR

Bit Name Explanation of Function Timer
7 GATE1 When this bit is set the timer will only run when INT1 (P3.3) is high. When this bit is clear the timer will run regardless of the state of INT1. 1
6 C/T1 When this bit is set the timer will count events on T1 (P3.5). When this bit is clear the timer will be incremented every machine cycle. 1
5 T1M1 Timer mode bit 1
4 T1M0   1
3 GATE0 When this bit is set the timer will only run when INT0 (P3.2) is high. When this bit is clear the timer will run regardless of the state of INT0. 0
2 C/T0 When this bit is set the timer will count events on T0 (P3.4). When this bit is clear the timer will be incremented every machine cycle. 0
1 T0M1

Timer mode bit

0
0 T0M0

Timer mode bit

0

As we see in the above table, four bits (two for each timer) are used to specify a mode operation. The modes of operation are given below

TxM1 TxM0 timer Mode Description of Mode
0 0 0 13-bit Timer.
0 1 1 16-bit Timer
1 0 2 8-bit auto-reload
1 1 3 Split timer mode

13-BIT TIME MODE (MODE 0)
Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to maintain compatibility with its predecessor, the 8048. Generally the 13-bit timer mode is not used in new development.

When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in essence, the timer can only contain 8192 values. If one sets a I3-bit timer to 0, it will overflow back to zero 8192 machine cycles later.

16-bit Time Mode (MODE 1)
Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just like 13. that all 16 bits are used.

TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536 distinct values. If programmer set a I6-bit timer to 0, it will overflow back to 0 after 65,536 machine cycles.

For Timer mode 1, a time delay can be created by loading TLx and THx with values
Derived from the formula:

Time Delay= DI(12*(65, 536-InitValue))
                                   Freq 
Where, Init Value TLx + (256 * THx)

8-BIT TIME MODE (MODE 2)
Timer mode "2" is an 8-bit auto-reload mode. When a timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counting up. When TLx reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx. .

In Timer mode 2 ,when TLx overflows {goes from 0FFh to 0 ),it is reloaded with the value set in THx. The delays between overflows can be calculated from:

Time Delay = (12 * (256 - THx))
                             Freq 

For example, let's say TH0 holds the value FDh and TL0 holds the value FEh. If we were to watch the values of TH0 and TL0 for a few machine cycles this is what we'd see:

Machine cycle TH0 Value TL0 Value
1 FDh FEh
2 FDh FFh
3 FDh FDh
4 FDh FEh
5 FDh FFh
6 FDh FDh
7 FDh FEh

The value of TH0 never changed. In fact, when one uses mode 2 he almost always set THx to a known value and TLx is the SFR that is constantly incremented.

Benefit of auto-reload mode could be understand by this example, suppose programmer want the timer to always have a value from 200 to 255. If he uses mode 0 or 1, he'd have to check in code to see if the timer had overflowed and, if so, reset the timer to 200. This takes precious instructions of execution time to check the value and/or to reload it. When he uses mode 2 the microcontroller takes care of this. Once programmer has configured a timer in mode 2 he does not have to worry about checking to see if the timer has overflowed nor does he has to worry about resetting the value, the microcontroller hardware will do it all.

The auto-reload mode is very commonly used for establishing a baud rate.

SPLIT TIMER MODE (MODE 3)
Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to TH0

While Timer 0 is in split mode, the real Timer 1 (i.e., TH1 and TL1) can be put into modes 0, 1 or 2 normally, however, one may not start or stop the real timer 1 since the bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle.

The one use of using split timer mode is if programmer needs to have two separate
Timers and, additionally, a baud rate generator. In such case he can use the real Timer 1 as a baud rate generator and use TH0/I'L0 as two separate timers.


THE TCON SFR
Finally, there's one more SFR that controls the two timers and provides valuable information The TCON SFR has the following structure 

TCON (88H) SFR

Bit Name Bit Address Explanation of Function Timer
7 TF1 8Fh Timer 1 Overflow. This bit is set by the microcontroller when Timer 1 overflows 1
6 TR1 8Eh Timer 1 Run. When the bit set Timer 1 is set Timer 1 is turned on. When this bit is clear Timer 1 is off 1
5 TF0 8Dh Timer 0 Overflow. This bit is set by the microcontroller when Timer 0 overflows. 0
4 TR0 8Ch Timer 0 Run. When this bit is set Timer 0 is turned on. When this bit is clear Timer 0 is off. 0

The TCON SFR's only 4 of the 8 bits are defined. That's because the other 4 bits of the SFR don't have anything to do with timers, they have to do with Interrupts. 

A new information in this table is the column "bit address." This is because this SFR is "bit-addressable." Bit-addressable means if programmer wants to set the bit TF1, which is the highest bit of TCON, he could execute the command:

MOV TCON, #80H
or, since the SFR is bit-addressable, could just execute the command:

SETB TF1
This has the benefit of setting the high bit of TCON without changing the value of any of the other bits of the SFR. Usually when programmer start or stop a timer he does not want to modify the other values in TCON, so he can takes advantage of the fact that the SFR is bit-addressable.

INITIALIZING A TIMER
First we must decide what mode we want the timer to be in. In this case we want a 16-bit timer that runs continuously; that is to say, it is not dependent on any external pins.

We must first initialize the TMOD SFR. Since we are working with timer 0 we will be using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since we want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of TMOD. Thus to initialize the timer we execute the instruction:

MOV TMOD, #01H
Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the timer running we must set the TR0 bit we can do that by executing the instruction:

SETB TR0
Upon executing these two instructions timer 0 will immediately begin counting, begin incremented once every machine cycle (every 12 crystal pulses).

READING THE TIMER
There are two common ways of reading the value of a 16-bit timer; which programmer depends on specific application. Either read the actual value of the timer as a 16-bit number, or may simply detect when the timer has overflowed.

READING THE VALUE OF A TIMER
If timer is in an 8-bit mode, that is, either 8-bit Auto Reload mode or in split timer mode, then reading the value of the timer is simple. Simply read the 1-byte value of the timer.

However, if dealing with a 13-bit or 16-bit timer the task is a little more complicated. Consider what would happen if programmer read the low byte of the timer as 255, then read the high byte of the timer as 15. In this case, what actually happened was that the timer value was 14/255 (high byte 14, low byte 255) but programmer read 15/255. Because programmer read the low byte as 255. But when programmer executed the next instruction a small amount of time passed, but enough for the timer to increment again at which time the value rolled from 14/255 to 15/0. But in the process programmer has read the timer as being 15/255. Obviously there's a problem there.

The solution of this problem is to simply turn off the timer run bit (i.e. CLR TR0), read the timer value, and then turn on the timer run bit (i.e. SETB TR0). Of course, this implies that the timer will be stopped for a few machine cycles. Whether or not this is tolerable depends on specific application.

DETECTING TIMER OVERFLOW

Often it is necessary to just know that the timer has reset to 0. That is to say, when the timer back to 0.

Whenever a timer overflows from it's highest value back to 0, the microcontroller automatically sets the TFx bit in the TCON register. This is useful since rather than checking e of the timer programmer can just check if the TFx bit is set. If TF0 is set it means that timer 0 has overflowed; ifTF1 is set it means that timer 1 has overflowed.

We can use this approach to cause the program to execute a fixed delay. As we calculated earlier that it takes the 80511/20th of a second to count from 0 to 46,079. However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to use the TFx flag to indicate when 1/20th of a second has passed we must set the timer initially to 65536 less 46079, or 19,457. If we set the timer to 19,457 1/20th of a second later the timer will overflow. Thus we come up with the following code to execute a pause of 1I20th of a second:

MOV TH0, #76;High byte of 19,457 (76 x 256 = 19,456)
MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457)
MOV TMOD, #0l;Put Timer 0 in 16-bit mode
SETB TR0; Make Timer 0 start counting
JNB TF0, $;If TF0 is not set, jump back to this same instruction

In the above code the first two lines initialize the Timer 0 starting value to 19,457. The
Next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB TF0, $, reads, "Jump, if TF0 is not set, back to this same instruction." The "$" operand means, in most assemblers, 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 1/20th of a second timer 0 will overflow, set the TF0 bit, and program execution will then break out of the loop.

TIMING THE LENGTH OF EVENTS
The 8051 provides another way that can be used to time the length of events.

For example, let's say we're trying to save electricity in the office and we're interested in how long a light is turned on each day. When the light is turned on, we want to measure time. When the light is turned off we don't. One option would be to connect the light switch to one of the pins, constantly read the pin, and turn the timer on or off based on the state of that pin. While this would worrk fine, the 8051 provides us with an easier method of accomplishing this.

Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always cleared this bit because we wanted the timer to run regardless of the state of the external pins. However, now it would be nice if an external pin could control whether the timer was running or not. It can . All we need to do is connect the light switch to pin INT0 (P3.2) on the 8051 and set the bit GATE0. When GATE0 is set Timer 0 will only run if P3.2 is high. When P3.2 is low (i.e., the light switch is off) the timer will automatically be stopped.

Thus, with no control code whatsoever, the external pin P3.2 can control whether or not our timer is running or not.


USING TIMER AS EVENT COUNTERS
We've discussed how a timer can be used for the obvious purpose of keeping track of time. However, the 8051 also allows us to use the timers to count events. The only difference between timing and counting is the source of clock pulses to the counters. When used as timer, the clock pulses are sourced from the oscillator through the divide-by-l2 circuit. used as a counter, pin T0 (P3.4) and pin T1 (P3.5) supplies pulses to counter 0 and counter1 respectively. The C/T bit in TMOD must be set to1 to enable pulses from the TX pin to r the control circuit.

For example-Let's say there had a sensor placed across a road that would send a pulse every time a car passed over it. This could be used to determine the volume of traffic on the road. We could attach this sensor to one of the 8051's I/O lines and constantly monitor it, detecting when it pulsed high and then incrementing our counter when it went back to a low state. This is not terribly difficult, but requires some code. Let's say we hooked the sensor to P1.0; the code to count cars passing would look something like this:

JNB P1.0, $ ; IF a car hasn't raised the signal, keep waiting
JB P1.0, $ ; The line is high which means the car is on the sensor right now
INC COUNTER; The car has passed completely, so we count it
As we can see, it's only three lines of code.
Since the 8051 provides us a way to use the timers to count events we don't have to bother with it, but we only have to configure an additional bit.
Let's say we want to use Timer 0 to count the number of cars that pass. If we looks back to the bit table for the TC0N SFR there is a bit called "C/T0", it's bit 2 (TCON.2). Reviewing the explanation of the bit we see that if the bit is clear then timer 0 will be incremented every machine cycle. This is what we've already used to measure time. However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being incremented every machine cycle, timer 0 will count events on the P3.4 line. So in our case we simply connect our sensor to P3.4 and let the 8051 do the work. Then when we want to know how many cars have passed, we just read the value of timer 0, the value of timer 0 will be the number of cars that have passed. .

So what exactly is an event? What does timer 0 actually "count?" Speaking at the electrical level, the 8051 count 1-0 transitions on the P3.4 line. This means that when a car first runs over out sensor it will raise the input to a high ("1") condition. At that point the 8051 will not count anything since this is a 0-1 transition. However, when the car has passed the sensor will fall back to a low ("0")" state. This is a 1-0 transition and at that instant the counter will be incremented by 1.

It is important to note that the 8051 checks the P3.4line each machine cycle (12 clock
Cycles). This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it will probably not be detected by the 8051. This also means the 8051 event counter is only capable of counting events that occur at a maximum of 1/24th the rate of the crystal frequency. That is to say, if the crystal frequency is 12.000 Mhz it can count a maximum of 500,000 events per second (12.000 Mhz x 1/24 = 500,000). If the event being counted occurs more than 500,000 times per second it will not be able to be accurately counted by the 8051.

BACK

SPONSORED LINKS