From a225c1cc83fa08a1d7a555ec02c66685637e1195 Mon Sep 17 00:00:00 2001 From: zeflo Date: Thu, 4 Mar 2021 17:35:14 +0100 Subject: [PATCH] Update NTPClient.cpp Until now the fraction of the second was not taken into account. Therefore the resulting time offset is up to 1000 ms. Using the provided Information increases the accuracy of the synchronization to 20-30 milliseconds. And it requires just two lines of code. https://imgur.com/a/aVjvHON In this plot both methods are compared. Plotted is the time difference in respect to a PPS signal provided by a GPS receiver. For comparison the time was synchronized over 1000 times and the resulting time difference filled into the respective histogram. --- NTPClient.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/NTPClient.cpp b/NTPClient.cpp index 760e142..49ff534 100755 --- a/NTPClient.cpp +++ b/NTPClient.cpp @@ -114,6 +114,12 @@ bool NTPClient::forceUpdate() { this->_currentEpoc = secsSince1900 - SEVENZYYEARS; + // get also the most significant 16 bits of the fraction of the second + unsigned long fracWord = word(this->_packetBuffer[44], this->_packetBuffer[45]); + + // Account for fraction of the second. + this->_lastUpdate -= (fracWord/66); // should be devided by 2^16/1000 = 65.536 but 66 is close enough + return true; // return true after successful update } @@ -207,4 +213,4 @@ void NTPClient::sendNTPPacket() { void NTPClient::setRandomPort(unsigned int minValue, unsigned int maxValue) { randomSeed(analogRead(0)); this->_port = random(minValue, maxValue); -} \ No newline at end of file +}