Searching \ for '[PIC]: Timer1 and Interrupt' in subject line. ()
Make payments with PayPal - it's fast, free and secure! Help us get a faster server
FAQ page: www.piclist.com/techref/microchip/ints.htm?key=interrupt
Search entire site for: 'Timer1 and Interrupt'.

Exact match. Not showing close matches.
PICList Thread
'[PIC]: Timer1 and Interrupt'
2003\03\18@215956 by Jai Dhar

flavicon
face
Hi,

I have been trying to sort out this problem for the last 2 days, and have
done nothing to successfully do so - hopefully you guys will be able to help
me out. Basically, what I'm building is an alarm clock... simple. I figured I
would use Timer 1 on an f877 to generate an interrupt every 500mS (couldn't do
one second since 16 bits couldn't hold it, even with a prescaler). All the
interrupt would be responsible for is incrementing the second register, and
consequently the minute and hour bla bla ... the rest of the functionality
would be done outside of the interrupt (As in outputting the values etc).
Since it interrupts every 500ms, I need a flag to tell whether it's in the 0 -
0.5 second range, or 0.5 - 1 second so I can know when to increment the second
register. I hope I'v explained this much well... so anyway, the check is very
simple. If it is in the 0.5 - 1 second range (ie: back half of one second), I
don't bother continuing in the interrupt since a whole second hasn't elapsed
yet - I just called 'retfie'. If it's on the first half of the second, then
and only then do I increment and so on... my problem (finally) is that the
time between the first half interrupt and second half interrupt aren't even..
they vary by one instruction cycle... and this is because of the check for the
flag. If I remove that check, it interrupts every 500mS as it should (I am
checking all this with the stopwatch in MPSIM Btw). What doesn't make sense to
me is that I set the timer running BEFORE I do the test, so regardless of the
test, the time should already be running. It shouldn't matter if I return from
the interrupt one instruction later, or 20! At least in my understanding...
anyway, that's my long explanation, hopefully you guys can see my obvious flaw
which I can't. My ISR is below: the main code of my program as of now is very
simple, it's just looping endlessly. And I know I do'nt have any 'context
saving' implemented yet in my ISR, but it's coming. I just wanted to get this
working first...

isr
;Stop the Timer and reload with value 0BDF (value I have calculated to work
with 500mS)
T1Stop    ;Macro to stop the timer
banksel TMR1H
movlw 0x0B
movwf TMR1H
banksel TMR1L
movlw 0xDF
movwf TMR1L
;Clear the T1 Interrupt Flag so it doesn't interrupt again when we exit.
T1IFClear

;Start Timer.
T1Start
;Now that Timer 1 has started, we can work out other code.

;First test to see if Timer 1 is in the 0.5 - 1 sec range (_SECONDBIT will be
set), or 0 - 0.5 sec.
;Toggle the bit first, and then continue if it is set (meaning it was
previously cleared).
;This will be our mask to toggle the first bit.
movlw b'10000000'
banksel flagreg
xorwf flagreg,f
;Test _SECONDBIT - skip if it's set, meaning it was clear before.
btfss _SECONDBIT
 retfie
;Increment the seconds register since code is at first half of second.
banksel seconds
movlw 0x01
addwf seconds,f

;I will add the other registers in here etc... once I get this working

retfie


Thank you all again!



----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: PICList Posts must start with ONE topic:
[PIC]:,[SX]:,[AVR]: ->uP ONLY! [EE]:,[OT]: ->Other [BUY]:,[AD]: ->Ads

2003\03\18@223659 by hard Prosser

flavicon
face
A couple of comments
1. It is better to update the timer by adding a correcting value rather
than loadoing it. This way it doesn't matter at all how many clocks have
passed before the update.
2. With some micros, the latency can vary slightly , so either you need to
ensure that the mico is interrupted from the same point each time (eg a
sleep mode) or you may need to introduce a variable delay to ensure you are
hitting the same point in your ISR at  the same clock reading. This is only
really applicable if you are concerned with the exact timing of an output
pulse - so doesn't apply here.

Overall - Add a value to the Timer, rather than load it each time.

Richard P





                   Jai Dhar
                   <spam_OUTjdharTakeThisOuTspamENGMAIL.UWA        To:     .....PICLISTKILLspamspam@spam@MITVMA.MIT.EDU
                   TERLOO.CA>                cc:
                   Sent by: pic              Subject:     [PIC]: Timer1 and Interrupt
                   microcontroller
                   discussion list
                   <PICLISTspamKILLspamMITVMA.MI
                   T.EDU>


                   19/03/03 14:59
                   Please respond to
                   pic
                   microcontroller
                   discussion list






Hi,

I have been trying to sort out this problem for the last 2 days, and have
done nothing to successfully do so - hopefully you guys will be able to
help
me out. Basically, what I'm building is an alarm clock... simple. I figured
I
would use Timer 1 on an f877 to generate an interrupt every 500mS (couldn't
do
one second since 16 bits couldn't hold it, even with a prescaler). All the
interrupt would be responsible for is incrementing the second register, and
consequently the minute and hour bla bla ... the rest of the functionality
would be done outside of the interrupt (As in outputting the values etc).
Since it interrupts every 500ms, I need a flag to tell whether it's in the
0 -
0.5 second range, or 0.5 - 1 second so I can know when to increment the
second
register. I hope I'v explained this much well... so anyway, the check is
very
simple. If it is in the 0.5 - 1 second range (ie: back half of one second),
I
don't bother continuing in the interrupt since a whole second hasn't
elapsed
yet - I just called 'retfie'. If it's on the first half of the second, then
and only then do I increment and so on... my problem (finally) is that the
time between the first half interrupt and second half interrupt aren't
even..
they vary by one instruction cycle... and this is because of the check for
the
flag. If I remove that check, it interrupts every 500mS as it should (I am
checking all this with the stopwatch in MPSIM Btw). What doesn't make sense
to
me is that I set the timer running BEFORE I do the test, so regardless of
the
test, the time should already be running. It shouldn't matter if I return
from
the interrupt one instruction later, or 20! At least in my understanding...
anyway, that's my long explanation, hopefully you guys can see my obvious
flaw
which I can't. My ISR is below: the main code of my program as of now is
very
simple, it's just looping endlessly. And I know I do'nt have any 'context
saving' implemented yet in my ISR, but it's coming. I just wanted to get
this
working first...

isr
;Stop the Timer and reload with value 0BDF (value I have calculated to
work
with 500mS)
T1Stop    ;Macro to stop the timer
banksel TMR1H
movlw 0x0B
movwf TMR1H
banksel TMR1L
movlw 0xDF
movwf TMR1L
;Clear the T1 Interrupt Flag so it doesn't interrupt again when we exit.
T1IFClear

;Start Timer.
T1Start
;Now that Timer 1 has started, we can work out other code.

;First test to see if Timer 1 is in the 0.5 - 1 sec range (_SECONDBIT will
be
set), or 0 - 0.5 sec.
;Toggle the bit first, and then continue if it is set (meaning it was
previously cleared).
;This will be our mask to toggle the first bit.
movlw b'10000000'
banksel flagreg
xorwf flagreg,f
;Test _SECONDBIT - skip if it's set, meaning it was clear before.
btfss _SECONDBIT
 retfie
;Increment the seconds register since code is at first half of second.
banksel seconds
movlw 0x01
addwf seconds,f

;I will add the other registers in here etc... once I get this working

retfie


Thank you all again!



----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: PICList Posts must start with ONE topic:
[PIC]:,[SX]:,[AVR]: ->uP ONLY! [EE]:,[OT]: ->Other [BUY]:,[AD]: ->Ads

--
http://www.piclist.com hint: PICList Posts must start with ONE topic:
[PIC]:,[SX]:,[AVR]: ->uP ONLY! [EE]:,[OT]: ->Other [BUY]:,[AD]: ->Ads

2003\03\18@224323 by Jai Dhar

flavicon
face
Quoting Richard Prosser <.....Richard.ProsserKILLspamspam.....ENERGY.INVENSYS.COM>:

> A couple of comments
> 1. It is better to update the timer by adding a correcting value rather
> than loadoing it. This way it doesn't matter at all how many clocks have
> passed before the update.
> 2. With some micros, the latency can vary slightly

Granted latency can vary - but keep in mind I'm doing this in MPSIM right now,
and I doubt this accounts for latency. Especially since it's EXACTLY one clock
pulse off every other interrupt. Same goes for adding it - as far as the
simulator is concerned, loading the timer will take the same amount of time no
matter what. But I will keep this in mind when trying this out for real. Is
adding better because I don't have to wait for X amount of cycles before the
timer updates?? (I think this is what you were referring to, but couldn't tell
for sure).

, so either you need to
{Quote hidden}

----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: PICList Posts must start with ONE topic:
[PIC]:,[SX]:,[AVR]: ->uP ONLY! [EE]:,[OT]: ->Other [BUY]:,[AD]: ->Ads

2003\03\18@231949 by Ned Konz

flavicon
face
On Tuesday 18 March 2003 06:59 pm, Jai Dhar wrote:
> my problem (finally) is that the
> time between the first half interrupt and second half interrupt
> aren't even.. they vary by one instruction cycle... and this is
> because of the check for the flag. If I remove that check, it
> interrupts every 500mS as it should (I am checking all this with
> the stopwatch in MPSIM Btw)

I seem to recall someone complaining about the same thing with MPSIM
and hearing from Microchip that there was a timing bug.

The timer itself will generate periodic interrupts reliably, though
latency may vary depending on what's being done at the time (i.e.
whether you're inside a 2-cycle instruction or not when the interrupt
fires).

--
Ned Konz
http://bike-nomad.com
GPG key ID: BEEA7EFE

--
http://www.piclist.com hint: PICList Posts must start with ONE topic:
[PIC]:,[SX]:,[AVR]: ->uP ONLY! [EE]:,[OT]: ->Other [BUY]:,[AD]: ->Ads

2003\03\19@035212 by daniel_sweet

picon face
I think it was me who was complaining previously ; ). Sounds like you may have seen a similar issue, below are microchips two responses.

