SSD1306 是一款常见的 OLED(有机发光二极管)显示驱动芯片,常用于小型单色 OLED 显示屏,分辨率一般为 128×64 或 128×32。这里展示的是 I2C(两线:SCL、SDA)的通信方式
硬件接线
|SSD1306|ESP32(默认 I2C)|
|:—:—|:—:—|
|VCC|3.3V 或 5V|
|GND|GND|
|SCL|GPIO22(SCL)|
|SDA|GPIO21(SDA)|
查找 I2C 设备
1
2
3
4
5
6
7
8
9
|
from machine import Pin, I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
devices = i2c.scan() # 扫描 I2C 设备
if devices:
print("I2C 设备地址:", [hex(dev) for dev in devices])
else:
print("未找到 I2C 设备,请检查接线!")
|
程序返回:
程序
显示文字
注意:需下载并上传 ssd1306.py
到 ESP32
1
2
3
4
5
6
7
8
9
10
|
from machine import Pin, SoftI2C
import ssd1306
# 初始化 I2C
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# 显示文本
oled.text("Coffeelize, Go home!", 20, 30)
oled.show()
|
如果要显示大字体,可以下载 symbol.py
并上传到 ESP32
symbol.py
是一个自定义库,用于在 SSD1306 OLED 屏幕上 显示大字体(16x16 或更大)。因为在 MicroPython 的 ssd1306 官方驱动中,text() 方法只能显示 默认 8x8 像素的 ASCII 字符,字体有些小
1
2
3
4
5
6
7
8
9
10
11
12
|
from machine import Pin, SoftI2C
import ssd1306
import symbol
# 初始化 I2C
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
dsp = symbol.Symbol(oled) # 仍然保留 symbol
# 显示文本
oled.text("Meow, Go home!", 20, 30)
oled.show()
|
迷你像素画/动画
例如在屏幕中绘制一个移动端点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import ssd1306
from machine import Pin, SoftI2C
import time
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
x, y = 0, 30
dx = 1 # 方向
while True:
oled.fill(0) # 清屏
oled.pixel(x, y, 1) # 画一个点
oled.show()
x += dx
if x >= 128 or x <= 0:
dx = -dx # 反向移动
time.sleep(0.05)
|
电子时钟
可以结合 ESP32 内部 RTC 来做一个 电子时钟
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import network
import ssd1306
import time
from machine import Pin, SoftI2C
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
while True:
t = time.localtime()
now = f"{t[3]:02d}:{t[4]:02d}:{t[5]:02d}" # 格式化小时:分钟:秒
oled.fill(0) # 清屏
oled.text("Current Time:", 10, 20)
oled.text(now, 35, 40)
oled.show()
time.sleep(1)
|
GUI
参考资料:GitHub - peterhinch/micropython-nano-gui: A lightweight MicroPython GUI library for display drivers based on framebuf class