Harrison Cooper wrote: > I've found every now and then, noisy power will cause my counters to > misbehave, so rather than fight that, I'll just add a crystal. My inclination would be to "fight it" in the spirit of making software do what software can do. You imply that you are using an R-C oscillator. This can most probably be made sufficiently accurate to distinguish 50 Hz from 60 Hz, so it should be able to "auto-seek" the line frequency. http://www.elmelectronics.com/Products/EBench/EBench.htm#ELM440 does something like this using the 12C508 and its internal oscillator. I'd look at starting up a counter to determine an approximate second and count transitions over this period. If you have more than 55, it's a 60 Hz system. This of course could represent spurious counting on noise but you should pre-condition the mains transitions with a 5 ms software "debounce". This is readily implemented with a(n approximate) 1 ms clock "tick" derived from TMR0 overflows (you have to make your own overflow flag on teh 16C54, but that's not hard). 5 successive same-state reads of the input and it's presumed to be stable; this is the software version of the resistor-capacitor suggested. Having guessed at which frequency to operate the Phase Lock Loop, this is set up as a software counter (a resolution better than 1 ms may be advisable here) and its rollovers divided by 50 or 60 as previously determined to derive the 1 Hz output. Debounced transitions from the mains input are now compared to the loop count at which they occur with five (perhaps) "windows"; "early", "very early", "very late" "late" and "spot on". An error accumulator is incremented or decremented accordingly, by one for a simple error and three for "very". When it reaches a certain threshold (e.g. 10) in either direction, the loop count is "bumped" in the appropriate direction and the error count cleared. This much implements a *phase*-locked loop and would suit nicely for an already accurate crystal oscillator-locked loop, but where the oscillator is inaccurate to start, a second-order *frequency* lock can be implemented by accumulating the phase corrections in a FIR algorithm by which exceeding the dilution factor results in a correction of the loop period (rather than the count). I venture to say this all codes cleaner than it sounds, and I haven't tried it. Mind you, if I had, I'd probably be *selling* it like ELM! Harrison continued: > Now, from my calculations, if I use a 32.768KHz source, set the > prescaler to 128, the TMR0 will roll over every second. So my delay > loop, which counts seconds, simply polls for TMR0 to overflow, then I > reset it, and go one.. > Do I have this right? Sounds correct to me. -- Cheers, Paul B.