Seen some projects lately that needed a 1Hz clock signal for a mechanical clock. The go-to device for that is of course a RTC. I was curious if it could be done with an ESP8266 board and NTP, which should be more accurate over time than a RTC.
A NTP clock works with a free-running timer, close enough to what you want, which is frequently corrected with a timeserver on the internet. Which then jumps to the correct time a second or more when needed.
Works fine for digital clocks that can just jump forwards or backwards a second or more , but mechanical clocks could have problems doing so.
I tried to solve that with a second free running timer, that is only adjusted a fraction of a Hz when needed. The mechanical clock keeps ticking the same, but a second fast or slow is corrected over a time of 500 seconds, making it virtually unnoticeable.
Test code attached, It displays epoch, the corrected timer, and half a period of the 1Hz signal.
When corection is needed, that 500ms will vary one or more ms.
The ESP8266 is supprisingly stable on it's own. Corrections are very rare.
Every hour you see the NTP update printed, which could include a correction.
The sketch only needs YOUR WiFi credentials.
IDEv2 users might have to change baud rate to 115200.
Let me know what you think.
Leo..
#include <ESP8266WiFi.h>
#include <coredecls.h>
time_t now;
unsigned long tick, prevMillis;
int interval = 500;
bool ntp, toggle;
void time_is_set() {
Serial.println(F("time was updated"));
ntp = true;
}
void setup() {
Serial.begin(74880);
Serial.println(F("\nESP8266 NTP clock"));
configTime("GMT0", "pool.ntp.org");
settimeofday_cb(time_is_set);
WiFi.mode(WIFI_STA);
WiFi.begin("YOUR_SSID", "YOUR_PASSWORD");
while (WiFi.status() != WL_CONNECTED) delay(200);
Serial.println(F("\nConnected\nEpoch"));
while (!ntp);
time(&now);
tick = now;
}
void loop() {
if (millis() - prevMillis >= interval) {
prevMillis = millis(); // reset
time(&now); // read the current time
interval = 500 + (tick - now); // correction
toggle = !toggle; // 1Hz
//digitalWrite(pin, toggle);
if (toggle) { // when HIGH
Serial.print(now);
Serial.print("\t");
Serial.print(tick);
Serial.print("\t");
Serial.println(interval);
tick ++; // update
}
}
}