Texas Instruments MSC1210 User Manual

Page 85

Advertising
background image

Using Timers to Measure Time

8-11

Timers

This approach can be used to cause the program to execute a fixed delay. As
shown earlier, we calculated that it takes the 8051 1/20th of a second to count
from 0 to 46 080. However, the TFx flag is set when the timer overflows back
to 0.

Therefore, to use the TFx flag to indicate when 1/20th of a second has passed,
the timer must be set initially to 65 536 less 46 080, or 19 456. If the timer is
set to 19 456, 1/20th of a second later the timer will overflow. Thus, the follow-
ing code will execute a pause of 1/20th of a second:

MOV TH0,#76

;High byte of 19,456 (76 * 256 = 19,456)

MOV TL0,#00

;Low byte of 19,456 (19,456 + 0 = 19,456)

MOV TMOD,#01 ;Put Timer 0 in 16−bit mode

CLR TF0

;Make sure TF0 bit is clear initially

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 456. The next two instructions configure Timer 0 and turn it on. Finally, the
last instruction (JNB TF0,$) reads: jump back to the same instruction if TF0 is
not set. The $ operand means, in most assemblers, the address of the current
instruction.

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 overflows, sets the TF0 bit, and program execution then breaks out
of the loop.

8.3.7

Timing the Length of Events

The MSC1210 provides another useful method to time the length of events.

For example, in order to save electricity in the office, a light switch is measured
to see how long it is turned on each day. When the light is turned on, time must
be measured; when the light is turned off, time is not measured. One option
is 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. Although this method
works well, the MSC1210 provides an easier way of accomplishing this.

Looking again at the TMOD SFR, there is a bit called GATE0. So far, this bit
has always been cleared because the timer is 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.

Simply connect the light switch to pin INT0 (P3.2) on the MSC1210 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 the timer is running.

Advertising