Uses Timer 0 and the RTC to keep accurate time. It can accept a PPS from an external source like a GPS or a regular time stamp from an external source like an NTP server. It also provides timer functions to 96MHz up to 44 seconds using the CPU clock.

Dependents:   oldheating gps motorhome heating

Description

The clock library provides a number of separate functions:

  • hrtimer An unsigned 32bit high resolution timer which wraps around every 44 seconds from which all the time is derived.
  • mstimer An unsigned 32bit low resolution timer which wraps around every 49 days
  • clktimer A signed 64bit timer (TAI) which doesn't wrap (or not until 2242 when clock time breaks)
  • scan Calculates the max, min and average scan times.
  • rtc A real time clock to provide backup
  • tm Routines to manipulate struct tm local and utc times
  • clk A clock which is synchronised to an external source

High resolution timer

hrtimer uses TIM0 as a 32bit timer which counts at the cpu frequency 96MHz and rolls over after about 44s.
It has an init routine called from ClkInit to start it, thereafter it free runs.
No dependencies.

Millisecond timer

mstimer uses the high resolution timer to count the number of ms since power up. Its unsigned 32bit count rolls over after about 49 days.
It has a main routine called from ClkMain.
Depends on timer.

Clock timer

clktimer uses the signed 64 bit clock time.
Depends on clock and hence hrtimer.

Scan times

scan uses the high resolution timer to calculate the max, min and average scan times.
It has a main routine called from ClkMain.
Depends on hrtimer.

Real time clock

rtc contains routines to save and restore the time in the battery backed real time clock.
Parameters are struct tm.
No dependencies.

Local and UTC manipulation

tm contains

  • the typedef time64 which contains the count of seconds since 1970; just like time_t but based on int64_t to avoid the 2038 problem
  • a number of functions for manipulating time64 and struct tm times

No dependencies.

Clk

clk contains

  • settings
  • functions to save and restore the time to the RTC. Depends on timer, rtc and tm.

clktime increments the time by 1 each second via clk.c from timer.c.
It increments the signed 64 bit time count using the ppb and slew (governed by clkgov.c).
When the time is requested it uses its count and a proportion of the elapsed second from the high resolution timer to calculate the exact time.
See time-formats.text for the clock time format.

clkgov governs the ppb and slew to synchronise the clock time with an external source.
PPB is stored in GPREG0 whenever it is set and retrieved during initialisation.
It takes external time from either:

  • a long term source such as NTP
  • a pulse per second (PPS) such as GPS

clkntp converts clock time to NTP time and vice versa.

clktm converts clock time to struct tm and vice versa

clkutc maintains the era offset (leap seconds count).
The era offset and other information is stored in GPREG1 whenever it is set and retrieved during initialisation.
It contains:

  • the current era offset
  • for the next epoch:
    • its start month (as year and month since 1970)
    • its state: normal; waiting to leap forward; waiting to leap back; leaping forward (second 60)
  • conversion routines between tai and utc (clk time is tai)

Clock time formats

Criteria

Resolution

PPS
We get an interrupt each second which we can resolve to a microsecond. The divisor is 1000. To carry this resolution into the governor we need 1 ppb.
NTP
Suppose we are adding compensation every second, sampling every 4 hours and want to represent 3ms of error with a divisor of 10: that would need a resolution of 23 ppb.
The best temperature compensated crystal oscillators can manage about 1ppm (see Wikipedia) long term or 10 ppb short term.

Lifetime

Needs to keep going during the lifetime of this, or other related, projects. At least a century (so 2100) but more than a few centuries is likely to be pointless

Ease of transforming to NTP, time_t

A count of decimal times - ms, us, ns or ps - can only be transformed using multiplication or division by 1000s. NTP and time_t use binary fractions about a fixed decimal point.

Ease of representing ppm or ppb

A count of decimal times is best but a count of fractions is near enough as 10 bits (1024) is very close to being 1000. As long as it is only needed for a correction such as ppb the approximation would only manifest itself as a 7% error.

The version chosen

1 bit sign, 33 bits for seconds, 30 bits for fraction

+/- 272 years at 1ns or 1 ppb per second
Clock era is 1970

Advantages:

  • adequately representing the freq adjustments for pps
  • simple transformation to NTP and time_t
  • approximates to ns or, with a bit shift, to us or ms
  • adequately covers the next two centuries
  • one unit represents 1 ppb for display

Disadvantage:

  • none