DAN

Reply1:
Daniel

I apologize for the delay. I do not know what happened to your first email.

I tried out the code and the both the interrupt latency and the delayed
increment after writes to the timer seem to be incorrectly simulated. Since
there is one interrupt and two writes to the timer, this probably accounts
for the three cycles missing in the simulation. I will report the issue to
our developers to get fixed. As a general rule, if the part and the
simulator behave differently, the part is right and the simulator is wrong!

Sincerely,

Mike Garbutt
Sr. Applications Engineer
Microchip Technology

Reply2:

Daniel

When a write occurs to the timer (eg. clrf TMR0L), the timer will not
increment on the next instruction cycle. Please see the Timer0 chapter of
the PIC18C MCU Family Reference Manual for details:

www.microchip.com/download/lit/suppdoc/refernce/golden/indgate/39513.pdf
http://www.microchip.com/1010/suppdoc/refernce/index.htm

When an interrupt happens, there is a fixed number of instruction cycles
that occur before the first interrupt instruction is executed. In the
PICmicro architecture, the next instruction is fetched while the current
instruction is executed. When an interrupt occurs the current execution
completes, the prefetched instruction is flushed skipping a cycle, the
program branches and skips another cycle while it fetches the first
interrupt instruction. This is shown in Figure 13-3 in the Timer0 chapter
of the reference manual.

