Using Timers to Measure Time

So far, only four of the eight bits have been defined. That is because the other four bits of the SFR do not have anything to do with timers—they have to do with interrupts and they will be discussed in Chapter 10, Interrupts.

Table 8−4 contains the bit address column because this SFR is bit-address- able. That means in order to set bit TF1, which is the highest bit of TCON, you execute the command:

MOV TCON, #80h

However, because this SFR is bit-addressable, you can 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 starting or stopping a timer, the other values in TCON should not be modified, so take advantage of the fact that the SFR is bit-addressable.

8.3.5Initializing a Timer

After discussing the timer-related SFRs, it is time to write code that initializes the timer and starts it running. As shown previously, the timer mode should be decided upon. In this case, a 16-bit timer that runs continuously will be used; that is to say, it is not dependent on any external pins.

We must first initialize the TMOD SFR. When working with Timer 0, the low four bits of TMOD will be used. The first two bits, GATE0 and CT0 are both 0, be- cause the timer needs to be independent of the external pins. 16-bit mode is timer mode 1, so T0M1 must be cleared and T0M0 must be set. Effectively, bit 0 of TMOD is the only bit that should be turned on. Therefore, to initialize the timer, 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, set the TR0 bit by executing the instruction:

SETB TR0

Upon executing these two instructions, Timer 0 will immediately begin count- ing, being incremented once every instruction cycle (every 12 crystal pulses).

8.3.6Reading the Timer

There are two common ways of reading the value of a 16-bit timer; which one is used depends on the specific application. The actual value of the timer may be read as a 16−bit number, or the timer may be detected when overflowed.

8.3.6.1Reading the Value of a Timer

If the timer is in 8-bit mode—that is, either 8-bit auto-reload mode, or in split- timer mode—reading the value of the timer is simple. Just read the 1-byte val- ue of the timer and that is it.

Timers8-9

Page 83
Image 83
Texas Instruments MSC1210 manual Initializing a Timer, Reading the Timer