Alternatives considered

1 bit sign, 43 bits for seconds, 20 bits for fraction

+/- 278,731 years at 1us or 1 ppm per second

Advantages:

  • a wide coverage
  • simple transformation to NTP and time_t
  • approximates to us or, with a bitwise shift, to ms
  • one unit represents 1 ppm for display

Disadvantage:

  • not able to reflect the freq adjustments for pps.

1 bit sign, 35bits for seconds, 28bits for fraction

+/- 1089 years at 3ns or 3ppb per second
looks like SSSS SSSS S.FFF FFFF in hex

Advantages:

  • easily represented in hex
  • a wide coverage
  • simple transformation to NTP and time_t

Disadvantage:

  • one unit doesn't approximate to anything simple

32 bits for seconds, 32 bits for fraction

Ntp time with an era of 1900
1900 to 2036 with a resolution of 250ps or 0.25 ppb

Advantages:

  • Already NTP and easily converted to time_t

Disadvantage:

  • Will rollover in 2036

Use 96MHz int64 count

+/- 3044 years with a resolution of 10ns or 10ppb per second

Advantages:

  • a wide coverage

Disadvantage:

  • cannot use simple bit shifts to transform to NTP and time_t
  • not transferable to a system with a different clock rate

Use a count of ns

+/- 292 years at 1ns or 1ppb per second

Advantages:

  • adequately representing the freq adjustments for pps
  • easily usable with ppb and ns
  • a wide coverage

Disadvantage:

  • cannot use simple bit shifts to transform to NTP and time_t
Revision:
57:4daf2e423b27
Parent:
54:a3c018ceca77
Child:
69:4e48d3859b87
--- a/clk/clkgov.c	Thu Feb 21 15:45:43 2019 +0000
+++ b/clk/clkgov.c	Thu Feb 21 21:08:03 2019 +0000
@@ -5,6 +5,7 @@
 #include "clktime.h"
 #include "clk.h"
 #include "clkutc.h"
+#include "time64.h"
 
 #define GPREG0 (*((volatile unsigned *) 0x40024044))
 
@@ -39,11 +40,11 @@
 bool ClkGovRateIsSynced = false;
 bool ClkGovIsSynced() { return ClkGovRateIsSynced && ClkGovTimeIsSynced; }
 
-static void setSyncedTime(int64_t diff)
+static void setSyncedTime(clktime diff)
 {
-    int64_t absDiff = llabs(diff);
-    int64_t limit      = ClkGovSlewSyncedLimNs;
-    int64_t hysterisis = ClkGovSlewSyncedHysNs;
+    clktime absDiff = llabs(diff);
+    clktime limit      = ClkGovSlewSyncedLimNs;
+    clktime hysterisis = ClkGovSlewSyncedHysNs;
 
     if (absDiff < limit - hysterisis)
     {
@@ -56,12 +57,12 @@
         ClkGovTimeIsSynced = false;
     }
 }
-static void setSyncedRate(int64_t diff)
+static void setSyncedRate(clktime diff)
 {
 
-    int64_t absDiff = llabs(diff);
-    int64_t limit      = ClkGovFreqSyncedLimPpb;
-    int64_t hysteresis = ClkGovFreqSyncedHysPpb;
+    clktime absDiff = llabs(diff);
+    clktime limit      = ClkGovFreqSyncedLimPpb;
+    clktime hysteresis = ClkGovFreqSyncedHysPpb;
 
     if (absDiff < limit - hysteresis)
     {
@@ -75,9 +76,9 @@
     }
 }
 
-static void setSlew(int64_t diff)
+static void setSlew(clktime diff)
 {
-    int64_t toAdd = -diff / ClkGovSlewDivisor;
+    clktime toAdd = -diff / ClkGovSlewDivisor;
     int32_t slewMaxTicks = ClkGovSlewChangeMaxMs << CLK_TIME_ONE_MS_ISH_SHIFT;
 
     if (toAdd >  slewMaxTicks) toAdd =  slewMaxTicks;
@@ -87,9 +88,9 @@
 
     if (ClkGovTrace) LogTimeF("Sync setSlew diff %lld gives slew %lld gives TickSlew %ld\r\n", diff, toAdd, slew);
 }
