This trivial little code snippet shows how to use a standard 32.768KHz clock crystal wired on to the secondary oscillator of a 28X2 or 40X2 (pins C.0 and C.1) to create an accurate time counter and real time clock without needing a DS1307 and with minimal processor overhead. Obviously after setting up the timer pins c.0 and c.1 must not be impacted by commands such as "dirsc"
Code:
'
' example to show how to get an accurate real time clock unrelated to processor speed on a 28X2 or 40X2
' uses a 32.768khz clock crystal across C.0 and C.1, with the usual 22pf capacitors to ground, driving timer3
' note the timer tick rate is unrelated to the main processor clock allowing perfect timekeeping
' the basic signal 32.768khz input creates a two second update in the picaxe timer3 variable which
' is incremented when the internal TMR3 register rolls over (65536/32768/khz = 2 second)
' reading the internal timer register allows for greater discrimination of time. In this example
' bit 7 of the high byte gives resolution to 1 second
'
' Use of this to create a real time clock
'
#picaxe 28X2
setfreq em64
'
symbol hours = b1
symbol minutes = b2
symbol seconds = b3
'
hours=12
minutes=57
seconds=00
tmr3setup %10001001 ; timer3 on, 1:1 prescalar, enable secondary crystal as timer source
b0=seconds/2
timer3=hours*60+minutes*30+b0 'time since midnight in 2 second increments (0-43199)
do
pause 500
if timer3>43199 then: timer3=timer3-43200 :endif ' must be called within 12 hours of midnight ((65536-43200)/1800=12.4)
hours = timer3/1800
minutes= timer3//1800/30
seconds=timer3//1800//30*2
peeksfr $b3,b0 ' get the high byte of the internal timer 3 register
b0=b0>>7 ' move bit 7 to bit 0 to give 0 or 1 seconds
seconds=seconds|b0 ' OR this in to the seconds to complete the 1 second accuracy
debug ; display time
loop
Last edited: