PROGRAMMING 8051 TIMERS

The 8051 has two timers/counters. They can be used either as timers to generate a time delay or as counters to count events happening outside the microcontroller. In Section 9.1 \ve see how these timers are used to generate time delays. In Section 9.2 we show how they are used as event counters. In Section 9.3 we use C language to program the 8051 timers.
SECTION 9.1: PROGRAMMING 8051 TIMERS
The 8051 has two timers: Timer 0 and Timer 1. They can be used either as timers or as event counters. In this section we first discuss the timers’ registers and then show how to program the timers to generate time delays.
Basic registers of the timer
Both Timer 0 and Timer 1 are 16 bits wide. Since the 8051 has an 8-bit architecture, each 16-bit timer is accessed as two separate registers of low byte and high byte. Each timer is discussed separately.
Timer 0 registers
The 16-bit register of Timer 0 is accessed as low byte and high byte. The low byte register is called TLO (Timer 0 low byte) and the high byte register is referred to as THO (Timer 0 high byte). These registers can be accessed like any other register, such as A, B, RO, Rl, R2, etc. For example, the instruction “MOV TLO , #4FH” moves the value 4FH into TLO, the low byte of Timer 0. These registers can also be read like any other register. For example, “MOV R5 , THO” saves THO (high byte of Timer 0) in R5.

Figure 9-1. Timer 0 Registers
Timer 1 registers



Figure 9-2. Timer 1 Registers

Timer I is also 16 bits, and its 16-bit register is split into two bytes, referred to as TLl (Timer I low byte) and TH1 (Timer 1 high byte). These registers are accessible in the same way as the registers of Timer 0.




TMOD (timer mode) register
Both timers 0 and 1 use the same register, called TMOD, to set the various timer operation modes. TMOD is an 8-bit register in which the lower 4 bits are set aside for Timer 0 and the upper 4 bits for Timer 1. In each case, the lower 2 bits are used to set the timer mode and the upper 2 bits to specify the operation. These options are discussed next.


Figure 9-3. TMOD Register
M1, MO
MO and Ml select the timer mode. As shown in Figure 9-3, there are three modes: 0, 1, and 2. Mode 0 is a 13-bit timer, mode 1 is a 16-bit timer, and mode 2 is an 8-bit timer. We will concentrate on modes 1 and 2 since they are the ones used most widely. We will soon describe the characteristics of these modes, after describing the rest of the TMOD register.
C/T (clock/timer)
This bit in the TMOD register is used to decide whether the timer is used as a delay generator or an event counter. If C/T = 0, it is used as a timer for time delay generation. The clock source for the time delay is the crystal frequency of the 8051. This section is concerned with this choice. The timer’s use as an event counter is discussed in the next section.


Example 9-1
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:
We convert the values from hex to binary. From Figure 9-3 we have:
  1. TMOD = 00000001, mode 1 of Timer 0 is selected.
  2. TMOD = 00100000, mode 2 of Timer 1 is selected.
    1. TMOD = 00010010, mode 2 of Timer 0, and mode 1 of
      Timer 1 are selected.
Clock source for timer
As you know, every timer needs a clock pulse to tick. What is the source of the clock pulse for the 8051 timers? If C T = 0. the crystal frequency attached to the 8051 is the source of the clock for the timer. This means that the size of the crystal frequency attached to the 8051 also decides the speed at which the 8051 timer ticks. The frequency for the timer is always 1 12th the frequency of the crystal attached to the 8051. See Example 9-2.
Example 9-2




NOTE THAT 8051 TIMERS USE 1/12 OF XTAL FREQUENCY, REGARDLESS OF MACHINE CYCLE TIME.