The simulator should simulate normal timing loops correctly. All program
branches will flush the prefetch buffer and add an extra cycle to the
execution time. Also, the PIC18 parts have some two word instructions that
take an extra cycle.

Sincerely,

Mike Garbutt
Sr. Applications Engineer
Microchip Technology






{Original Message removed}

2003\03\19@074412 by Jai Dhar

flavicon
face
..so for once, it's not actually me :-) Question though.. was your case
varying by more than one cycle, or just one? It would be nice if I could
verify this with the part (since the part is always right and the sim is
wrong, lol), but I have no idea how I'm going to differentiate between 500ms
and 500.001 ms, heh. Normally, I wouldn't care, but if I'm off 1uS every
second, that's 1uS * 3600 sec/hour * 12 hour/day * 30 day's/month = 1.3
seconds per month. Maybe I'm just beeing too picky :-)

Quoting KILLspamdaniel_sweetKILLspamspamNTLWORLD.COM:

{Quote hidden}

www.microchip.com/download/lit/suppdoc/refernce/golden/indgate/39513.pdf
{Quote hidden}

> {Original Message removed}

2003\03\19@080732 by Olin Lathrop

face picon face
>  I have been trying to sort out this problem for the last 2 days, and
> have done nothing to successfully do so - hopefully you guys will be
> able to help me out. Basically, what I'm building is an alarm clock...
> simple. I figured I would use Timer 1 on an f877 to generate an
> interrupt every 500mS (couldn't do one second since 16 bits couldn't
> hold it, even with a prescaler).

That depends on the clock rate you are running at.  Which is ...?

You could also give timer 1 its own crystal.  At 32,768Hz you get two
seconds without the prescaler.

> my problem (finally) is that the time between the first half
> interrupt and second half interrupt aren't even.. they vary by one
> instruction cycle...

So?  I don't see the problem.  It sounds to me like it doesn't matter how
long the interrupt routine takes as long as it doesn't exceed 500mS.

> isr
>  ;Stop the Timer and reload with value 0BDF (value I have calculated to

Ah, there's the problem.  Let the timer free run and produce periodic
interrupts.  Timer 2 would be better for this since it has a period
register for this purpose.  Timer 1 can also do this in conjunction with
one of the CCP modules.  All else being equal, I would use timer 2 to
generate a periodic interrupt at some sub-multiple of a second, and use a
counter to get whole seconds.  This is just like using a seconds counter
to get whole minutes.  You are essentially doing this already, except that
your counter is one bit wide and therefore you called it a flag.


*****************************************************************
Embed Inc, embedded system specialists in Littleton Massachusetts
(978) 742-9014, http://www.embedinc.com

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@081154 by Jinx

face picon face
> and 500.001 ms, heh. Normally, I wouldn't care, but if I'm off
> 1uS every second, that's 1uS * 3600 sec/hour * 12 hour/day
> * 30 days /month = 1.3 seconds per month. Maybe I'm just
> beeing too picky :-)

Without the oscillator being temperature-compensated I doubt if
you'd notice 1.3 seconds amongst the probable drift, and that's
on top of the base error if you haven't fine-tuned the frequency

Can you change the crystal so that you let the timer roll over and
avoid re-loads ?

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@083719 by Jai Dhar

flavicon
face
Quoting Jinx <RemoveMEjoecolquittTakeThisOuTspamCLEAR.NET.NZ>:

