時刻の表示
今回はWifiに接続して時刻を取ってきて表示するプログラミングを作成しました。
色々と詰め込んでしまいました。。。
wifiへの接続
まずは初期化して引数にSSIDとパスワードを設定します。
WiFi.begin(ssid, password);
戻り値に WL_CONNECTED が返ってきたら成功です。
while (WiFi.status() != WL_CONNECTED) { delay(500); M5.Lcd.print("."); }
時刻の取得
NTPサーバに接続して時刻を取得します。
日本時刻を取得するには以下の設定で取得できます。
const char* ntpServer = "ntp.nict.jp"; const long gmtOffset_sec = 3600 * 9; const int daylightOffset_sec = 0; //init and get the time configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
時刻を表示するコード
こちらがコードです。
#include <M5Stack.h> #include <WiFi.h> #include "time.h" const char* ssid = "YOUR_SSID"; ←変更箇所 const char* password = "YOUR_PASS"; ←変更箇所 const char* ntpServer = "ntp.nict.jp"; const long gmtOffset_sec = 3600 * 9; const int daylightOffset_sec = 0; void printLocalTime() { struct tm timeinfo; if(!getLocalTime(&timeinfo)){ M5.Lcd.println("Failed to obtain time"); return; } // テキストサイズ指定 M5.Lcd.setTextSize(2); // カーソル位置を設定 M5.Lcd.setCursor(40,100); M5.Lcd.printf("%04d-%02d-%02d %02d:%02d:%02d" ,timeinfo.tm_year + 1900 ,timeinfo.tm_mon ,timeinfo.tm_mday ,timeinfo.tm_hour ,timeinfo.tm_min ,timeinfo.tm_sec ); } void setup() { M5.begin(); //connect to WiFi M5.Lcd.print("Connecting to YOUR_SSID "); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); M5.Lcd.print("."); } M5.Lcd.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(); }
Twitterの動画では時刻がおかしかったですが、こちらで公開しているソースでは正常に取得して表示できるようになっています。
wifiに接続して、時間を取ってきて表示できた。ただ時間がちょっと変…#m5stack pic.twitter.com/1hYaIw6b8v
— yamanonono (@yamano_no_no) September 17, 2019