Skip to content

Commit

Permalink
Merge pull request #112 from edgar-bonet/rtc-micros
Browse files Browse the repository at this point in the history
Implement RTC_Micros with tunable drift
  • Loading branch information
drak7 authored Jul 1, 2019
2 parents 75607ab + d8cf253 commit 3f7d2e2
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
26 changes: 26 additions & 0 deletions RTClib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,32 @@ DateTime RTC_Millis::now() {
}

////////////////////////////////////////////////////////////////////////////////
// RTC_Micros implementation

// Number of microseconds reported by micros() per "true" (calibrated)
// second.
uint32_t RTC_Micros::microsPerSecond = 1000000;

// The timing logic is identical to RTC_Millis.
uint32_t RTC_Micros::lastMicros;
uint32_t RTC_Micros::lastUnix;

void RTC_Micros::adjust(const DateTime& dt) {
lastMicros = micros();
lastUnix = dt.unixtime();
}

// A positive adjustment makes the clock faster.
void RTC_Micros::adjustDrift(int ppm) {
microsPerSecond = 1000000 - ppm;
}

DateTime RTC_Micros::now() {
uint32_t elapsedSeconds = (micros() - lastMicros) / microsPerSecond;
lastMicros += elapsedSeconds * microsPerSecond;
lastUnix += elapsedSeconds;
return lastUnix;
}

////////////////////////////////////////////////////////////////////////////////
// RTC_PCF8563 implementation
Expand Down
18 changes: 18 additions & 0 deletions RTClib.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,22 @@ class RTC_Millis {
static uint32_t lastMillis;
};

// RTC using the internal micros() clock, has to be initialized before
// use. Unlike RTC_Millis, this can be tuned in order to compensate for
// the natural drift of the system clock. Note that now() has to be
// called more frequently than the micros() rollover period, which is
// approximately 71.6 minutes.
class RTC_Micros {
public:
static void begin(const DateTime& dt) { adjust(dt); }
static void adjust(const DateTime& dt);
static void adjustDrift(int ppm);
static DateTime now();

protected:
static uint32_t microsPerSecond;
static uint32_t lastUnix;
static uint32_t lastMicros;
};

#endif // _RTCLIB_H_
2 changes: 2 additions & 0 deletions keywords.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ DateTime KEYWORD1
TimeSpan KEYWORD1
RTC_DS1307 KEYWORD1
RTC_Millis KEYWORD1
RTC_Micros KEYWORD1
Ds1307SqwPinMode KEYWORD1

#######################################
Expand All @@ -27,6 +28,7 @@ secondstime KEYWORD2
unixtime KEYWORD2
begin KEYWORD2
adjust KEYWORD2
adjustDrift KEYWORD2
isrunning KEYWORD2
now KEYWORD2
readSqwPinMode KEYWORD2
Expand Down

0 comments on commit 3f7d2e2

Please sign in to comment.