> > and 500.001 ms, heh. Normally, I wouldn't care, but if I'm off
> > 1uS every second, that's 1uS * 3600 sec/hour * 12 hour/day
> > * 30 days /month = 1.3 seconds per month. Maybe I'm just
> > beeing too picky :-)
>
> Without the oscillator being temperature-compensated I doubt if
> you'd notice 1.3 seconds amongst the probable drift, and that's
> on top of the base error if you haven't fine-tuned the frequency
>
> Can you change the crystal so that you let the timer roll over and
> avoid re-loads ?

I *could* (I would really like to implement that since it would save a lot of
work) - but what value crystal would I need for this? Or what value is
commonly used I should say... Timer 1 is 16-bit, so it can count 65 536
values. If each value is incremented on one instruction cycle, I would need 65
536 instruction cycles per second in order to give me a one second interrupt,
or a clock rate of 262.144 KHz. I could be wrong in this calculation, but
doesn't that seem a bit slow??

And in response to the previous email:
>> my problem (finally) is that the time between the first half
>> interrupt and second half interrupt aren't even.. they vary by one
>> instruction cycle...

>So?  I don't see the problem.  It sounds to me like it doesn't matter how
>long the interrupt routine takes as long as it doesn't exceed 500mS.

Of course it's a problem. One interrupt has a period of 500mS from the last,
and the other has a period of 500.001mS. I'm just trying to minimize error
here... and that's with the little code that I have right now. When I add more
code to the ISR, the gap seems to lengthen - but as was pointed at, this seems
to be a bug in MPSIM.

>
> --
> http://www.piclist.com hint: The list server can filter out subtopics
> (like ads or off topics) for you. See http://www.piclist.com/#topics
>




----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@084129 by Jai Dhar

flavicon
face
Quoting Olin Lathrop <spamBeGoneolin_piclistspamBeGonespamEMBEDINC.COM>:

> >  I have been trying to sort out this problem for the last 2 days, and
> > have done nothing to successfully do so - hopefully you guys will be
> > able to help me out. Basically, what I'm building is an alarm clock...
> > simple. I figured I would use Timer 1 on an f877 to generate an
> > interrupt every 500mS (couldn't do one second since 16 bits couldn't
> > hold it, even with a prescaler).
>
> That depends on the clock rate you are running at.  Which is ...?
>

4Mhz.

{Quote hidden}

Reading the mid-range manual, you are right Olin - Timer 2 definitely seems
more fit for my purpose. This way I can avoid re-load's... doesn't really
explain why my periods are off, but it is still better. Thank you.

{Quote hidden}

----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@085827 by Jinx

face picon face
> I *could* (I would really like to implement that since it would
> save a lot of work) - but what value crystal would I need for
> this?

What Olin has suggested would be fine

> Or what value is commonly used I should say...

> or a clock rate of 262.144 KHz. I could be wrong in this calculation,
> but doesn't that seem a bit slow??

Not as slow as 32768 !! 262144 (h4000) crystals are available
but I doubt if they are as cheap as the much more common 32k
(which BTW can be scavenged for nothing from all sorts of scrap
boards)

If you check the specs you'll find that power consumption goes down
as frequency and Vcc are reduced, which is what you want for
presumably a 32kHz, battery-operated clock. If you have a mains PSU
then mains cycles would be preferable as the defaut time base and
keep the crystal as back-up when necessary

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@090625 by Jai Dhar

flavicon
face
Quoting Jinx <TakeThisOuTjoecolquittEraseMEspamspam_OUTCLEAR.NET.NZ>:

{Quote hidden}

I considered this at first (60Hz, correct?), but I wasn't sure how to
basically extract the mains cycles into clock pulses - any help there? I would
use these cycles as an external 'crystal' for Timer 2 instead of the internal
pic one then, correct? If I could get the mains cycles extracted, that would
be great since I wouldn't have to worry about accuracy. They are more accurate
than crystals, correct... except in Argentina (I think) where a short while
back, they were losing time on clocks due to cutbacks at their electrical
facilities :-)

Thank you once again,

Jai

>
> --
> http://www.piclist.com hint: The list server can filter out subtopics
> (like ads or off topics) for you. See http://www.piclist.com/#topics
>




----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@091919 by Olin Lathrop

face picon face
> I considered this at first (60Hz, correct?),

Depends on where you live.  60Hz in North America, 50Hz in Europe and you
can't count on much most everywhere else.  In some places it's easier to
set your clock by the daily power outage :-)

> I would use these cycles as an external 'crystal' for Timer 2 instead
> of the internal pic one then, correct?

No, timer 2 doesn't have its own oscillator.  I would just take an
interrupt every power cycle and count time that way.

> They are more accurate than crystals, correct... except in
> Argentina (I think)

I wouldn't trust the power in any country where the leader is addressed
"Generalissimo", "Your Highness", or "Comrade".


*****************************************************************
Embed Inc, embedded system specialists in Littleton Massachusetts
(978) 742-9014, http://www.embedinc.com

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@092659 by Jai Dhar

flavicon
face
Quoting Olin Lathrop <RemoveMEolin_piclistspamTakeThisOuTEMBEDINC.COM>:

