|
| WiFiを使って日付と時刻の取得 |
|
M5StackはWiFi機能が実装されています。 とりあえず簡単なサンプルとしてNTP (Network Time Protocol)から時刻を取得してLCDに表示します。
/*
*******************************************************************************
* M5Stack prototype
* date:2022/7/25
* Author Sadajejeje
*******************************************************************************
*/
#include <M5Core2.h>
#include <WiFi.h>
#define JST (3600L * 9)
const char* ssid = "my_ssid";
const char* password = "my_password";
void setup(){
M5.begin(); //Init M5Core2
M5.Lcd.setTextSize(2);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
delay(500);
M5.Lcd.print('*');
}
M5.Lcd.print("\n\nIP Address ");
M5.Lcd.println(WiFi.localIP());
delay(1000);
M5.Lcd.setTextSize(3);
configTime(JST,0,"ntp.nict.jp", "time.google.com", "ntp.jst.mfeed.ad.jp");
}
void loop(){
struct tm tm;
char buf[32];
if(getLocalTime(&tm)){
M5.Lcd.setTextDatum(TC_DATUM);
sprintf(buf, "%d/%d/%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
M5.Lcd.drawString(buf, 160, 80, 2);
sprintf(buf, "%02d:%02d:%02d\n", tm.tm_hour, tm.tm_min, tm.tm_sec);
M5.Lcd.drawString(buf, 160, 140, 2);
}
delay(1000);
}
ssidとpasswordはご自分の機器に合わせてください。 M5.Lcd.setTextDatum(TC_DATUM); でセンタリングが楽にできます。 画面の中央に表示するには、xを320/2の160にします。 M5.Lcd.drawString(buf, 160, 80, 2); ![]() |