11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ESP32 NTPを使って時刻をGET

Posted at

ESP32のWifiを使ってネットワークから時刻を取得します。

Qiita初投稿です。 どんな感じに掲示されるのか確認。 
Aruduino SAMPLEにあるSimpleTimeをちょこっと手直しして日本時間対応にしただけのもの。 WifiのIDとパスワードを入れてコンパイル、ESP32へ転送して実行。
DHCPからIPアドレスが払い出されたら、時刻表示します。

SimpleTime.ino
#include <WiFi.h>
#include "time.h"

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

const char* ntpServer =  "ntp.jst.mfeed.ad.jp";  //日本のNTPサーバー選択
const long  gmtOffset_sec = 9 * 3600;  //9時間の時差を入れる
const int   daylightOffset_sec = 0;  //夏時間はないのでゼロ

void printLocalTime()
{
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%Y %m %d %a %H:%M:%S");  //日本人にわかりやすい表記へ変更
}

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();
}

これで、シリアルのターミナル画面に1秒おきに時刻が表示されます。

ふむふむ、なんとなくQittaへの寄稿方法がわかってきた。

11
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?