首先,上效果图
你可能需要的准备
- 配置ESP8266的Arduino IDE环境 - IDZD
- NodeMCU连接&固件烧录 - IDZD
- 半离线安装EPS8266支持到Arduino IDE
- NTPClient库
- 安装支持库 - IDZD
- ESP8266使用I2C连接OLDE屏幕
连线&安装NTPClient库
安装NTPClient库
这次我们选择NTPClient
库,联网获取ntp时间。
#获取UNIX时间戳
getEpochTime();
#获取当前时间
getFormattedTime();
#获取星期,0是星期日
getDay();
连线
- D1 --- SDA
- D2 --- SCL
- 3V --- VCC
- G --- GND
代码
#include <Arduino.h>
#include <U8g2lib.h>
#include <time.h>
#include <SPI.h>
#include <Wire.h>
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>
#define SDA 05 //ESP8266 D1 PIN 05
#define SCL 04 //ESP8266 D2 PIN 04
const char *ssid = "360 N7 Pro";
const char *password = "123456780";
char *week = "";
//SSD1306,128x64,全屏缓冲模式,模拟I2C,I2C,u8g2(旋转0度,时钟,数据,重置)
U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com",60*60*8, 30*60*1000);//设置访问的ntp服务器
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
timeClient.begin();
u8g2.begin();
u8g2.enableUTF8Print();
}
void loop() {
timeClient.update();
u8g2.setFont(u8g2_font_unifont_t_chinese2);
u8g2.firstPage();
do {
u8g2.setCursor(0, 15);
u8g2.print("北京时间:=");
u8g2.setCursor(0, 35);
u8g2.print(timeClient.getFormattedTime());
u8g2.setCursor(75, 35);
switch(timeClient.getDay();){
case 0:
week = "Sun.";
break;
case 1:
week = "Mon.";
break;
case 2:
week = "Tues.";
break;
case 3:
week = "Wed.";
break;
case 4:
week = "Thur.";
break;
case 5:
week = "Fri.";
break;
case 6:
week = "Sat.";
break;
}
u8g2.print(week);
u8g2.setCursor(0, 55);
time_t t;
struct tm *p;
t=timeClient.getEpochTime();
p=gmtime(&t);
char s[100];
//strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", p);
strftime(s, sizeof(s), "%Y年%m月%d日", p);
u8g2.print(s);
} while ( u8g2.nextPage() );
Serial.println(timeClient.getEpochTime());
delay(1000);
}