> > I considered this at first (60Hz, correct?),
>
> Depends on where you live.  60Hz in North America, 50Hz in Europe and you
> can't count on much most everywhere else.  In some places it's easier to
> set your clock by the daily power outage :-)
>
> > I would use these cycles as an external 'crystal' for Timer 2 instead
> > of the internal pic one then, correct?
>
> No, timer 2 doesn't have its own oscillator.  I would just take an
> interrupt every power cycle and count time that way.
>

This might present a problem, coding wise.. I plan on running both a 7-seg and
Hitachi LCD display for this project - if I use interrupts every 1/6th of a
uS, then that will definitely be interrupting the display refreshing process.
This is fine if I code my interrupts very carefully with good context saving,
but wouldn't it be easier then to use Timer 1 with it's own oscillator (the
power cycles) and use reloading? This way I know my refreshing process won't
get interrupted (since it will only take a few ms).

> > They are more accurate than crystals, correct... except in
> > Argentina (I think)
>
> I wouldn't trust the power in any country where the leader is addressed
> "Generalissimo", "Your Highness", or "Comrade".
>

You have a point :-)
{Quote hidden}

----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@094043 by Micro Eng

picon face
If you have an AC source (rather than running on a battery) what about just
using an optocoupler and go off the 60Hz (or 50Hz)pulse?




_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*
http://join.msn.com/?page=features/junkmail

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@104312 by Alan B. Pearce

face picon face
>if I use interrupts every 1/6th of a uS,


I hope you mean every 1/6mS. You will have a problem trying to do any usable
interrupt every 1/6uS on any PIC.

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@112513 by Jai Dhar

flavicon
face
Now that I have my brain together, yes, I did mean this :-) I temporarily
thought that mains was 60 Mhz instead of Hz... my bad.

Quoting "Alan B. Pearce" <A.B.PearceEraseMEspam.....RL.AC.UK>:

{Quote hidden}

----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@134102 by Olin Lathrop

face picon face
> This might present a problem, coding wise.. I plan on running both a
> 7-seg and Hitachi LCD display for this project - if I use interrupts
> every 1/6th of a uS, then that will definitely be interrupting the
> display refreshing process.

60Hz is 1/60 of a second, which is once every 16.7mS, or once every 83000
instructions if the PIC is running at 20MHz.  That shouldn't be a burden
on the rest of the code.


*****************************************************************
Embed Inc, embedded system specialists in Littleton Massachusetts
(978) 742-9014, http://www.embedinc.com

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@140338 by Dale Botkin

flavicon
face
In CCS C, but should translate fairly easily to other C compilers or to
ASM:

int32 clock;
struct time {
   char seconds;
   char minutes;
   char hours;
   } real_time;


////////////////////////////////////////////////////////////////////////////
// Kick internal tick counter.  This should happen every 16384 clocks,
// or every 3.2ms.
//
// We start out with clock loaded with 5016384 -- that's 5000000 clocks per
// second, plus 16384 for one interrupt time.  Each time the interrupt occurs
// we subtract 16384 (number of elapsed clocks).  When we have less than one
// interrupt left, we add 5000000 and increment the number of seconds.  This
// way our long term timer error *should* be zero -- anything left over on
// one interrupt cycle gets added to the next.  Thanks to PIClist members
// for this idea.

#int_rtcc
void tmr0_int() {

   clock -= 16384;
   if(clock < 16384) {
       real_time.seconds++;
       clock += 5000000;
   }
   if(elapsed.seconds == 60) {
       real_time.minutes++;
       real_time.seconds = 0;
   }
   if(elapsed.minutes == 60) {
       real_time.hours++;
       real_time.minutes = 0;
   }
}


In main():

// TMR0 gets internal clock, /4 prescaler
setup_counters(RTCC_INTERNAL, RTCC_DIV_64);
clock = 5016384;

I use this all the time.  You end up with a clock that's just as accurate
as your crystal.  There are more code-efficient ways of doing this, but I
usually have a 16F877 to play with when I'm doing real time anyway so it
hasn't been an issue.  I believe the PICList web site has an ASM
implementation.

Dale
--
It's a thankless job, but I've got a lot of Karma to burn off.

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\19@172756 by Jinx

face picon face
part 1 5582 bytes content-type:text/plain; (decoded 7bit)

> I considered this at first (60Hz, correct?), but I wasn't sure how
> to basically extract the mains cycles into clock pulses - any help
> there ?

Attached is one of the methods I use. The PSU is 17VDC to get
a 13.8V battery float voltage and the main 5V. The transformer
AC generates 20ms interrupts for a cycles counter which when
done advances the seconds counter. It's a base program that I
customise/improve for individual apps. Pretty complete in itself,
although hardly optimised, it's more of a library routine. The
crystal may change, use of an external timer or SLEEPing the
PIC etc

You'll probably have your own tweaks. For a start you'd need to
change the ticks counter from 50 to 60

