SimpleTime

はじめに

NTPサーバから時刻を取得し、ESP32の時刻を合わせ、表示します。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <WiFi.h>
#include "time.h"
#include "sntp.h"

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer1 = "pool.ntp.org";
const char* ntpServer2 = "time.nist.gov";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

const char* time_zone = "CET-1CEST,M3.5.0,M10.5.0/3";  // TimeZone rule for Europe/Rome including daylight adjustment rules (optional)
 

ssidとpasswordは、WiFiアクセス用のSSID/パスフレーズです。

ntpServer1とntpServer2には、NTPサーバを設定します。

gmtOffset_secは、ローカル時刻とGMTとの差分を秒で設定します。日本の場合は、GMTより9時間早いので、9*3600 = 32400 を設定します。

daylightOffset_secは、夏時間の差分を秒で設定します。日本の場合は、夏時間はないので、0を設定します。

printLocalTime()

15
16
17
18
19
20
21
22
23
24
void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("No time available (yet)");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}
 

この関数は、シリアルコンソールに、現在時刻を表示します。

getLocalTime()は、現在の日付と時刻を取得する関数です。取得した日付・時刻情報は、struct tm型であらわされます。

最後に、Serial.println()で、時刻をシリアルコンソールに表示します。

このフォーマットは、ESP32での拡張で、以下に示すように、内部では、64バイトの領域を用意し、strftime()を呼び出しています。fはフォーマットで、NULLポインタを渡したときは、"%c"が設定されます。

    char buf[64];
    size_t written = strftime(buf, 64, f, timeinfo);

timeavailable()

25
26
27
28
29
30
// Callback function (get's called when time adjusts via NTP)
void timeavailable(struct timeval *t)
{
  Serial.println("Got time adjustment from NTP!");
  printLocalTime();
}

sntp_set_time_sync_notification_cb()で、SNTPサーバと同期したときに呼び出す関数です。

setup()

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
void setup()
{
  Serial.begin(115200);

  // set notification call-back function
  sntp_set_time_sync_notification_cb( timeavailable );

  /**
   * NTP server address could be aquired via DHCP,
   *
   * NOTE: This call should be made BEFORE esp32 aquires IP address via DHCP,
   * otherwise SNTP option 42 would be rejected by default.
   * NOTE: configTime() function call if made AFTER DHCP-client run
   * will OVERRIDE aquired NTP server address
   */
  sntp_servermode_dhcp(1);    // (optional)

  /**
   * This will set configured ntp servers and constant TimeZone/daylightOffset
   * should be OK if your time zone does not need to adjust daylightOffset twice a year,
   * in such a case time adjustment won't be handled automagicaly.
   */
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2);

  /**
   * A more convenient approach to handle TimeZones with daylightOffset 
   * would be to specify a environmnet variable with TimeZone definition including daylight adjustmnet rules.
   * A list of rules for your zone could be obtained from https://github.com/esp8266/Arduino/blob/master/cores/esp8266/TZ.h
   */
  //configTzTime(time_zone, ntpServer1, ntpServer2);

  //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");

}
 

sntp_set_time_sync_notification_cb()で、SNTPサーバと同期したときに呼び出すコールバック関数(今回は、timeavailable())を登録します。

configTime()は、NTPサーバと時刻を同期させるとともに、ローカルのタイムゾーンの設定を行います。

WiFi.begin()により、ssidで指定したアクセスポイントに接続します。この際のパスフレーズは、passwordです。WiFiは、WiFi.cppで定義されている変数です。

WiFi.status()は、現在の接続状態を返却します。アクセスポイントに接続しているときは、WL_CONNECTEDが返ってきます。

WiFi.disconnect()は、ESP32をWiFiネットワークから切断します。WiFI.mode()により、null modeに設定します。

loop()

74
75
76
77
78
void loop()
{
  delay(5000);
  printLocalTime();
}

5秒ごとにprintLocalTime()を呼び出して、時刻をシリアルコンソールに表示します。

バージョン

Hardware:ESP-WROOM-32
Software:Arduino core for the ESP32 2.0.4

最終更新日

September 4, 2022

inserted by FC2 system