Hi,
using the code of the „3.4 WebServer Display Sensors Readings from File“ example sometimes (especially at the begin) the NTP server called from code returns a value of 0 (January 1st 1970) instead of the right time.
A consequence is that the charts begin with a value far in the past and then only the following are actual values. This is also stored in the JSON data.txt file.
How can I get from the begin right NTP values? Can I discard the first one?
Many thanks!
Best regards,
Enrico
Hi.
That happens when the board is not able to connect to the NTP server, so it returns the start of the epoch time.
You can add an if statement that either discards that time or add a while loop that continuously tries until it gets the right time.
For example:
unsigned long getTime() {
time_t now;
struct tm timeinfo;
while (!getLocalTime(&timeinfo)) {
// Wait for a short duration before retrying
sleep(1); // Adjust the duration as needed
}
time(&now);
return now;
}
I hope this helps.
Regards,
Sara
Hi Sara,
thanks for your answer.
Unfortunately your suggestion seems not really to solve the problem. The program get stick inside the loop.
Inside setup(), the first time that getTime() is called (and returns 0) is inside getSensorReadings in the case that the data.txt file doesn‘t exist and has to be created.
This happens before configTime(0, 0, ntpServer) get called.
Calling configTime quite at the beginning, before to check if data.txt exists, seems to solve the problem.
I think that getTime() get a valid result, only after having executed configTime. In the example instead configTime is called towards the end of setup().
Can you please check if this could be a solution for the problem?
Best regards,
Enrico
Hi.
After taking a look at the code, yes, that seems to probably be causing the issue and your suggestion should solve the problem.
Have you tried that solution? Let me know if that fixes the problem.
If yes, I’ll update the code with those modifications.
Regards,
Sara
Hi Sara,
yes I have implemented my solution and since then, after a few days, I haven’t got no more time values equal 0. Probably the problem has been fixed.
Many thanks!
Best regards;
Enrico