通过wifi获取时间并显示
官方提供的例程很详尽,本程序设置了时区参数gmtOffset_sec为8*60*60
#include#include #include "time.h" // Set the name and password of the wifi to be connected. 配置所连接wifi的名称和密码 const char* ssid = "就是WiFi的名称"; const char* password = ""; const char* ntpServer = "time1.aliyun.com"; //Set the connect NTP server. 设置连接的NTP服务器 const long gmtOffset_sec = 28800;//这里采用UTC计时,中国为东八区,就是 8*60*60 const int daylightOffset_sec = 3600; struct tm timeinfo; void printLocalTime(){ //Output current time. 输出当前时间 if(!getLocalTime(&timeinfo)){ //Return 1 when the time is successfully obtained. 成功获取到时间返回1 M5.Lcd.println("Failed to obtain time"); return; } M5.Lcd.println(&timeinfo, "%A, %B %d \n%Y %H:%M:%S"); //Screen prints date and time. 屏幕打印日期和时间 } void setup(){ M5.begin(); //Init M5Core. 初始化 M5Core M5.Lcd.setTextSize(3); //Set the font size to 3. 设置字号大小为3 M5.Lcd.printf("\nConnecting to %s", ssid); WiFi.begin(ssid, password); //Connect wifi and return connection status. 连接wifi并返回连接状态 while(WiFi.status() != WL_CONNECTED) { //If the wifi connection fails. 若wifi未连接成功 delay(500); //delay 0.5s. 延迟0.5s M5.Lcd.print("."); } M5.Lcd.println("\nCONNECTED!"); configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); //init and get the time. 初始化并设置NTP getLocalTime(&timeinfo);//必须要获取一下 WiFi.disconnect(true); //Disconnect wifi. 断开wifi连接 WiFi.mode(WIFI_OFF); //Set the wifi mode to off. 设置wifi模式为关闭 M5.Lcd.fillScreen(BLACK); delay(20); } void loop(){ delay(1000); M5.Lcd.setCursor(0,50); //设置光标处于(0,50) printLocalTime(); }