Best way to do longer period timers using PIC?

Thread Starter

spinnaker

Joined Oct 29, 2009
7,830
My project uses a PIC. I have a need to have a timer for longer periods. From minutes up to several hours. It does not need to be very accurate. Accuracy within a few minutes will be just fine.

What is the best way to do this?


I was thinking that I could set my clock to 1MHZ. I could set up an interrupt handler that increments microseconds, when microseconds reaches 1000, it increments milli seconds, when milliseconds reaches 1000, it updates seconds, when seconds reaches 60 it updates minutes etc.

Is there a better way to do this?

I was thinking of using a prescaler and maybe slowing down the clock but I can't figure out a combination that makes sense and is worth doing.
 

Thread Starter

spinnaker

Joined Oct 29, 2009
7,830
Thanks for the link but I do not need a delay I need a timer. The code needs to do other things will the timer is running. I figured the easiest way do do this is through a timer interrupt.

Also ASM code is fine but I prefer C. But even if I just had an algorithm, I think I can figure it out from there.
 

achilez

Joined Mar 23, 2010
6
Enable interrupts on a timer. Set the appropriate prescaler and load the compare match register with a appropriate value -- this combination will get you an interrupt every, say, 50 us. Then in your interrupt service routine, if you want to call your mom every 50 seconds, you can do something like

Rich (BB code):
ISR(your vector here) {
    counter++;

    if (counter == 10^6) //50us * 10^6 = 50secs
        call mom
        counter = 0
    else
       do nothing
}
You could nest several counters with uint64_t storage types and what not, to get arbitrarily long intervals. Hope this helps.
 
Last edited:

t06afre

Joined May 11, 2009
5,934
Your plan to do interrupt on timer is good. The solution will depend on which PIC you use and if this is a low power/battery app. On some PICs you can use a separate 32768Hz crystal to drive one of timers(timer1 most often). Enable interrupt on timer, and apply sleep mode between interrupt. This setup use very little power.
Here is a project you can use to get you started. I think it has some ideas you can pick up, and use. I know you do not want to build a nixie clock ;). But after reading about it I, was thinking about building one myself :)
http://elbastl.sweb.cz/clock.htm
 
Last edited:
Top