1. 程式人生 > 其它 >通過wifi獲取時間並顯示

通過wifi獲取時間並顯示

官方提供的例程很詳盡,本程式設定了時區引數gmtOffset_sec為8*60*60

#include <M5Stack.h>
#include <WiFi.h>
#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(); }