Tell me more ×
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It's 100% free, no registration required.

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. .."

share|improve this question
2  
There's no such thing as a generic "Timer1". Tell us which controller you're using, and at what frequency it's clocked. – stevenvh Apr 12 '12 at 8:16
Do you really need to use the timer, e.g. to save power? If not, you could just use a busy wait loop instead. – noah1989 Apr 12 '12 at 8:26
In your updated question you specify, that you want to use the CPU for "more efficiently", which implies that you 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. could you explain what exactly you're trying to do? – noah1989 Apr 12 '12 at 8:33
@noah1989 thanks for your comment. Please see my edit version – user1315050 Apr 12 '12 at 10:18

1 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.