[time-nuts] Clock Correction Algorithm

Miguel Gonçalves mail at miguelgoncalves.com
Thu Nov 24 05:14:17 EST 2011


I am building a clock that fetches its time from a local NTP server (GPS
synched machine).

I am using a timer based on a 16 bit interrupt on an Arduino (ATmega328
clocked at 16 MHz).

I am implementing an algorithm to steer the this clock (nothing as
complicated as the NTP algorithms) and wanted your opinion regarding this.

The clock is set by sending an NTP packet and setting the clock with the
replied timestamp plus half of the round trip time. In a local LAN this
seems a good solution. I am not after micro-second accuracy as this is a
clock and our eyes don't recognize anything faster than 50 ms. Even then I
am aiming for 1-10 ms maximum offset with the NTP server.

So, I am thinking about this algorithm (1-4 are done once and then it will
jump to a):

1. interval = 64
2. ncorrections = 0
3. lastcorrection = 0
4. lastset = now

a. while (lastset - now) < interval do nothing
b. fetch time from NTP
c. compute offset from local clock
d. compute correction to be added/subtracted to each second for this
interval (offset/interval)
e. reset clock with time fetched from NTP and apply correction to clock
(making the second longer or shorter as appropriate)
f. lastset = now
g. if lastcorrection = 0 then go to i
h. if abs(lastcorrection - correction) > max then go to r
i. lastcorrection = correction
j. ncorrections = ncorrections + 1
k. if ncorrections < 3 go to a
l. if interval = 1024 go to m
l. interval = interval x 2
m. ncorrections = 0
n. lastcorrection = 0

r. interval = 64
s. ncorrections = 0
t. lastcorrection = 0
u. go to a

What's your take regarding this matter?

Any help will be appreciated.


More information about the time-nuts mailing list