Another pin is used to detect whether the PIC is being powered
from mains (by tapping the DC after the bridge) or battery and
selects either b0 or Timer0 interrupts. To avoid any timing errors
you should synchronise the two IRQ sources, eg by clearing the
timer register periodically in synch with the external IRQ, so that
any switching between them neither loses nor gains time. Generally
mains outages are so rare (here anyway) that this is not a major
concern

One thing to be aware of when timing testing. Mains frequency
does vary with demand and you should measure over at least
a whole 24 hour period

This particular s/w is for a 3.2768MHz crystal and a pair of 30-
second solenoid movements so no minutes or hours. An LED is
flashed for 1 IRQ period every second

(not been up long and only one cup of tea so far - hope I've not
blundered anywhere)

;==================================================

  list P = 16F628
  include "P16F628.inc"

errorlevel -305, -302, -306

__CONFIG _CP_ALL & _XT_OSC & _WDT_OFF & _PWRTE_OFF & _BODEN_OFF & _LVP_OFF

;================================================
;        Macros for bank and page selection
;================================================

bank0    macro
        bcf    status,rp0
        bcf    status,rp1
        bcf    status,irp
        endm

bank1    macro
        bsf    status,rp0
        bcf    status,rp1
        bcf    status,irp
        endm

#define vsense    portb,4
#define drive1    portb,3
#define led       portb,5
#define drive2    portb,6

#define carry     status,0
#define zero      status,2

        cblock 0x20

        ticks
        secs
        dcount

        endc

;================================================

        org     0x00         ;start address
        goto    init

        org     0x04         ;IRQ address
        goto    irq

init     clrf    status       ;bank0

        clrf    porta
        clrf    portb
        clrf    t1con        ;Timer1 off, no pre-scaler, use Fosc
        clrf    intcon
        clrf    pir1
        clrf    tmr1h
        clrf    tmr1l

        bank1
        movlw   b'00000000'

;                     0
;                      0
;                       0
;                        0
;                         0

        movwf   trisa

        movlw   b'00001001'

;                  0
;                   0          Drive2
;                    0         LED
;                     0        Drive1
;                      1       voltage sense
;                       0
;                        0
;                         1    AC input

        movwf   trisb
        movlw   b'10000101'   ;pullups off, TMR p/s = 64 = 50 IRQ/sec
        movwf   option_reg
        bank0

        movlw   0x07         ;turn comparators off
        movwf   cmcon

        clrf    ticks
        clrf    secs

        bsf     led          ;LED off

        movlw   0x32         ;50 cycles or TMR0 rollovers/sec
        movwf   ticks
        movlw   0x1e         ;30-second movement
        movwf   secs
        clrf    dcount       ;clear delay counter

        bcf     intcon,t0if
        bcf     intcon,intf
        call    power        ;test power source
        bsf     intcon,gie   ;IRQs enabled

wait     call    power        ;wait here for IRQ
        nop
        goto    wait

;===================================================

irq      bcf     intcon,t0if  ;clear flags
        bcf     intcon,intf

tick     decfsz  ticks,f
        goto    led01
        goto    load32       ;ticks=0

led01    movlw   0x01         ;turn LED on if ticks=1
        xorwf   ticks,w
        btfss   zero
        goto    exit         ;ticks <> 1
        bcf     led          ;LED on until next IRQ
        goto    exit

load32   movlw   0x32
        movwf   ticks        ;re-load ticks counter
        bsf     led          ;LED off

        decfsz  secs,f       ;30-second counter
        goto    exit
        movlw   0x1e         ;re-load seconds counter
        movwf   secs

pulse    bsf     drive1       ;drives on
        nop
        bsf     drive2

        call    delay        ;hold for about 1ms

        bcf     drive1
        nop
        bcf     drive2

exit     retfie

;==================================================

power    btfss   vsense       ;if = 1 then power is mains
        goto    battery

mains    bcf     intcon,t0ie  ;timer off
        bsf     intcon,inte  ;b0 on
        return

battery  bsf     intcon,t0ie  ;timer on
        bcf     intcon,inte  ;b0 off
        return

delay    incfsz  dcount,f
        goto    $-1
        return

end



--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics




part 2 2850 bytes content-type:image/gif; (decode)


part 3 2 bytes
-

2003\03\19@175446 by Jinx

face picon face
> If you have an AC source (rather than running on a battery)
> what about just using an optocoupler and go off the 60Hz
> (or 50Hz)pulse?

Ah yes, thanks for reminding me. The diagram I sent using an
AC tap from the PSU does suffer from a short switching delay.
If AC is removed, the voltage on Vsense stays high for a bit
of a second (because of the PSU filter caps) after the AC
waveform has gone. Therefore the PIC doesn't switch over to
internal IRQs immediately. Not a big issue so far but it should
be corrected. An OC is a better solution and one I've looked at.
It means changing the s/w to interrogate what's going on with b0
rather than a Vsense pin

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics

2003\03\20@112919 by Bob Ammerman

picon face
Perhaps the interrupted code is being interupted in the middle of a one
cycle instruction in one case, and a two cycle instruction in the other.

Look at using the compare functionality of the CCP module.

