; Automatic adjustment of the RealTimeClock. ; This code will automatically adjust the speed of the RTC based on ; the correction applied to set a new time and the elapsed time since ; the clock was last set. ; Apply a correction, in Seconds, to the clock's time. ; Correction is +ve to set the clock forward, and -ve to set it back. ; Also, adjust the clock's speed to take account of the applied correction. To ApplyClockCorrection(correction) Local elapsedTime Local lastSet := clock.GetLast ; Read when the clock was last set. elapsedTime := clock.Time - lastSet clock.Time := clock.Time + correction ; set the clock to the new time. speedUpClockBy(correction/elapsedTime) ; Adjust the clock. Speed it up if we had to set it forward. End ; Adjust the speed of the clock. ; adjustment is a float value. ; +ve values make the clock go faster. To speedUpClockBy(adjustment) Local NewAdjust Local AdjustValue := (adjustment * (2 ^ 20)) As Int ; Convert to units used by the clock hardware. ; Find the new Adjust value. ; [Increasing the Adjust value slows the clock down, ; so we have to subtract from the existing value]. NewAdjust := clock.Adjust - AdjustValue ; Limit the range to valid values: If NewAdjust > 127 NewAdjust := 127 Else If NewAdjust < 0 NewAdjust := 0 ;Set the new adjustment clock.Adjust := NewAdjust End ;**** TEST CODE SECTION **** #Define DaysToSeconds(Days) (60*60*24*Days) #Define MinutesToSeconds(Mins) (60*Mins) To main ; Reset the Adjust value to its default setting: clock.Adjust := 64 Print "Before: ", clock.Adjust,CR ; Set the clock's time, but as if we set it one year ago: setTimeThenElapsed("2014-08-05 09:34:00", DaysToSeconds(365)) ; Now apply a -15 minute correction: ApplyClockCorrection(-MinutesToSeconds(15)) ; See the effect of the correction on the Adjust value: Print "After: ", clock.Adjust,CR End ; Set the clock's time, but then falsify the time since it was last set. ; to the elapsed time given. To setTimeThenElapsed(setting, elapsed) If TypeOf setting = TypeOf String Print To clock, setting Else clock.Time := setting SetClockGetLast(clock.Time - elapsed) End ; Falsify the time the clock was last set. To SetClockGetLast(t) clock.Element(1) := t clock.Element(2) := t >> 16 End