Software Clock


This code is from a program I used in testing the 9600 baud LCD interface. The surest way of knowing that a design works correctly is to let real-world users have access to it. In lieu of that, I let things run for several days to check for overflows, proper handling of inputs (switches in this application), and output indicators (LED's instead of piezo beepers and pumps).
After some minimal trimming of the OneSecondCount variable, the PICAXE 18A version was off about 4 minutes per day (~10 seconds per hour). This level of accuracy is adequate for a "snooze alarm" type function (turn on a light or display a message for a short period, or turn off an alert for a couple of minutes) but it's not good enough for timekeeping. My use would be to provide a time-limited audible alarm inhibit for an application such as the water level alarm / sump pump controller. For the short duration timers (less than 1 hour) I would be using, there's little value in trying to increase the accuracy - whether a 30 minute alarm inihibit lasts 29 minutes and 55 seconds or 30 minutes or 30 minutes and 5 seconds really doesn't matter.
symbol MyTimer = w4	'storage for approximate time count * 

' *16 bit storage because the speed of your chip and other code are unknown
'  likely to be an 8 bit value at 4MHz but larger at higher clock frequencies

symbol SecCount = w5	'storage for approximate second count
symbol OneSecondCount = 214		'adjust when changing chips or modifying code

'The value of OneSecondCount depends on the chip's clock speed, temperature, and the
' instruction mix.  I added the count and display code to an existing program and let
' it run a couple of minutes for the rough trimming, then 30 minutes for the medium
' trimming, then overnight for the fine trimming. Any program activity that's not in
' the main loop will slow the timer (gosub, interrupt).  Any "pause" or similar statements will slow
' the timer by their duration (100ms, 5 sec, etc).  Commands that wait for input 
' (serin, infrain, etc) may also affect the timer.
'Note that SecCount is 16 bits, so it overflows at 65536 counts.  This is a little over 18 hours.
'For longer periods, increment a minute timer every 60 seconds and reset the seconds counter.
' 65536 minutes is 1092 hours or a little over 45 days.  Based on my limited testing, the time
' would be off by 0.003 or 0.3% - that's a little over 3 hours in 45 days.

MyTimer = 0	'initialize time counter

MainLoop:
	MyTimer = MyTimer + 1
	if MyTimer < OneSecondCount then KeepCounting
	SecCount = SecCount + 1
	MyTimer = 0
	'send seconds count to LCD display
	setfreq m8
	sertxd("?y0?x10 ?l?y0?x10",#SecCount)
	setfreq m4
KeepCounting:
	'rest of main loop code here
  goto MainLoop




Home Page | Projects Page

Copyright © 2006 John E. Carter
Last update .