#include <WiFi.h>
#include <time.h>
#include <U8g2lib.h> //引入OLED程式庫
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE);
const char ssid[]="efewfew123232412"; //Wifi基地台ID
const char psw[]="42190471240";
const char ntpServer[] = "pool.ntp.org";
const uint16_t utcOffest = 28800; // UTC+8偏移量
const uint8_t daylightOffset = 0; // 夏令時間
void setup() {
Serial.begin(115200);
u8g2.begin(); //初始顯示器物件
u8g2.setFont(u8g2_font_t0_22b_te); //指定字型
WiFi.begin(ssid, psw); //指定連線資訊
//嘗試間隔0.5秒連線一次,直到連線成功
while (WiFi.status() != WL_CONNECTED) {
Serial.print("WIFI連線中 \n");
delay(500);
}
Serial.print("IP位址:");
Serial.println(WiFi.localIP());
//取回網路標準時間
configTime(utcOffest, daylightOffset, ntpServer); //UCT偏移量,夏日時間,時間伺服器
delay(1000);
}
void loop() {
struct tm now; // 建立時間結構變數
if(!getLocalTime(&now)){ // 測試是否取得本地時間
u8g2.clearBuffer(); //清除暫存區
u8g2.drawStr(5, 55, "ERROR!!");
u8g2.sendBuffer(); //送出繪製內容
return;
}
//在OLED中顯示日期時間
u8g2.firstPage();
do {
u8g2.setCursor(5, 20);
u8g2.print(&now, "%Y/%m/%d"); //列印日期
u8g2.setCursor(15, 62);
u8g2.print(&now, "%H:%M:%S"); //列印時間
} while ( u8g2.nextPage() );
delay(1000);
}