演示:
✨本案例采用1.3寸OLED屏幕,同时保留0.96屏幕接口函数,只要u8g2库支持的屏幕都可以,需要到\U8g2\src\U8g2lib.h
中匹配自己的屏幕函数接口。
SDA-----> 21
SCL----->22
所需库都可以在IDE管理库当中下载到。
U8g2库
Ticker库
#include
#include //包含u8g2头文件,用于OLED显示
//#include //包含ESP8266头文件
#include
#include //调用Ticker.h库
#define NTP1 "ntp1.aliyun.com"
#define NTP2 "ntp2.aliyun.com"
#define NTP3 "ntp3.aliyun.com"
#ifndef STASSID
#define STASSID "MERCURY_D268G"
#define STAPSK "pba5ayzk"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
#define U8X8_HAVE_HW_I2C
//U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // 1.3寸,默认引脚
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE, /* clock=*/22, /* data=*/21); // 1.3寸,指定引脚
//U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);//0.96寸,默认引脚
//U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE, /* clock=*/22, /* data=*/21); //0.96寸,指定引脚
#ifdef U8X8_HAVE_HW_I2C //定义OLED连接方式为I2C
#include
#endif
const String WDAY_NAMES[] = {"Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //星期
void printLocalTime(){
struct tm timeInfo;//声明一个结构体
char buff[16];
if (!getLocalTime(&timeInfo))
{
Serial.println("Failed to obtain time");
u8g2.setCursor(0,9);
u8g2.print("NTP time failure");
return;
}
// Serial.println(&timeinfo, "%F %T %a"); // 格式化输出,串口显示
String date = WDAY_NAMES[timeInfo.tm_wday];
u8g2.clearBuffer();
sprintf_P(buff, PSTR("%04d-%02d-%02d %s"), timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday, WDAY_NAMES[timeInfo.tm_wday].c_str());
u8g2.setFont(u8g2_font_wqy14_t_gb2312a);
u8g2.setCursor(9 , 20 ); //年份居中显示
u8g2.println(buff);//显示出年份
//Serial.println(buff);
sprintf_P(buff, PSTR("%02d:%02d:%02d"), timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);//时间
u8g2.setFont(u8g2_font_fur17_tn);
u8g2.drawStr(19 , 45 , buff);
u8g2.sendBuffer();
}
Ticker timer1(printLocalTime, 1000);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
u8g2.begin(); //初始化OLED
WiFi.mode(WIFI_STA); //设置ESP32工作模式为无线终端模式
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
configTime(8 * 3600, 0, NTP1, NTP2,NTP3);
u8g2.setPowerSave(0);// 关省电模式
timer1.start();
}
void loop() {
timer1.update();
}