Over using timer, calculating exact one second delay

pic

Can you help me to write a macro which generates a one seconds delay by using Timer1 or Timer0 ? In other words, I have tried to write a macro for 1 seconds delay but I could not manage it .Why I am trying to write a macro is because I will use that macro in several place.

If you know more about timer, can you give me general formule when time is calculated ?

EDIT:

pic16f8xx
4MHZ
MPLAB simulation = 5 MHZ

EDIT:

"… [I] actually don't just want a delay, but using interrupts to execute a task later when 1 second has passed while doing other things in the meantime. .."

Best Answer

I would use timer 2 to set up a periodic interrupt. 1 ms (1 kHz frequency) is usually a good interrupt period. At 4 MHz clock frequency you have 1 MHz instruction rate, so 1 ms interrupt would be every 1000 instructions. You should be in and out of the interrupt in a few 10s of instructions, so that is a small overall burden on the processor.

To get long delays, set up a counter that the interrupt routine decrements if it is not zero. When this counter reaches 0, the interrupt routine sets a global flag. If you need 1 ms resolution for your 1 s time, then you make this a 16 bit counter. If 5 ms is enough resolution, then you divide the 1 ms tick in the interrupt routine by 5 to make a 5 ms tick, and decrement a single byte counter every 5 ms. If you really only ever need 5 ms timing, then you can set up the periodic interrupt to be 5 ms (every 5000 instruction cycles).

To use the delay, the forground code clears the delay elapsed flag and writes the delay time in units of 5 ms to the counter. The foreground code checks the flag regularly to see if the delay has elapsed. In the mean time, it can perform other processing.