alexstocker / sensordata

Simple python scripts to read sensor data using adafruit and publish to SensorLogger for owncloud or nextcloud
15 stars 10 forks source link

Arduino (NodeMCU) Get Date from NTP #6

Open christoschronopoulos opened 5 years ago

christoschronopoulos commented 5 years ago

Platform you are using

owncloud

Sensors/Hardware

DHT22, NodeMCU

Your Goals

Simple temperature/humidity logger to my owncloud.

Your Question

I used the provided sample code for the Arduino IDE. It works well, but I cannot make it to get the date from NTP server. I also used the "0.europe.pool.ntp.org" and "time.google.com" but without any luck. What do I miss?

christoschronopoulos commented 5 years ago

Ok, I managed to make it work by implementing the NTPClient.h and the WiFiUdp.h libraries in the Arduino IDE as follows:

Credits to the author of Random Nerd Tutorials for the excellent guide! You can find it here. I adjusted it to the provided sample code and made some alterations to make it work for the sensorlogger!

We include the libraries and define the NTP Client `#include

include `

I decided to use the string dateTime of the original code, so we need to keep it String dateTime = "";

Additionally, we add the following strings String formattedDate; String dayStamp; String timeStamp;

I altered the getDateFromNtp() function to the following void getDateFromNtp() { while (!timeClient.update()) { timeClient.forceUpdate(); } // The formattedDate comes with the following format: // 2018-05-28T16:00:13Z // We need to extract date and time formattedDate = timeClient.getFormattedDate(); Serial.println(formattedDate); // Extract date int splitT = formattedDate.indexOf("T"); dayStamp = formattedDate.substring(0, splitT); Serial.print("DATE: "); Serial.println(dayStamp); // Extract time timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() - 1); Serial.print("HOUR: "); Serial.println(timeStamp); delay(1000); // Combine strings dateTime = dayStamp + " " + timeStamp; Serial.println(dateTime); }

You can delete some of the time and date string serial prints. I added them mainly for testing purposes.

In the setup section of the original code I added // Initialize a NTPClient to get time timeClient.begin(); // Set offset time in seconds to adjust for your timezone, for example: // GMT +1 = 3600 Copenhagen timeClient.setTimeOffset(3600);

In the loop, we only need to change the root["date"] root["date"] = dateTime; instead of the root["date"] = "20" + dateTime;

Finally, I added a 48000 ms delay to get the values every 1 minute. This is it!

Screenshot [1], [2]