Best way to do longer period timers using PIC?

Discussion in 'Embedded Systems and Microcontrollers' started by spinnaker, Jun 3, 2010.

  1. spinnaker

    Thread Starter AAC Fanatic!

    Oct 29, 2009
    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.
  2. jpanhalt


    Jan 18, 2008
  3. spinnaker

    Thread Starter AAC Fanatic!

    Oct 29, 2009
    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.
  4. achilez

    New Member

    Mar 23, 2010
    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

    Code ( (Unknown Language)):
    2. ISR(your vector here) {
    3.     counter++;
    5.     if (counter == 10^6) //50us * 10^6 = 50secs
    6.         call mom
    7.         counter = 0
    8.     else
    9.        do nothing
    10. }
    You could nest several counters with uint64_t storage types and what not, to get arbitrarily long intervals. Hope this helps.
    Last edited: Jun 3, 2010
  5. t06afre

    AAC Fanatic!

    May 11, 2009
    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 :)
    Last edited: Jun 4, 2010