Bob Ammerman
RAm Systems


{Original Message removed}

2003\03\21@092419 by Bob Ammerman

picon face
Assuming a 20MHz clock (5MHz instruction) rate....

Setup timer 1 to count instruction cycles with a prescaler of 8. This will
result in a counting frequency of 625,000 per second.

Setup CCP1 as follows:

CCP1M = B'1011'

CCPR1H:CCPR1L = 62499

These settings will cause timer 1 to count from 0 through 62499 and then
back to zero again. On each reset, the CCP1IF flag is set. Thus you will get
exactly ten interrupts per second.

(btw: I am not sure if you need to set CCPR1H:CCPR1L to 62499 or 62500).

Bob Ammerman
RAm Systems

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email EraseMElistservspammitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@115127 by Jai Dhar

flavicon
face
Just out curiosity, how do you guys test for accuracy of your clock (for those
who have built one). Aside from the obvious comparing it to another clock, are
there any other methods that you guys use for testing how far your clock
drifts?

Thank you,

jai



----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email RemoveMElistservEraseMEspamEraseMEmitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@124527 by Olin Lathrop

face picon face
> Just out curiosity, how do you guys test for accuracy of your clock (for
those
> who have built one). Aside from the obvious comparing it to another
clock, are
> there any other methods that you guys use for testing how far your clock
> drifts?

Let it run a day or more and compare to WWV before and after.  Instead of
receiving WWV directly, you can compare to a clock that receives WWVB.
You can also synchronize your computer clock to one of several NIST time
servers, then use it as a reference.  I would NOT use a local radio
station time beep as a reference.  Some are quite good and receive a
signal from a network that is carefully synchronized to NIST (like WBZ
here in the Boston MA area), but others use a much more sloppy approach.
This was a while ago, but I knew of one local radio station that had a
clock automatically generate the hourly beep, but this clock was free
running and set by hand whenever someone felt like it.


*****************************************************************
Embed Inc, embedded system specialists in Littleton Massachusetts
(978) 742-9014, http://www.embedinc.com

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email RemoveMElistservspam_OUTspamKILLspammitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@131946 by Banjo Spam

picon face
I second that. I currently have on my desk just such a
project. Running for 12 hours so far. I am comparing
it to WWV (in the US) on one of 2500 kHz, 5000 kHz,
10000 kHz, 15000 kHz (also 20000 kHz but I don't
usually receive it that well) on my shortwave radio.

More information at:
http://www.boulder.nist.gov/timefreq/stations/wwv.html

Be careful of the "radio" or "atomic" clocks that get
their time from WWVB. They will sync up, often, only
at night. Unless they have an indicator of when they
last synced, you won't know how many days it's been
since the time was set accurately. They can be off by
a second or two per day, if not synced.

For information about these WWVB clocks:
http://www.boulder.nist.gov/timefreq/stations/radioclocks.htm

--- Olin Lathrop <RemoveMEolin_piclistTakeThisOuTspamspamEMBEDINC.COM> wrote:
{Quote hidden}

*****************************************************************
{Quote hidden}

__________________________________________________
Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop!
http://platinum.yahoo.com

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email RemoveMElistservKILLspamspammitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@140416 by Jai Dhar

flavicon
face
Great, I will look into this WWV (I didn't even know it existed). Thank you
all once again!

Quoting Banjo Spam <banjospamSTOPspamspamspam_OUTYAHOO.COM>:

{Quote hidden}

----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email @spam@listserv@spam@spamspam_OUTmitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@143438 by Olin Lathrop

face picon face
> Great, I will look into this WWV (I didn't even know it existed). Thank
> you all once again!

WWV is the NIST (National Institute of Standards and Technology) public
time broadcasts from near Boulder Colorado.  The carrier frequency and the
time encoded onto it is derived from the NIST atomic clocks, and is
traceable in a legal sense.  This works well if you are most places in
North America.  NIST also runs WWVH in Hawaii to cover the central Pacific
region.  Both broadcast on nice round number frequencies, like 5MHz,
10MHz, etc.

Other countries have other time broadcasts from different locations.
Canada has CHU, which I think originates from someplace in Quebec or
Ontario.  I think the British Royal Naval Observatory also runs a time
standard and public transmitter.  Probably a number of other countries do
too.  Where are you located?

The time signal from GPS is also very accurate, and of course available
anywhere in the world.


*****************************************************************
Embed Inc, embedded system specialists in Littleton Massachusetts
(978) 742-9014, http://www.embedinc.com

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email spamBeGonelistservspamKILLspammitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@144257 by Jai Dhar

flavicon
face
I'm in Canada - but I don't know, something about trusting 'Canadian'
standards doesn't make me feel as comforted as trusting the US institution
with a cool name like NIST :-) I'm sure there is no difference between the
two ,correct? (aside from location)


Quoting Olin Lathrop <.....olin_piclistspam_OUTspamEMBEDINC.COM>:

{Quote hidden}

----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email TakeThisOuTlistservKILLspamspamspammitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@145311 by Olin Lathrop

face picon face
> I'm in Canada - but I don't know, something about trusting 'Canadian'
> standards doesn't make me feel as comforted as trusting the US
> institution with a cool name like NIST :-) I'm sure there is no
> difference between the two ,correct? (aside from location)

