# 8051 timer delay calculation

In the following program

MOV TMOD, #01H
HERE: MOV TLO, #0F2H
MOV THO, #0FFH
CPL P1.2
ACALL DELAY
SJMP HERE

DELAY:SETB TR0
AGAIN: JB TF0,AGAIN
CLR TF0
CLR TR0
RET


It is asked to calculate the time delay generated by the delay subroutine.

Clearly the counter or timer counts a total of FFFF-FFF2 = 13 + 1 (one more count for setting up TFO). Note the crystal frequency used here is 11.0592 MHz, hence the timer frequency would be 11.0592 / 12 = 921.6 kHz, hence one cycle length of the timer is 1/921.6 = 1.085 μs. Hence the delay should be 14 × 1.085 but the answer says it is 28 × 1.085 as shown here:

14 × 1.085 µs is closer to the correct answer for the question that was actually asked.

However, the solution ignores altogether the time required to execute the instructions in the DELAY subroutine.

When you insert a call to the subroutine into a sequence of instructions, the following additional instructions are executed:

        ACALL DELAY      2 cycles

DELAY:  SETB TR0         1 cycle
AGAIN:  JB TF0,AGAIN    14 cycles (2 cycles * 7 iterations)
CLR TF0          1 cycle
CLR TR0          1 cycle
RET              2 cycles
---------
21 cycles total (22.786 us)


The final sentence of the solution is answering a different question: How long does it take for the output pin to finish a complete cycle?

That loop actually includes not only the delay calculated above, but also the additional instructions above and below the call.

HERE:   MOV TLO, #0F2H    2 cycles
MOV THO, #0FFH    2 cycles
CPL P1.2          1 cycle
ACALL DELAY      21 cycles (from above)
SJMP HERE         2 cycles
---------
28 cycles total (30.382 us)


So a complete cycle of the output bit, or two iterations of this loop, would require a total of 60.764 µs.

This illustrates why it is rarely useful to involve the hardware timer for short delays. A simple DJNZ loop uses much less code.

• what do you mean by output pin? do you mean how long does it take to change p2.1 from 1 to zero then again zero to 1 (a complete cycle)? if that is the case, are they ignoring the machine cycle delay of the last three lines and first three lines? Jul 24, 2021 at 14:44
• Yes, they are indeed ignoring the execution time of the code altogether, including the execution of the instructions in the DELAY subroutine itself. Jul 24, 2021 at 14:59
• Note that the analysis above is for the original 8051, since that's what you mentioned in your title and tags. However, there are also "fast" or "single cycle" variants of the 8051 that execute code 12x as fast, which means that the error introduced by instruction execution time is that much less. Jul 24, 2021 at 15:39