Although various 8051-based systems have an XTAL frequency of 10 MHz to 40 MHz, we will concentrate on the XTAL frequency of 11.0592 MHz. The reason behind such an odd number has to do with the baud rate for serial communication of the 8051. XTAL = 11.0592 MHz allows the 8051 system to communicate with the IBM PC with no errors, as we will see in Chapter 10.
GATE
The other bit of the TMOD register is the GATE bit. Notice in the TMOD register of Figure 9-3 that both Timers 0 and 1 have the GATE bit. What is its purpose? Every timer has a means of starting and stopping. Some timers do this by software, some by hardware, and some have both software and hardware controls. The timers in the 8051 have both. The start and stop of the timer are controlled by way of software by the TR (timer start) bits TRO and TR1. This is achieved by the instructions “SETB TR1″ and “CLR TR1″ for Timer 1, and “SETB TRO” and “CLR TRO” for Timer 0. 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. However, to avoid further confusion for now, we will make GATE = 0, meaning that no external hardware is needed to start and stop the timers. In using software to start and stop the timer where GATE = 0. all we need are the instructions “SETB TRx” and “CLR TRx”. The use of external hardware to stop or start the timer is discussed in Chapter 11 when interrupts are discussed.
Example 9-3
Find the value for TMOD if we want to program Timer 0 in mode 2, use 8051 XTAL for the clock source, and use instructions to start and stop the timer.


Now that we have this basic understanding of the role of the TMOD register, we will look at the timer’s modes and how they are programmed to create a time delay. Because modes 1 and 2 are so widely used, we describe each of them in detail.
Mode 1 programming
The following are the characteristics and operations of mode 1:
  1. It is a 16-bit timer; therefore, it allows values of 0000 to FFFFH to be loaded
    into the timer’s registers TL and TH.
  2. After TH and TL are loaded with a 16-bit initial value, the timer must be start
    ed. This is done by “SETB TRO” for Timer 0 and “SETB TR1″ for Timer 1.
  1. After the timer is started, it starts to count up. It counts up until it reaches its




limit of FFFFH. When it rolls over from FFFFH to 0000, it sets high a flag bit called TF (timer flag). This timer flag can be monitored. When this timer flag is raised, one option would be to stop the timer with the instructions “CLR TRO” or “CLR TR1″, for Timer 0 and Timer 1, respectively. Again, it must be noted that each timer has its own timer flag: TFO for Timer 0, and TF1 for Timer 1.
4. After the timer reaches its limit and rolls over, in order to repeat the process the registers TH and TL must be reloaded with the original value, and TF must be reset to 0.






Steps to program in mode 1
To generate a time delay, using the timer’s mode 1, the following steps are taken. To clarify these steps, see Example 9-4.
  1. Load the TMOD value register indicating which timer (Timer 0 or Timer 1) is
    to be used and which timer mode (0 or 1) is selected.
  1. Load registers TL and TH with initial count values.
  2. Start the timer.
    1. Keep monitoring the timer flag (TF) with the “JNB TFx, target” instruc
      tion to see if it is raised. Get out of the loop when TF becomes high.
  3. Stop the timer.
  4. Clear the TF flag for the next round.
  5. Go back to Step 2 to load TH and TL again.
    To calculate the exact time delay and the square wave frequency generated on pin PI .5, we need to know the XTAL frequency. See Example 9-5.
From Example 9-6 we can develop a formula for delay calculations using mode 1 (16-bit) of the timer for a crystal frequency of XTAL = 11.0592 MHz. This is given in Figure 9-4. The scientific calculator in the Accessories directory of Microsoft Windows can help you to find the TH, TL values. This calculator supports decimal, hex, and binary calculations.
(a) in hex
(FFFF – YYXX + 1) X 1.085 us where YYXX are TH, TL initial values respectively. Notice that values YYXX are in hex.
(b) in decimal
Convert YYXX values of the TH,TL register to decimal to get a NNNNN decimal number, then (65536 – NNNNN) x 1.085 mircosec
Timer Delay Calculation for XTAL = 11.0592 MHz




Example 9-4
In the following program, we are creating a square wave of 50% duty cycle (with equal portions high and low) on the PI.5 bit. Timer 0 is used to generate the time delay. Analyze the program.

