OLED显示当前时间

Uncategorized
318 words

ESP32学习笔记(一)

材料

ESP32-WROOM-32

OLED(我的驱动芯片是sh1106)

细节

  1. 由于OLED是sh1106不是常用的SSD1306,所以库引入得引入u8g2这个库

  2. 这里要使用 U8G2_SH1106_128X64_NONAME_F_SW_I2C 软连接 这个类,用硬连接方式不行

  3. WiFi的库也要修改,例程的库用的是ESP8266,要改成我们ESP32的<WiFi.h>这个就行了

  4. u8g2字库文档

中文字库 https://github.com/larryli/u8g2_wqy

英文字库 https://github.com/olikraus/u8g2/wiki/fntlistall

代码

time_OLED.ino的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiClient.h>
#include <WiFiGeneric.h>
#include <WiFiMulti.h>
#include <WiFiSTA.h>
#include <WiFiScan.h>
#include <WiFiServer.h>
#include <WiFiType.h>
#include <WiFiUdp.h>

#include <NTPClient.h>
// change next line to use with another board/shield

//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

#include <U8g2lib.h> // 导入 U8g2 库

#define SDA_PIN 21 // 替换为实际 SDA(数据)引脚号
#define SCL_PIN 22 // 替换为实际 SCL(时钟)引脚号

U8G2_SH1106_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, SCL_PIN, SDA_PIN, U8X8_PIN_NONE); // 创建 SH1106 OLED 对象


const char *ssid = "Reyee";
const char *password = "13907922579";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

void setup(){
Serial.begin(115200);

u8g2.begin(); // 初始化 OLED 屏幕
u8g2.setFont(u8g2_font_inb16_mf); // 设置字体
u8g2.clearBuffer(); // 清空缓冲区


WiFi.begin(ssid, password);

while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}

timeClient.begin();
timeClient.setTimeOffset(28800);
}

void loop() {
timeClient.update();

Serial.println(timeClient.getFormattedTime());
u8g2.setCursor(0, 30); // 设置光标位置
u8g2.print(timeClient.getFormattedTime()); // 显示时间
u8g2.sendBuffer(); // 将缓冲区内容发送到 OLED 屏幕显示
delay(1000);
u8g2.clearBuffer(); // 清空缓冲区
}