Editor:  ms=millisecond (one thousandth) and uS=microsecond (one millionth)

To create a very precise timer with a simple structure, you can use the Timer1 (when available!!) that is a 16 bit timer and gives you up to 65 ms delay with 1uS resolution, or very long time delay if you use the prescaler (i.e. 1 second delay with 16 uS resolution!).

 Its use is very simple:

- Set the TMR1 with the negative value of the delay you want (FFFF – x)

- clear the overflow flag (TMR1IF)

- start the timer

- wait until TMR1IF is high.

This technique has a very, very big advantage.  While the timer is running, your software can do other tasks, and only the overflow flag must be tested!  If you enable the timer interrupt, this process becomes a transparent background process, as when the time is over the interrupt routine is called, the timer is reloaded and some flags are set.   Your main program has only to test these flags to verify if the programmed time interval has elapsed or not.

A typical application is a flashing light  driven by a RC channel.  If you have a flashing rate of approx 0.3 seconds, you can set-up the timer for this value, start the timer and then you can do some samples of the command line (say 10) that can take approximately 200 ms, then you need some other time to do some calculations to obtain the average value on the command. When you have finished all these operation you can poll the timer flag to determine the exact end of the flash period.

For the output, the suggestion is to use a register in which a copy of the current output state is saved.  In this way, it is easy to refresh the output at regular intervals to avoid having an output bit stay in a wrong state for long time if an external event has modified the current output state.   It is also easier to set-up multiple bit using and/or mask on the output copy register

Michele - December 2003