Time.ino 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. *******************************************************************************
  3. * Copyright (c) 2022 by M5Stack
  4. * Equipped with M5Core sample source code
  5. * 配套 M5Core 示例源代码
  6. * Visit for more information: https://docs.m5stack.com/en/core/gray
  7. * 获取更多资料请访问: https://docs.m5stack.com/zh_CN/core/gray
  8. *
  9. * Describe: NTP TIME.
  10. * Date: 2021/8/3
  11. *******************************************************************************/
  12. #include <M5Stack.h>
  13. #include <WiFi.h>
  14. #include "time.h"
  15. // Set the name and password of the wifi to be connected.
  16. // 配置所连接wifi的名称和密码
  17. const char* ssid = "M5";
  18. const char* password = "123456";
  19. const char* ntpServer =
  20. "time1.aliyun.com"; // Set the connect NTP server. 设置连接的NTP服务器
  21. const long gmtOffset_sec = 0;
  22. const int daylightOffset_sec = 3600;
  23. void printLocalTime() { // Output current time. 输出当前时间
  24. struct tm timeinfo;
  25. if (!getLocalTime(&timeinfo)) { // Return 1 when the time is successfully
  26. // obtained. 成功获取到时间返回1
  27. M5.Lcd.println("Failed to obtain time");
  28. return;
  29. }
  30. M5.Lcd.println(&timeinfo,
  31. "%A, %B %d \n%Y %H:%M:%S"); // Screen prints date and time.
  32. // 屏幕打印日期和时间
  33. }
  34. void setup() {
  35. M5.begin(); // Init M5Core. 初始化 M5Core
  36. M5.Power.begin(); // Init power 初始化电源模块
  37. M5.Lcd.setTextSize(2); // Set the font size to 2. 设置字号大小为2
  38. M5.Lcd.printf("\nConnecting to %s", ssid);
  39. WiFi.begin(ssid, password); // Connect wifi and return connection status.
  40. // 连接wifi并返回连接状态
  41. while (WiFi.status() !=
  42. WL_CONNECTED) { // If the wifi connection fails. 若wifi未连接成功
  43. delay(500); // delay 0.5s. 延迟0.5s
  44. M5.Lcd.print(".");
  45. }
  46. M5.Lcd.println("\nCONNECTED!");
  47. configTime(gmtOffset_sec, daylightOffset_sec,
  48. ntpServer); // init and get the time. 初始化并设置NTP
  49. printLocalTime();
  50. WiFi.disconnect(true); // Disconnect wifi. 断开wifi连接
  51. WiFi.mode(WIFI_OFF); // Set the wifi mode to off. 设置wifi模式为关闭
  52. delay(20);
  53. }
  54. void loop() {
  55. delay(1000);
  56. M5.Lcd.setCursor(0, 47); // Set cursor to (0,47). 设置光标处于(0,47)
  57. printLocalTime();
  58. }