-static void adjustPpb(int64_t diff)
+static void adjustPpb(clktime diff)
 {
-    int64_t toAdd = diff / ClkGovFreqDivisor;
+    clktime toAdd = diff / ClkGovFreqDivisor;
     int32_t maxAdd = ClkGovFreqChangeMaxPpb;
 
     if (toAdd >  maxAdd) toAdd =  maxAdd;
@@ -100,9 +101,9 @@
     if (ClkGovTrace) LogTimeF("Sync setPpb diff %lld gives toAdd %lld gives TickPpb %ld\r\n", diff, toAdd, ppb);
 }
 
-static int64_t lastIntClock = -1; //-1 indicates invalid value. 0 is a valid value.
-static int64_t lastExtClock = -1;
-static void reset(int64_t thisExtClock)
+static clktime lastIntClock = -1; //-1 indicates invalid value. 0 is a valid value.
+static clktime lastExtClock = -1;
+static void reset(clktime thisExtClock)
 {
     ClkTimeSet(thisExtClock);
     ClkGovSetPpb(0);
@@ -110,7 +111,7 @@
     lastExtClock = 0;
 }
 
-static void sync(int64_t thisExtClock)
+static void sync(clktime thisExtClock)
 {
 
     if (!ClkTimeIsSet()) //Cold start - only ever true if the RTC was not set.
@@ -121,13 +122,13 @@
     }
 
     //Get the time at the time of the interrupt
-    int64_t thisIntClock;
-    int64_t thisAbsClock;
+    clktime thisIntClock;
+    clktime thisAbsClock;
     ClkTimesGetFromSnapshot(&thisIntClock, &thisAbsClock);
 
     //Calulate the time error
-    int64_t absDiff = thisAbsClock - thisExtClock;
-    if (llabs(absDiff) > ((int64_t)ClkGovSlewOffsetMaxSecs << CLK_TIME_ONE_SECOND_SHIFT))
+    clktime absDiff = thisAbsClock - thisExtClock;
+    if (llabs(absDiff) > ((clktime)ClkGovSlewOffsetMaxSecs << CLK_TIME_ONE_SECOND_SHIFT))
     {
         LogTimeF("Sync - offset is greater than %d seconds so resetting\r\n", ClkGovSlewOffsetMaxSecs);
         reset(thisExtClock);
@@ -139,12 +140,12 @@
     //Calculate the rate error
     if (lastExtClock > -1)
     {
-        int64_t extPeriod = thisExtClock - lastExtClock;
+        clktime extPeriod = thisExtClock - lastExtClock;
 
-        int64_t intPeriod = thisIntClock - lastIntClock;
-        int64_t periodDiff =   intPeriod -    extPeriod;
+        clktime intPeriod = thisIntClock - lastIntClock;
+        clktime periodDiff =   intPeriod -    extPeriod;
 
-        int64_t ppbDiff;
+        clktime ppbDiff;
         if (extPeriod == CLK_TIME_ONE_SECOND) ppbDiff =  periodDiff; //This saves a 64bit shift and division for PPS
         else                                  ppbDiff = (periodDiff << CLK_TIME_ONE_SECOND_SHIFT) / extPeriod;
 
@@ -156,17 +157,20 @@
     lastIntClock = thisIntClock;
     lastExtClock = thisExtClock;
 }
-void ClkGovSyncPpsI(             ) { ClkTimeSaveSnapshot(); }
-void ClkGovSyncPpsN(time_t  t    )
+void ClkGovSyncPpsI()
 {
-    int64_t time;
-    time = (int64_t)t << CLK_TIME_ONE_SECOND_SHIFT;
+    ClkTimeSaveSnapshot();
+}
+void ClkGovSyncPpsN(time64 t)
+{
+    clktime time;
+    time = (clktime)t << CLK_TIME_ONE_SECOND_SHIFT;
     time = ClkUtcToTai(time);
     sync(time);
 }
-void ClkGovSyncPpsZ(             )
+void ClkGovSyncPpsZ()
 {            
-    int64_t time;
+    clktime time;
     time   = ClkNowTai();
     time  += 1UL << (CLK_TIME_ONE_SECOND_SHIFT - 1); //Add half a second so as to round to nearest rather than round down
     time >>= CLK_TIME_ONE_SECOND_SHIFT;
@@ -174,4 +178,8 @@
     sync(time);
 }
 
-void ClkGovSyncTime(int64_t time ) { ClkTimeSaveSnapshot();                                  sync(time); }
\ No newline at end of file
+void ClkGovSyncTime(clktime time)
+{
+    ClkTimeSaveSnapshot();
+    sync(time);
+}
\ No newline at end of file