code
نسخ
اقتباس
عرض
تنزيل
#include <WiFi.h>
#include "time.h"
const char* ssid = "admin";
const char* password = "12345678";
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 3600;
const int daylightOffset_sec = 3600;
char strftime_buf[64];
void printLocalTime()
{
struct tm timeinfo;
setenv("TZ", "CST-3", 1);//Central Standard Time (CST) is 6 hours behind Coordinated Universal Time (UTC)
//CST-3 === GMT+2
tzset();
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
Serial.println(strftime_buf);
}
void setup()
{
Serial.begin(115200);
//connect to WiFi
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
//init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void loop()
{
delay(1000);
printLocalTime();
}