Solution:
In the above program notice the following steps.
  1. TMOD is loaded.
  2. FFF2H is loaded into THO – TLO.
  3. P1.5 is toggled for the high and low portions of the pulse.
  4. The DELAY subroutine using the timer is called.
  5. In the DELAY subroutine, Timer 0 is started by the “SETB TRO” instruction.
    1. Timer 0 counts up with the passing of each clock, which is provided by the crystal
      oscillator. As the timer counts up, it goes through the states of FFF3, FFF4, FFF5,
      FFF6, FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it reaches FFFFH. One more
      clock rolls it to 0, raising the timer flag (TFO = 1). At that point, the JNB instruction
      falls through.
    2. Timer 0 is stopped by the instruction “CLR TRO”. The DELAY subroutine ends,
      and the process is repeated.
    Notice that to repeat the process, we must reload the TL and TH registers and start the timer again.


Example 9-5
In Example 9-4, calculate the amount of time delay in the DELAY subroutine generated by the timer. Assume that XTAL = 11.0592 MHz.
Solution:
The timer works with a clock frequency of 1/12 of the XTAL frequency; therefore, we have 11.0592 MHz / 12 = 921.6 kHz as the timer frequency. As a result, each clock has a period of T = 1 / 921.6 kHz = 1.085 (is. In other words, Timer 0 counts up each 1.085 us resulting in delay = number of counts x 1.085 us.
The number of counts for the rollover is FFFFH – FFF2H = ODH (13 decimal). However, we add one to 13 because of the extra clock needed when it rolls over from FFFF to 0 and raises the TF flag. This gives 14 x 1.085 us = 15.19 us for half the pulse. For the entire period T = 2 x 15.19 (as = 30.38 (is gives us the time delay generated by the timer.
Example 9-6
In Example 9-5, calculate the frequency of the square wave generated on pin PI. 5. Solution:
In the time delay calculation of Example 9-5, we did not include the overhead due to instructions in the loop. To get a more accurate timing, we need to add clock cycles due to the instructions in the loop. To do that, we use the machine cycles from Table A-l in Appendix A, as shown below.


NOTE THAT 8051 TIMERS USE 1/12 OF XTAL FREQUENCY, REGARDLESS OF MACHINE CYCLE TIME.




Example 9-7
Find the delay generated by Timer 0 in the following code, using both of the methods of Figure 9-4. Do not include the overhead due to instructions.

  1. (FFFF-B83E + 1) = 47C2H= 18370 in decimal and 18370 x 1.085 fis= 19.93145
    ms.
  2. Since TH – TL = B83EH = 47166 (in decimal) we have 65536 – 47166 = 18370.
    This means that the timer counts from B83EH to FFFFH.. This plus rolling over to
    0 goes through a total of 18370 clock cycles, where each clock is 1.085 \ls in dura
    tion. Therefore, we have 18370 x 1.085 (is = 19.93145 ms as the width of the pulse.
Example 9-8
Modify TL and TH in Example 9-7 to get the largest time delay possible. Find the delay in ms. In your calculation, exclude the overhead due to the instructions in the loop.
Solution:
To get the largest delay we make TL and TH both 0. This will count up from 0000 to FFFFH and then roll over to zero.


Making TH and TL both zero means that the timer will count from 0000 to FFFFH, and then roll over to raise the TF flag. As a result, it goes through a total of 65536 states. Therefore, we have delay = (65536 – 0) x 1.085 us = 71.1065 ms.


Example 9-9
The following program generates a square wave on pin PL5 continuously using Timer 1 for a time delay. Find the frequency of the square wave if XTAL =11.0592 MHz. In your calculation do not include the overhead due to instructions in the loop.

In the above program notice the target of SJMP. In mode 1, the program must reload the TH, TL register every time if we want to have a continuous wave. Now the calculation. Since FFFFH – 7634H = 89CBH + 1 = 89CCH and 89CCH = 35276 clock count. 35276 x 1.085 us = 38.274 ms for half of the square wave. The entire square wave length is 38.274 x 2 = 76.548 ms and has a frequency = 13.064 Hz.
Also notice that the high and low portions of the square wave pulse are equal. In the above calculation, the overhead due to all the instructions in the loop is not included.
In Examples 9-7 and 9-8, we did not reload TH and TL since it was a single pulse. Look at Example 9-9 to see how the reloading works in mode 1.
Finding values to be loaded into the timer
Assuming that we know the amount of timer delay we need, the question is how to find the values needed for the TH, TL registers. To calculate the values to be loaded into the TL and TH registers look at Example 9-10 where we use crystal frequency of 11.0592 MHz for the 8051 system.
Assuming XTAL = 11.0592 MHz from Example 9-10 we can use the following steps for finding the TH, TL registers’ values.

  1. Divide the desired time delay by 1.085 us.
  2. Perform 65536 – n, where n is the decimal value we got in Step 1.
    1. Convert the result of Step 2 to hex, where yyxx is the initial hex value to be
      loaded into the timer’s registers.
  3. Set TL = xx and TH = yy.




    Example 9-10
    Assume that XTAL = 11.0592 MHz. What value do we need to load into the timer’s registers if we want to have a time delay of 5 ms (milliseconds)? Show the program for Timer 0 to create a pulse width of 5 ms on P2.3.
    Solution:
    Since XTAL = 11.0592 MHz, the counter counts up every 1.085 us. This means that out of many 1.085 us intervals we must make a 5 ms pulse. To get that, we divide one by the other. We need 5 ms /•! .085 us = 4608 clocks. To achieve that we need to load into TL and TH the value 65536 – 4608 = 60928 = EEOOH. Therefore, we have TH = EE and tt = on


    Example 9-11
    Assuming that XTAL = 11.0592 MHz, write a program to generate a square wave of 2 kHz frequency on pin PI .5.
    Solution:
    This is similar to Example 9-10, except that we must toggle the bit to generate the square wave. Look at the following steps.
    1. T = 1 / f = 1 / 2 kHz = 500 us the period of the square wave.
    2. 1/2 of it for the high and low portions of the pulse is 250 us.
    3. 250 us / 1.085 us = 230 and 65536 – 230 = 65306. which in hex is FF1AH.
    4. TL = 1AH and TH = FFH. all in hex. The program is as follows.






    Example 9-12
    Assuming XTAL = 11.0592 MHz, write a program to generate a square wave of 50 Hz frequency on pin P2.3.
    Solution:
    Look at the following steps.
    1. T 1 / 50 Hz = 20 ms, the period of the square wave.
    2. 1/2 of it for the high and low portions of the pulse = 10 ms
      1. 10 ms / 1.085 us = 9216 and 65536 – 9216 = 56320 in decimal, and in hex it is
        DCOOH.
    3. TL = 00 and TH = DC (hex)


    Generating a large time delay
    As we have seen in the examples so far, the size of the time delay depends on two factors, (a) the crystal frequency, and (b) the timer’s 16-bit register in mode 1. Both of these factors are beyond the control of the 8051 programmer. We saw earlier that the largest time delay is achieved by making both TH and TL zero. What if that is not enough? Example 9-13 shows how to achieve large time delays.
    Using Windows calculator to find TH, TL
    The scientific calculator in Microsoft Windows is a handy and easy-to-use tool to find the TH, TL values. Assume that we would like to find the TH, TL values for a time delay that uses 35,000 clocks of 1.085 us. The following steps show the calculation.
  4. Bring up the scientific calculator in MS Windows and select decimal.
  5. Enter 35,000.
  6. Select hex. This converts 35,000 to hex, which is 88B8H.
  7. Select +/- to give -35000 decimal (7748H).
    1. The lowest two digits (48) of this hex value are for TL and the next two (77)
      are for TH. We ignore all the Fs on the left since our number is 16-bit data.




    Example 9-13
    Examine the following program and find the time delay in seconds. Exclude the overhead due to the instructions in the loop.

    Solution:
    TH – TL = 0108H = 264 in decimal and 65536 – 264 = 65272. Now 65272 x 1.085 jis = 70.820 ms, and for 200 of them we have 200 x 70.820 ms = 14.164024 seconds.
    Mode 0
    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. Therefore, when the timer reaches its maximum of 1FFH, it rolls over to 0000, and TF is raised.
    Mode 2 programming
    The following are the characteristics and operations of mode 2.
    1. It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded
      into the timer’s register TH.
    2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL. Then
      the timer must be started. This is done by the instruction “SETB TRO” for
      Timer 0 and “SETB TR11‘ for Timer 1. This is just like mode 1.
    3. After the timer is started, it starts to count up by incrementing the TL register.
      It counts up until it reaches its limit of FFH. When it rolls over from FFH to
      00, it sets high the TF (timer flag). If we are using Timer 0, TFO goes high; if
      we are using Timer 1, TF1 is raised.




    4. When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded automatically with the original value kept by the TH register. To repeat the process, we must simply clear TF and let it go without any need by the programmer to reload the original value. This makes mode 2 an auto-reload, in contrast with mode 1 in which the programmer has to reload TH and TL.
    It must be emphasized that mode 2 is an 8-bit timer. However, it has an auto-reloading capability. In auto-reload, TH is loaded with the initial count and a copy of it is given to TL. This reloading leaves TH unchanged, still holding a copy of the original value. This mode has many applications, including setting the baud rate in serial communication, as we will see in Chapter 10.
    Steps to program in mode 2
    To generate a time delay using the timer’s mode 2, take the following steps.
    1. Load the TMOD value register indicating which timer (Timer 0 or Timer 1) is
      to be used, and select the timer mode (mode 2).
  8. Load the TH registers with the initial count value.
  9. Start the timer.
    1. Keep monitoring the timer flag (TF) with the “JNB TFx, target” instruc
      tion to see whether it is raised. Get out of the loop when TF goes high.
  10. Clear the TF flag.
  11. Go back to Step 4, since mode 2 is auto-reload.
    Example 9-14 illustrates these points. To achieve a larger delay, we can use multiple registers as shown in Example 9-15.
    Example 9-14
    Assuming that XTAL = 11.0592 MHz. find (a) the frequency of the square wave generated on pin P 1.0 in the following program, and (b) the smallest frequency achievable in this program, and the TH value to do that.


    Solution:
    1. First notice the target address of SJMP. In mode 2 we do not need to reload TH since
      it is auto-reload. Now (256 – 05) x 1.085 us = 251 x 1.085 us = 272.33 us is the
      high portion of the pulse. Since it is a 50% duty cycle square wave, the period T is
      twice that; as a result T = 2 x 272.33 us = 544.67 us and the frequency = 1.83597
      kHz.
    2. To get the smallest frequency, we need the largest T and that is achieved when TH
      = 00. In that case, we have T = 2 x 256 x 1.085 us = 555.52 us and the frequency
      = 1.8kHz.






    Example 9-15
    Example 9-16
    Assuming that we are programming the timers for mode 2, find the value (in hex) loaded into TH for each of the following cases.


    You can use the Windows scientific calculator to verify the results provided by the assembler. In Windows calculator, select decimal and enter 200. Then select hex, then +/- to get the TH value. Remember that we only use the right two digits and ignore the rest since our data is an 8-bit data. The following is what we get.




    Assemblers and negative values
    Since the timer is 8-bit in mode 2, we can let the assembler calculate the value for TH. For example, in “MOV TH1 ,#-10 0″, the assembler will calculate the -100 = 9C, and makes TH1 = 9C in hex. This makes our job easier.
    Example 9-17
    Find (a) the frequency of the square wave generated in the following code, and (b) the duty cycle of this wave.

    Solution:
    For the TH value in mode 2, the conversion is done by the assembler as long as we enter a negative number. This also makes the calculation easy. Since we are using 150 clocks, we have time for the DELAY subroutine = 150 x 1.085 us = 162 (as. The high portion of the pulse is twice that of the low portion (66% duty cycle). Therefore, we have: T = high portion + low portion = 325.5 (is + 162.25 jis = 488.25 (is and frequency = 2.048 kHz.
    Notice that in many of the time delay calculations we have ignored the clocks caused by the overhead instructions in the loop. To get a more accurate time delay, and hence frequency, you need to include them. If you use a digital scope and you don’t get exactly the same frequency as the one we have calculated, it is because of the overhead associated with those instructions.
    In this section, we used the 8051 timer for time delay generation. However, a more powerful and creative use of these timers is to use them as event counters. We discuss this use of the counter next.

Next post:

Previous post: