硬件连接
SSD1306 ------>ESP32
GND ------> GND
VCC ------> 3V3
SCL ------> D22
SDA ------> D21
下载库文件
打开Arduino----------->库管理----------->搜索SSD1306----------->安装Adafruit SSD1306
// Author: David
// Date:16 Oct,2022
//ESP32 Arduino驱动0.91" OLED
//ESP32 DEVKITV1
//Arduino V1.8.19
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
// 引入驱动OLED0.91所需的库
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // 设置OLED宽度,单位:像素
#define SCREEN_HEIGHT 64 // 设置OLED高度,单位:像素
// 自定义重置引脚,虽然教程未使用,但却是Adafruit_SSD1306库文件所必需的
#define OLED_RESET 4
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const char *ssid = "REALIZE"; //你的网络名称
const char *password = "123456"; //你的网络密码
const char *ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 8 * 3600;
const int daylightOffset_sec = 0;
void printLocalTime()
{
struct tm timeinfo;
if (!getLocalTime(&timeinfo))
{
display.println("Failed to obtain time");
return;
}
display.println(&timeinfo, "%F"); // 格式化输出
display.println(&timeinfo, "%T"); // 格式化输出
display.println(&timeinfo, "%A"); // 格式化输出
}
void setup()
{
// put your setup code here, to run once:
//设置I2C的两个引脚SDA和SCL,这里用到的是17作为SDA,16作为SCL
Wire.setPins(/*SDA*/21,/*SCL*/22);
//初始化OLED并设置其IIC地址为 0x3C
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
//清除屏幕
display.clearDisplay();
//设置字体颜色,白色可见
display.setTextColor(WHITE);
//设置字体大小
display.setTextSize(2);
//设置光标位置
display.setCursor(1, 1);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
display.print(".");
}
display.println("WiFi connected!");
// 从网络时间服务器上获取并设置时间
// 获取成功后芯片会使用RTC时钟保持时间的更新
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
display.println("WiFi disconnected!");
display.display();
}
void loop()
{
// put your main code here, to run repeatedly:、
delay(1000);
//清除屏幕
display.clearDisplay();
//设置光标位置
display.setCursor(0, 0);
printLocalTime();
display.display();
}