いきなり時計プログラム。 サンプルを参考にしています。
#include <WiFi.h>
#include "time.h"
#include "esp_sntp.h"
// WiFi認証情報
const char *ssid = "あなたのWiFI";
const char *password = "あなたのWEP";
// NTPサーバーとタイムゾーン設定(東京用)
const char *ntpServer1 = "ntp.nict.jp";
const char *ntpServer2 = "time.cloudflare.com"; // 信頼性の高いサーバーを追加
const char *time_zone = "JST-9"; // JST-9は日本標準時がGMTより9時間進んでいることを示す
void printLocalTime() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("No time available (yet)");
return;
}
Serial.println(&timeinfo, "%Y/%m/%d %H:%M:%S");
}
void timeSyncCallback(struct timeval *t) {
Serial.println("Got time adjustment from NTP!");
printLocalTime();
}
void setup() {
Serial.begin(115200);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
// NTPサーバーから時刻を取得し、タイムゾーンを設定する
configTzTime(time_zone, ntpServer1, ntpServer2);
// 時刻同期が完了したときに呼ばれるコールバック関数を設定
sntp_set_time_sync_notification_cb(timeSyncCallback);
}
void loop() {
delay(5000);
printLocalTime();
}