村上や |
|
ニュース |
2021年10月30日
M5Stackです。
毎日、NTPサーバーに接続して、、時刻合わせをします。
これで時刻がズレることはありません。
日付と曜日も表示させています。
ソースです。
#include
<M5Stack.h> #include <WiFi.h> #define TFT_GREY 0x5AEB const char *ssid = "your ssid"; const char *password = "your password"; int myear; uint8_t mon; uint8_t mday; uint8_t hh; uint8_t mm; uint8_t ss; byte omm = 60; byte oss = 60; byte xcolon; byte xsecs; struct tm timeInfo; uint8_t cday = 0; void setup(void) { M5.begin();
M5.Lcd.fillScreen(TFT_BLACK);
M5.Lcd.setTextSize(1);
M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Lcd.setBrightness(200); } void loop() { //時刻取得 gettime(); //日付が変わった if (cday !=
mday) { //画面初期化
M5.Lcd.fillScreen(TFT_BLACK);
//WiFi接続
connection(); //時刻取得
gettime(); //日付保存
cday = mday; //日付表示
int xpos0 = 0;
int ypos0 = 40; if
(mon < 10) xpos0 += M5.Lcd.drawChar('0', xpos0, ypos0, 7);
xpos0 += M5.Lcd.drawNumber(mon, xpos0, ypos0, 7);
xpos0 += M5.Lcd.drawChar('-', xpos0, ypos0, 7); if
(mday < 10) xpos0 += M5.Lcd.drawChar('0', xpos0, ypos0, 7);
xpos0 += M5.Lcd.drawNumber(mday, xpos0, ypos0, 7);
showWeek(myear, mon, mday, xpos0 + 20, ypos0); } //時刻表示 if (oss != ss)
{
int xpos = 0;
int ypos = 130; int ysecs = ypos + 24; if
(omm != mm) { omm = mm; if (hh <
10) xpos += M5.Lcd.drawChar('0', xpos, ypos, 8); xpos +=
M5.Lcd.drawNumber(hh, xpos, ypos, 8); xcolon = xpos; xpos +=
M5.Lcd.drawChar(':', xpos, ypos - 8, 8); if (mm < 10) xpos +=
M5.Lcd.drawChar('0', xpos, ypos, 8); xpos +=
M5.Lcd.drawNumber(mm, xpos, ypos, 8); xsecs = xpos; } if
(oss != ss) { oss = ss; xpos = xsecs;
M5.Lcd.drawChar(':', xcolon, ypos - 8, 8); xpos +=
M5.Lcd.drawChar(':', xsecs, ysecs, 6); if (ss <
10) xpos += M5.Lcd.drawChar('0', xpos, ysecs, 6);
M5.Lcd.drawNumber(ss, xpos, ysecs, 6); } } delay(100); } void showWeek(int y, int m, int d, int xpos0, int ypos0) { if (m < 3)
{
y--; m
+= 12; } int w = (y + y
/ 4 - y / 100 + y / 400 + (13 * m + 8) / 5 + d) % 7;
M5.Lcd.setTextSize(6); if (w == 0) {
xpos0 += M5.Lcd.drawString("Sun", xpos0 + 10, ypos0); } else if (w
== 1) {
xpos0 += M5.Lcd.drawString("Mon", xpos0 + 10, ypos0); } else if (w
== 2) {
xpos0 += M5.Lcd.drawString("Tue", xpos0 + 10, ypos0); } else if (w
== 3) {
xpos0 += M5.Lcd.drawString("Wed", xpos0 + 10, ypos0); } else if (w
== 4) {
xpos0 += M5.Lcd.drawString("Thu", xpos0 + 10, ypos0); } else if (w
== 5) {
xpos0 += M5.Lcd.drawString("Fri", xpos0 + 10, ypos0); } else if (w
== 6) {
xpos0 += M5.Lcd.drawString("Sat", xpos0 + 10, ypos0); }
M5.Lcd.setTextSize(1); } void connection() { //wifiにつながるまで while
(WiFi.status() != WL_CONNECTED) {
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
WiFi.waitForConnectResult(); } //ntpサーバに接続 configTime(9 *
3600L, 0, "ntp.nict.jp", "time.google.com",
"ntp.jst.mfeed.ad.jp"); //時刻反映
getLocalTime(&timeInfo);
WiFi.disconnect(); } void gettime() {
getLocalTime(&timeInfo); myear =
timeInfo.tm_year + 1900; mon =
timeInfo.tm_mon + 1; mday =
timeInfo.tm_mday; hh =
timeInfo.tm_hour; mm =
timeInfo.tm_min; ss =
timeInfo.tm_sec; |
【バックナンバー】