Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //NTP Serial monitor time stamp print by making a String to the format desired
- #include <WiFi.h>
- #include <WiFiUdp.h>
- #include "time.h"
- String time_str;
- uint32_t previousTime = 0;
- const char* ssid = "YOUR SSID HERE";
- const char* password = "YOUR WIFI PASSWORD";
- //NTP TZ_INFO for Auto Zone and Daylight savings Offsets
- // This from Github NZST-12NZDT,M9.5.0,M4.1.0/3
- // https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
- const char* NTP_SERVER = "pool.ntp.org";
- const char* TZ_INFO = "NZST-12NZDT,M9.5.0,M4.1.0/3";
- WiFiClient client; // wifi client object
- void setup() {
- Serial.begin(115200);
- if (!StartWiFi(ssid,password))
- Serial.println("Failed to start WiFi Service after 20 attempts");;
- /* configTime(12*3600, 0, "pool.ntp.org"); // +1hour (1*60*60=3600=+1hour) ahead for DST in the UK */
- configTime(0, 0, NTP_SERVER); // if TZ configured
- setenv("TZ", TZ_INFO, 1); // for TZ and Daylight Auto change
- time_t now = time(nullptr);
- delay(2000); // Wait for time to start
- while (!update_time()); //Get the latest time
- previousTime = millis();
- }
- void loop() {
- if(millis() - previousTime >= 1000){
- while (!update_time());
- previousTime = millis();
- }
- }
- bool update_time(){
- time_t now = time(nullptr);
- struct tm *now_tm;
- int hour,min,second,day,month,year;
- now = time(NULL);
- now_tm = localtime(&now);
- hour = now_tm->tm_hour;
- min = now_tm->tm_min;
- int weekday = now_tm->tm_wday;
- String week_days[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
- String wday = week_days[weekday];
- second = now_tm->tm_sec;
- day = now_tm->tm_mday;
- month = now_tm->tm_mon + 1;
- year = now_tm->tm_year - 100;// YY only no CC element add 1900 for CC element too
- // Needs to be in the format HH:MM:SS Sat 05-07-17
- time_str = (hour<10?"0":"")+String(hour)+":"+(min<10?"0":"")+String(min)+":"+(second<10?"0":"")+String(second)+" "+wday+(day<10?" 0":" ")+String(day)+"-"+(month<10?"0":"")+String(month)+"-"+String(year);
- Serial.println(time_str);
- return true;
- }
- int StartWiFi(const char* ssid, const char* password){
- int connAttempts = 0;
- Serial.println("\r\nConnecting to: "+String(ssid));
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED ) {
- delay(500);
- Serial.print(".");
- if(connAttempts > 20) return false;
- connAttempts++;
- }
- Serial.print("WiFi connected\r\nIP address: ");
- Serial.println(WiFi.localIP());
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement