i am using nodemcu to send data to firebase each 2 seconds, among those data is the timestamp when the data is acquired. and i am asking what is the best approach to get the time. for example, i thought abought getting timestamp from ntp server at setup() then increasing that timestamp variable by two each two second at loop(). so my code looks like this
#include <someheaders>
#define someconstant
long lastTick;
long timestamp;
void setup()
{
setting up wifi and firebase etc...
timestamp = getTimeStampFromNTPServer();
lastTick = millis();
}
void loop()
{
if(millis() - lastTick >= 2000)
{
lastTick = millis();
timestamp+=2;
sendToFirebase(timestamp,temperature,humidity...etc)
}
}
i think using if(millis()...) instead of delay(2000) is clear. so what is the better approach? even using an external RTC
thanks you. i know that, but i want the timestamp that the data was captured not inserted to firebase.also i want some control over the timestamp because i will capture only each 2 seconds.
It depends on what level of accuracy you need. Your code as written will drift over time since you are not guaranteed to execute it exactly every 2000 milliseconds.
But even that is at the mercy of the accuracy of the clock on the ESP8266. +/- 10 ppm. If you get an external RTC like the DS3231, it has a drift of about +/- 5ppm