I'm sure both are far more accurate than you need for your purpose.  It
may be a matter of convenience and signal strength.  I grew up in Salem MA
and used to use CHU to set the clocks because it came in a lot clearer
then WWV.  That's what leads me to believe that CHU is in eastern Canada
someplace.  If you're in western Canada, WWV is probably better.


*****************************************************************
Embed Inc, embedded system specialists in Littleton Massachusetts
(978) 742-9014, http://www.embedinc.com

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email .....listservspamRemoveMEmitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@161616 by Larry Bradley

flavicon
face
CHU is the Canadian Time station, located here in Ottawa. It's time
standard is controlled by the National Research Council of Canada' standard
group - the same as NIST, and to the same precision as NIST - they all use
the same techniques.

CHU broadcasts on a variety of frequencies, one of which as around 3.335
MHZ I think.

I needed accurate time of day on a PIC project - I used my GPS receiver and
it's RS232 output - a program read the time from the GPS and compared it to
the time from the PIC over a period of a week or so, and it computed a
correction factor for my interrupt routine to compensate for the
(in)accuracy of the PIC's xtal oscillator.

You can do the same thing by using the clock on your PC, if you sync the
clock to the Internet time standards. I did that as well, but the GPS was
more convenient.

Larry

At 02:42 PM 3/21/2003 -0500, you wrote:
>I'm in Canada - but I don't know, something about trusting 'Canadian'
>standards doesn't make me feel as comforted as trusting the US institution
>with a cool name like NIST :-) I'm sure there is no difference between the
>two ,correct? (aside from location)
>

Larry Bradley
Orleans (Ottawa), Ontario, CANADA

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email RemoveMElistservspamspamBeGonemitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@162621 by Jai Dhar

flavicon
face
Great, so now that I have these sources for testing the accuracy, what kind of
crystal should I be using for this application? Reading some app. notes on
google (From various sites), it seems that Quartz crystals are used in watches
most frequently (duh). Are these normally available for use with PIC's? Does
anyone have any specific model numbers they recommend so I can purchase a few.
Right now I'm using a resonator, so I don't expect the accuracy to be that
high (although from what I saw last nite, it drifted about one second in 6
hours).

Quoting Larry Bradley <spamBeGonelhbradley@spam@spamspam_OUTIGS.NET>:

{Quote hidden}

----------------------------------------
This mail sent through http://www.mywaterloo.ca

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email listservEraseMEspammitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@164910 by Olin Lathrop

face picon face
> Great, so now that I have these sources for testing the accuracy, what
> kind of crystal should I be using for this application? Reading some
> app. notes on google (From various sites), it seems that Quartz
> crystals are used in watches most frequently (duh). Are these normally
> available for use with PIC's?

Yup, you can use the same crystals a watch would.  You could use the
32768Hz watch crystal to run the timer 1 oscillator and be used as a real
time clock.

> Right now I'm using a
> resonator, so I don't expect the accuracy to be that high (although
> from what I saw last nite, it drifted about one second in 6 hours).

You were very lucky.  That works out to 46ppm, which is much smaller than
the worst case error of a ceramic resonator.


*****************************************************************
Embed Inc, embedded system specialists in Littleton Massachusetts
(978) 742-9014, http://www.embedinc.com

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email RemoveMElistservEraseMEspamspam_OUTmitvma.mit.edu with SET PICList DIGEST in the body

2003\03\21@165132 by Larry Bradley

flavicon
face
Digikey sells them  You want a parallel xtal (in the catalog, they will
show a column headed "load cap". It will say "series" or something like
"20pf". The ones with a capacitor value are parallel xtals.

For example, on page 560 of the Digikey catalog (online at
http://www.digikey.com), you will find the ECS xtals. The Digikey part number
X439ND is a 20 MHZ parallel (20 pf) xtal, 50 ppm over the specified temp
range, 30 ppm at 25 deg C. All for $.80.

Larry

At 04:26 PM 3/21/2003 -0500, you wrote:
>Great, so now that I have these sources for testing the accuracy, what kind of
>crystal should I be using for this application? Reading some app. notes on
>google (From various sites), it seems that Quartz crystals are used in watches
>most frequently (duh). Are these normally available for use with PIC's? Does
>anyone have any specific model numbers they recommend so I can purchase a few.
>Right now I'm using a resonator, so I don't expect the accuracy to be that
>high (although from what I saw last nite, it drifted about one second in 6
>hours).

Larry Bradley
Orleans (Ottawa), Ontario, CANADA

--
http://www.piclist.com#nomail Going offline? Don't AutoReply us!
email @spam@listservRemoveMEspamEraseMEmitvma.mit.edu with SET PICList DIGEST in the body

More... (looser matching)
- Last day of these posts
- In 2003 , 2004 only
- Today
- New search...