Write the assembly code to generate a 5KHz pulse train. Follow chapter 8, page 91
EdSim51’s Guide to the 8051
MOV TMOD, #02H
MOV THO, #131
SETB TRO
overflowWait:
JNB TFO, $
CPL P1.5
CLR TFO
JMP overflowWait
set up timer zero as 8-bit auto-reload
interval timer
put reload value into timer zero high byte
start timer zero
repeat this line while timer zero overflow
flag is not set
complement (invert) pin five on port one –
this instruction toggles the specified bit
; timer zero overflow flag is set by hardware on
transition from FFH the flag must be reset
; by software
go back and wait for overflow again
Generating a 4 KHz Pulse Train
The line that causes the delay is shown in blue. That line is executed over and over while timer zero’s
overflow flag (TF0) is not set. Once it’s set by the hardware on the timer’s transition from FFH, execution
moves on to the following instruction, which toggles P1.5. The line after that, in red, clears the overflow
flag. This is very important. If the programmer neglects to clear TF0, then when the program jumps back to
wait for the overflow, it would not wait because TFO would still be logic one, even though the timer is far
from overflowing. Clearing TFO means the program will wait for the actual overflow.
Duty Cycle
In the above program, P1.5 is at logic one for the same length of time that it’s at logic zero (125 us each).
This type of pulse train has what’s known as a 50% duty cycle. The duty cycle is defined as the ratio of the
length of the cycle to the length of the pulse:
duty cycle (t + T) × 100%
where t is the length of the pulse (ie: amount of time in a single cycle that the signal is at logic one) and T
is the length of the cycle. In the above example, T is 250 μs and t is 125 μs, hence the duty cycle of 50%.
Let’s say we wanted to modify the above program to result in a pulse train with the same frequency (4 KHz)
but with a 20% duty cycle, one way to do it would be use the same timer delay, but count the number of
overflows, as illustrated in the flowchart on the following page.
Since the pulse train’s frequency is still to be 4 KHz, this means the length of a full cycle is still 250 μs. But
now we want a 20% duty cycle which means the signal should be high for 50 us and low for 200 μs (during
one cycle). Therefore, the value placed in TH0 is 256-50-206. And RO gets the number four because the
signal must be low for four delays (4 x 50). So, P1.5 is cleared, then the program waits for an overflow.
Then it decrements R0. When RO gets to zero it means there have been four overflows, which in turn means
200 μs have passed. P1.5 is set and then the program waits for one overflow before going back through the
loop again.
91