M5Stack PaperS3という電子ペーパーディスプレイモジュールを使って日めくりカレンダーを作成しました。毎日変わる名言付き。
英語解説(Hackster)はコチラ

特長
自動画面回転
本体を縦向き・横向きのどちらで設置しても、自動的に向きを検出して表示を切り替えます。付属の3Dプリント製スタンドは、どちらの向きでも設置できるように設計されています。


超低消費電力設計
毎日午前0時を少し過ぎたタイミングでのみ起動し、日付の更新と新しい名言の取得を行います。それ以外の時間はRTC(リアルタイムクロック)を利用したディープスリープ状態を維持します。さらに、表示保持に電力をほとんど必要としない電子ペーパーディスプレイを採用しているため、1回の充電で1週間以上動作します。

APIによる名言取得と時刻同期
名言は「名言教えるよ!」APIから取得しています。また、時刻はNTP(Network Time Protocol)によってインターネット経由で自動同期されるため、常に正確な日時を表示できます。
名言の長さに応じた自動文字サイズ調整
名言の文字数に応じてフォントサイズを自動で調整します。長い名言でも表示領域内に収まるよう最適化されるため、文章が途中で切れてしまうことなく表示できます。

バッテリー残量表示
画面上にバッテリー残量を表示することで、充電が必要なタイミングをひと目で確認できます。

Arduinoコード
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 |
//日めくりカレンダー名言付き #include <M5Unified.h> #include <WiFi.h> #include <time.h> #include <HTTPClient.h> #include <Arduino_JSON.h> // ===== WiFi設定 ===== #define WIFI_SSID "YourWifiSSID" #define WIFI_PASSWORD "YourWifiPassword" // 名言API const char* apiUrl = "https://meigen.doodlenote.net/api/json.php?c=1"; const bool EnableRotate = true; //横向き表示を有効にする // ===== レイアウト関連定数 ===== const int MARGIN_X = 10; const int MARGIN_Y = 10; //const int LINE_SPACING = 34; const int AUTHOR_MARGIN = 70; int y_year = 20; int y_month = 100; int y_day = 200; int y_weekday = 430; int y_meigen = 530; int NTP_ICON_X = 400; int NTP_ICON_Y = 10; int NTP_ICON_SIZE = 50; bool isLandscape = false; // ===== NTP設定(日本)===== #if __has_include(<esp_sntp.h>) #include <esp_sntp.h> #define SNTP_ENABLED 1 #elif __has_include(<sntp.h>) #include <sntp.h> #define SNTP_ENABLED 1 #endif #ifndef SNTP_ENABLED #define SNTP_ENABLED 0 #endif #define NTP_TIMEZONE "UTC-9" // POSIX standard, in which "UTC+0" is UTC London, "UTC-8" is UTC+8 Beijing, "UTC+5" is UTC-5 New York #define NTP_SERVER1 "0.pool.ntp.org" #define NTP_SERVER2 "1.pool.ntp.org" #define NTP_SERVER3 "2.pool.ntp.org" //NTP, WiFi接続完了のフラグ bool ntpSynced, wifiConnected; const char* MONTH_EN[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const char* WEEKDAY_EN[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; const char* WEEKDAY_JP[] = {"日", "月", "火", "水", "木", "金", "土"}; // -------------------------------------------------- // 名言のフォントサイズを自動調整 // -------------------------------------------------- float decideTextSizeToFit( const String& meigen, int areaWidth, int areaHeight, int* outTextHeight ) { const float TEXT_SIZE_MAX = 1.3; const float TEXT_SIZE_MIN = 0.3; const float TEXT_STEP = 0.1; M5.Display.setFont(&fonts::lgfxJapanGothicP_40); for (float size = TEXT_SIZE_MAX; size >= TEXT_SIZE_MIN; size -= TEXT_STEP) { M5.Display.setTextSize(size); int fontH = M5.Display.fontHeight(); int textW = M5.Display.textWidth(meigen); int lines = (textW + areaWidth - 1) / areaWidth; int textHeight = lines * fontH; Serial.printf( "[FontCheck] size=%.1f fontH=%d textW=%d lines=%d textH=%d\n", size, fontH, textW, lines, textHeight ); if (textHeight <= areaHeight) { *outTextHeight = textHeight; Serial.printf("[FontSelect] size=%.1f selected\n", size); return size; } } // フォールバック M5.Display.setTextSize(TEXT_SIZE_MIN); *outTextHeight = areaHeight; Serial.println("[FontSelect] fallback to min size"); return TEXT_SIZE_MIN; } // -------------------------------------------------- // 名言を自動改行で表示、作者を右揃え // -------------------------------------------------- void displayQuote(const String& meigen, const String& auther) { int screenW = M5.Display.width(); int screenH = M5.Display.height(); M5.Display.setTextColor(BLACK, WHITE); // ================================================== // 縦表示 // ================================================== if (!isLandscape) { int areaTop = y_meigen; int areaBottom = screenH - MARGIN_Y; int areaHeight = areaBottom - areaTop; int areaWidth = screenW - MARGIN_X * 2; int quoteTextHeight = 0; float quoteTextSize = decideTextSizeToFit( meigen, areaWidth, areaHeight - AUTHOR_MARGIN, "eTextHeight ); int startY = areaTop + (areaHeight - quoteTextHeight - AUTHOR_MARGIN) / 2; M5.Display.setFont(&fonts::lgfxJapanGothicP_40); M5.Display.setTextSize(quoteTextSize); M5.Display.setTextDatum(top_left); M5.Display.setCursor(MARGIN_X, startY); M5.Display.printf("『%s』", meigen.c_str()); M5.Display.setFont(&fonts::lgfxJapanGothicP_28); M5.Display.setTextSize(1); String authorText = "- " + auther + " -"; int w = M5.Display.textWidth(authorText); M5.Display.drawString( authorText, M5.Display.width() - w, screenH - 45 ); return; } // ================================================== // 横表示 // ================================================== int quoteCenterX = screenW * 3 / 4; int quoteAreaW = screenW / 2 - 40; int quoteTextHeight = 0; float quoteTextSize = decideTextSizeToFit( meigen, quoteAreaW, screenH - 120, "eTextHeight ); String quoteText = "『" + meigen + "』"; M5.Display.setFont(&fonts::lgfxJapanGothicP_40); M5.Display.setTextSize(quoteTextSize); int quoteWidth = M5.Display.textWidth(quoteText); int quoteX = quoteCenterX - quoteWidth / 2; int quoteY = (screenH - quoteTextHeight) / 2 - 30; M5.Display.setClipRect( screenW / 2, 0, screenW / 2, screenH ); M5.Display.setTextWrap(true); M5.Display.setCursor(quoteX, quoteY); M5.Display.print(quoteText); M5.Display.clearClipRect(); // 作者 M5.Display.setFont(&fonts::lgfxJapanGothicP_28); M5.Display.setTextSize(1); String authorText = "- " + auther + " -"; M5.Display.setTextDatum(bottom_right); M5.Display.drawString( "- " + auther + " -", M5.Display.width()-10, M5.Display.height() - 20 ); } void setup() { Serial.begin(115200); //delay(2000);//USBSerilaの準備完了までの待ち Serial.println("=== BOOT ==="); auto cfg = M5.config(); M5.begin(cfg); //横向き表示を有効に if(EnableRotate){ M5.Imu.begin(); delay(500);//IMUが安定するまで待つ int rotation = updateRotationByIMU(); Serial.printf("rotation=%d\n", rotation); M5.Display.setRotation(rotation); isLandscape = (rotation == 1 || rotation == 3); } else{ M5.Display.setRotation(2); } setupLayout(); M5.Display.setEpdMode(epd_quality); // epd_quality, epd_text, epd_fast, epd_fastest //タイムゾーン設定 setenv("TZ", NTP_TIMEZONE, 1); tzset(); //RTCの値を内蔵時計と同期 syncRtcToSystemTime(); // ---- WiFi接続 ---- Serial.println("[WiFi] Connecting..."); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); if (WiFi.waitForConnectResult() == WL_CONNECTED) { wifiConnected = true; //NTP同期、RTCに書き込み ntpSynced = syncTimeWithNTP(); } else{ Serial.println("WiFi Connect Failed"); wifiConnected = false; } //日時呼び出し time_t t = time(nullptr); struct tm timeinfo; localtime_r(&t, &timeinfo); // ---- 日時取得内容確認 ---- Serial.println("[NTP] Time acquired"); Serial.printf(" %04d/%02d/%02d %02d:%02d:%02d\n", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec); Serial.printf(" weekday = %d (%s)\n", timeinfo.tm_wday, WEEKDAY_JP[timeinfo.tm_wday]); // ---- カレンダー表示 ---- M5.Display.clear(); drawCalendar(timeinfo); // ---- バッテリ残量 ---- int batt = M5.Power.getBatteryLevel(); // 0〜100 if(isLandscape){ drawBatteryIcon(15, 10, batt); } else{ drawBatteryIcon(M5.Display.width() - 70, 10, batt); } //WiFi接続時 if (wifiConnected) { // ---- 名言表示 ---- fetchAndShowQuote(); //WiFi切断 WiFi.disconnect(true); WiFi.mode(WIFI_OFF); Serial.println("[WiFi] OFF"); if(!ntpSynced){ //NTP同期失敗アイコンを表示 Serial.println("NTP Sync Failed"); drawNtpErrorIcon(); } } else{ Serial.println("WiFi Connect Failed"); drawNtpErrorIcon(); } Serial.println("[DISPLAY] done"); // ---- 次の0:00計算 ---- time_t now = mktime(&timeinfo); struct tm nextDay = timeinfo; nextDay.tm_hour = 0; nextDay.tm_min = 15;//次の日ギリギリにならないように15分追加 nextDay.tm_sec = 0; nextDay.tm_mday += 1; time_t next = mktime(&nextDay); uint64_t sleep_sec = difftime(next, now); Serial.printf("[SLEEP] sleep_sec = %llu\n", sleep_sec); Serial.println("[SLEEP] deep sleep in 10 seconds..."); delay(500); esp_sleep_enable_timer_wakeup(sleep_sec * 1000000ULL); esp_deep_sleep_start(); } void loop() { } // =============================== // 日付・曜日描画 // =============================== void drawCalendar(struct tm& t) { Serial.println("[DISPLAY] drawCalendar()"); int w = M5.Display.width(); int h = M5.Display.height(); int cx; if (isLandscape) { // 左半分の中央 cx = w / 4; } else { cx = w / 2; } char buf[32]; // ---- 年 ---- M5.Display.setTextColor(BLACK); M5.Display.setTextDatum(top_center); M5.Display.setTextSize(0.8); M5.Display.setFont(&fonts::Font8);//数字のみ snprintf(buf, sizeof(buf), "%d", t.tm_year + 1900); M5.Display.drawString(buf, cx, y_year); // ---- 月(英語)---- M5.Display.setTextSize(2); // フォントを小さく M5.Display.setFont(&fonts::lgfxJapanGothic_40); M5.Display.drawString(MONTH_EN[t.tm_mon], cx, y_month); //土日はフォントの色を薄くする bool isWeekend = (t.tm_wday == 0 || t.tm_wday == 6); uint16_t mainColor = isWeekend ? DARKGREY : BLACK; M5.Display.setTextColor(mainColor, WHITE); // ---- 日(大きく)---- M5.Display.setTextSize(3); // フォントを大きく M5.Display.setFont(&fonts::Font8);//数字のみ snprintf(buf, sizeof(buf), "%d", t.tm_mday); M5.Display.drawString(buf, cx, y_day); M5.Display.setTextSize(1); // 戻す // ---- 曜日(英語)---- M5.Display.setTextSize(2); // フォントを小さく M5.Display.setFont(&fonts::lgfxJapanGothic_40); M5.Display.drawString(WEEKDAY_EN[t.tm_wday], cx, y_weekday); // 色を戻す M5.Display.setTextColor(BLACK, WHITE); Serial.println("Calendar Display End"); } void setupLayout() { if (!isLandscape) { // ===== 縦 ===== y_year = 20; y_month = 100; y_day = 200; y_weekday = 430; y_meigen = 530; NTP_ICON_X = 400; NTP_ICON_Y = 10; } else { // ===== 横 ===== y_year = 20; y_month = 90; y_day = 180; y_weekday = 420; y_meigen = 0; NTP_ICON_X = 880; NTP_ICON_Y = 10; } } // -------------------------------------------------- //バッテリアイコン表示 // -------------------------------------------------- void drawBatteryIcon(int x, int y, int level) { Serial.printf("[DISPLAY] drawBattery(), Level = %d\n",level); const int w = 60; const int h = 32; const int capW = 8; const int capH = 14; // 本体(黒) M5.Display.fillRect(x, y, w, h, BLACK); // 端子 M5.Display.fillRect(x-capW, y + (h-capH)/2, capW, capH, BLACK); // 数字(白) char buf[8]; snprintf(buf, sizeof(buf), "%d", level); M5.Display.setTextColor(WHITE, BLACK); M5.Display.setTextSize(1); M5.Display.setFont(&fonts::lgfxJapanGothicP_24); M5.Display.drawCentreString(buf, x + w/2, y + 2); // 色を戻す M5.Display.setTextColor(BLACK, WHITE); } // -------------------------------------------------- // APIから名言を取得 // -------------------------------------------------- void fetchAndShowQuote() { Serial.println("[DISPLAY] fetchAndShowQuote()"); if (WiFi.status() != WL_CONNECTED) return; HTTPClient http; http.begin(apiUrl); int httpCode = http.GET(); if (httpCode <= 0) { http.end(); return; } String payload = http.getString(); http.end(); JSONVar root = JSON.parse(payload); if (JSON.typeof(root) == "undefined") return; String meigen = root[0]["meigen"]; String auther = root[0]["auther"]; Serial.print("Meigen: "); Serial.println(meigen); Serial.print("Auther: "); Serial.println(auther); displayQuote(meigen, auther); } // -------------------------------------------------- //加速度で画面の向きを調整 // -------------------------------------------------- int updateRotationByIMU() { float ax, ay, az; int rot; // 加速度取得 M5.Imu.update(); if (!M5.Imu.getAccel(&ax, &ay, &az)) { Serial.println("getAccel Failed"); return 3; // 取得失敗時 } Serial.printf("Accel x:%f, y:%f, z:%f\n",ax,ay,az); if (ay < -0.7) { rot = 3; // 通常横 } else if (ay > 0.7) { rot = 1; // 逆さ横 } else if (ax > 0.7) { rot = 0; // 通常縦 } else if (ax < -0.7) { rot = 2; // 逆さ縦 } else { rot = 3; } return rot; } // -------------------------------------------------- // 時刻をRTCからUTCで抜き出す // -------------------------------------------------- time_t timegm_like(struct tm *tm){ char *old_tz = getenv("TZ"); setenv("TZ", "UTC0", 1); tzset(); time_t t = mktime(tm); setenv("TZ", NTP_TIMEZONE, 1); tzset(); return t; } // -------------------------------------------------- // RTCから内蔵時計へ時間を書き出し // -------------------------------------------------- void syncRtcToSystemTime() { m5::rtc_time_t rtcTime; m5::rtc_date_t rtcDate; if (M5.Rtc.getTime(&rtcTime) && M5.Rtc.getDate(&rtcDate)) { struct tm tm_utc = {}; tm_utc.tm_year = rtcDate.year - 1900; tm_utc.tm_mon = rtcDate.month - 1; tm_utc.tm_mday = rtcDate.date; tm_utc.tm_hour = rtcTime.hours; tm_utc.tm_min = rtcTime.minutes; tm_utc.tm_sec = rtcTime.seconds; time_t epoch = timegm_like(&tm_utc); struct timeval tv; tv.tv_sec = epoch; tv.tv_usec = 0; settimeofday(&tv, nullptr); Serial.printf( "[RTC->SYS] %04d-%02d-%02d %02d:%02d:%02d UTC -> epoch=%ld\n", rtcDate.year, rtcDate.month, rtcDate.date, rtcTime.hours, rtcTime.minutes, rtcTime.seconds, (long)epoch ); } else { Serial.println("[RTC] read failed"); } } // -------------------------------------------------- //RTCをNTP(UTC)に同期する // -------------------------------------------------- bool syncTimeWithNTP(){ Serial.println("\nWiFi connected"); //ESP32の内蔵時計をNTPと同期 configTzTime(NTP_TIMEZONE, NTP_SERVER1, NTP_SERVER2, NTP_SERVER3); Serial.print("Time Zone:"); Serial.println(getenv("TZ")); Serial.print("NTP: "); uint32_t start = millis(); #if SNTP_ENABLED Serial.println("SNTP_Enabled"); while (sntp_get_sync_status() != SNTP_SYNC_STATUS_COMPLETED) { if (millis() - start > 10000) { Serial.println("[NTP] sync timeout"); return false; } Serial.print("."); delay(500); } #else Serial.println("SNTP_Unabled"); struct tm timeInfo; while (!getLocalTime(&timeInfo, 1000)) { if (millis() - start > 10000) { Serial.println("[NTP] sync timeout"); return false; } Serial.print("."); delay(500); } #endif Serial.println("\nNTP connected"); time_t t = time(nullptr) + 1; // Advance one second //time(nullptr)=1970/1/1 while (t > time(nullptr)) ; // Synchronization in seconds(内蔵時計の秒未満のタイミングを0にそろえる) M5.Rtc.setDateTime(gmtime(&t));//RTCにNTP同期の時間(UTC)を書き込み return true; } // -------------------------------------------------- //NTP同期失敗時のアイコン表示 // -------------------------------------------------- void drawNtpErrorIcon() { int cx = NTP_ICON_X + NTP_ICON_SIZE / 2; int cy = NTP_ICON_Y + NTP_ICON_SIZE / 2; int r = NTP_ICON_SIZE / 2 - 1; // 念のため背景クリア M5.Display.fillRect( NTP_ICON_X, NTP_ICON_Y, NTP_ICON_SIZE, NTP_ICON_SIZE, WHITE ); // 黒い円(●) M5.Display.fillCircle(cx, cy, r, BLACK); // 白い「!」 M5.Display.setTextColor(WHITE, BLACK); M5.Display.setTextDatum(middle_center); M5.Display.setFont(&fonts::Font4); M5.Display.setTextSize(1.5); M5.Display.drawString("!", cx, cy + 5); // 後始末(他描画への影響防止) M5.Display.setTextColor(BLACK, WHITE); M5.Display.setTextDatum(top_left); Serial.println("[EPD] NTP error icon drawn"); } |


コメント