语言
0.91寸OLED显示屏是一款基于I2C通信的低功耗显示模块,分辨率为128x32。它支持与Jetson系列主控、树莓派、香橙派等多种开发板连接,可实时显示系统运行状态信息。
核心功能
- 📊 实时显示CPU使用率
- ⏰ 显示当前系统时间
- 💾 显示内存使用率和总内存
- 🗄️ 显示TF卡空间使用率
- 🌐 显示设备本地IP地址
- 🔌 支持热插拔,稳定可靠
硬件连接
接线说明
采用I2C通信接口,接线方式如下:
| OLED引脚 | 开发板引脚 |
|---|---|
| VCC | 3.3V |
| GND | GND |
| SDA | I2C SDA |
| SCL | I2C SCL |
⚠️ 注意:请确保接线正确,避免引脚短路,否则可能导致主板硬件损坏!
软件使用指南
支持平台:
- ✅ Jetson系列主控
- ✅ 所有树莓派型号
- ✅ 所有香橙派型号
- ✅ 其他支持I2C通信的Linux开发板
Jetson系列安装步骤
1. 安装依赖
sudo apt install -y python3-pip
sudo pip3 install smbus
sudo pip3 install Adafruit_SSD1306
2. 检测I2C设备
# 列出所有I2C总线
i2cdetect -l
# 检测I2C设备,OLED默认地址为0x3c
i2cdetect -y -r *
3. 运行测试代码
#!/usr/bin/env python3
# coding=utf-8
import time
import os
import sys
import Adafruit_SSD1306 as SSD
from PIL import Image, ImageDraw, ImageFont
import subprocess
class Juxi_OLED:
def __init__(self, i2c_bus=1, debug=False):
self.__debug = debug
self.__i2c_bus = i2c_bus
self.__top = -2
self.__x = 0
self.__total_last = 0
self.__idle_last = 0
self.__str_CPU = "CPU:0%"
# 初始化OLED,成功返回True,失败返回False
def begin(self):
try:
self.__oled = SSD.SSD1306_128_32(rst=None, i2c_bus=self.__i2c_bus, gpio=1)
self.__oled.begin()
self.__oled.clear()
self.__oled.display()
self.__width = self.__oled.width
self.__height = self.__oled.height
self.__image = Image.new('1', (self.__width, self.__height))
self.__draw = ImageDraw.Draw(self.__image)
self.__font = ImageFont.truetype("DejaVuSansMono.ttf",8)
return True
except:
return False
# 清空显示,refresh=True表示立即刷新
def clear(self, refresh=False):
self.__draw.rectangle((0, 0, self.__width, self.__height), outline=0, fill=0)
if refresh:
self.refresh()
# 在指定位置添加文本
def add_text(self, start_x, start_y, text, refresh=False):
if start_x > 128 or start_x < 0 or start_y < 0 or start_y > 32:
return
x = int(start_x + self.__x)
y = int(start_y + self.__top)
self.__draw.text((x, y), str(text), font=self.__font, fill=255)
if refresh:
self.refresh()
# 在指定行(1-4)添加文本
def add_line(self, text, line=1, refresh=False):
if line < 1 or line > 4:
return
y = int(8 * (line - 1))
self.add_text(0, y, text, refresh)
# 刷新OLED显示
def refresh(self):
self.__oled.image(self.__image)
self.__oled.display()
# 获取CPU使用率
def getCPULoadRate(self, index):
count = 10
if index == 0:
f1 = os.popen("cat /proc/stat", 'r')
stat1 = f1.readline()
data_1 = []
for i in range(count):
data_1.append(int(stat1.split(' ')[i+2]))
self.__total_last = sum(data_1)
self.__idle_last = data_1[3]
elif index == 4:
f2 = os.popen("cat /proc/stat", 'r')
stat2 = f2.readline()
data_2 = []
for i in range(count):
data_2.append(int(stat2.split(' ')[i+2]))
total_now = sum(data_2)
idle_now = data_2[3]
total = int(total_now - self.__total_last)
idle = int(idle_now - self.__idle_last)
usage = int(total - idle)
usageRate = int(float(usage / total) * 100)
self.__str_CPU = "CPU:" + str(usageRate) + "%"
self.__total_last = 0
self.__idle_last = 0
return self.__str_CPU
# 获取系统时间
def getSystemTime(self):
cmd = "date +%H:%M:%S"
date_time = subprocess.check_output(cmd, shell=True)
str_Time = str(date_time).lstrip('b\'').rstrip('\\n\'')
return str_Time
# 获取内存使用率
def getUsagedRAM(self):
cmd = "free | awk 'NR==2{printf \"RAM:%2d%% -> %.1fGB \", 100*($2-$7)/$2, ($2/1048576.0)}'"
FreeRam = subprocess.check_output(cmd, shell=True)
str_FreeRam = str(FreeRam).lstrip('b\'').rstrip('\'')
return str_FreeRam
# 获取磁盘使用率
def getUsagedDisk(self):
cmd = "df -h | awk '$NF==\"/\"{printf \"SDC:%s -> %.1fGB\", $5, $2}'"
Disk = subprocess.check_output(cmd, shell=True)
str_Disk = str(Disk).lstrip('b\'').rstrip('\'')
return str_Disk
# 获取本地IP地址
def getLocalIP(self):
ip = os.popen("/sbin/ifconfig enP8p1s0 | grep 'inet' | awk '{print $2}'").read()
ip = ip[0: ip.find('\n')]
if(ip == ''):
ip = os.popen("/sbin/ifconfig wlP1p1s0 | grep 'inet' | awk '{print $2}'").read()
ip = ip[0: ip.find('\n')]
if(ip == ''):
ip = 'x.x.x.x'
if len(ip) > 15:
ip = 'x.x.x.x'
return ip
# 主运行循环,支持热插拔
def main_program(self):
state = False
try:
cpu_index = 0
state = self.begin()
while state:
self.clear()
str_CPU = self.getCPULoadRate(cpu_index)
str_Time = self.getSystemTime()
if cpu_index == 0:
str_FreeRAM = self.getUsagedRAM()
str_Disk = self.getUsagedDisk()
str_IP = "IPA:" + self.getLocalIP()
self.add_text(0, 0, str_CPU)
self.add_text(50, 0, str_Time)
self.add_line(str_FreeRAM, 2)
self.add_line(str_Disk, 3)
self.add_line(str_IP, 4)
self.refresh()
cpu_index = cpu_index + 1
if cpu_index >= 5:
cpu_index = 0
time.sleep(.1)
except:
pass
if __name__ == "__main__":
try:
i2c_num = 7
if len(sys.argv) > 1:
if str(sys.argv[1]).isdigit():
i2c_num = int(sys.argv[1])
oled = Juxi_OLED(i2c_num, debug=True)
while True:
oled.main_program()
time.sleep(2)
except KeyboardInterrupt:
oled.clear(True)
del oled
print(" Program closed! ")
pass
4. 启动程序
# 默认总线7
python3 Oled_i2c.py
# 或指定总线(如总线1)
python3 Oled_i2c.py 1
树莓派 / 香橙派安装步骤
1. 启用I2C接口
进入系统设置:Preferences → Raspberry Pi Configuration → Interfaces → 启用I2C选项,然后重启系统。
或者使用命令行模式:
sudo raspi-config
# 选择Interface Options → I2C → Enable → 重启系统
2. 安装依赖
sudo apt install -y python3-dev python3-smbus i2c-tools python3-pil python3-pip python3-setuptools python3-rpi.gpio python3-venv
# 安装所需字体
sudo apt-get install -y fonts-dejavu-core
3. 配置权限
sudo chmod a+rw /dev/i2c-* # 临时生效,永久生效需配置udev规则
4. 检测设备
i2cdetect -y 1
# 正常情况下会显示设备地址0x3c
5. 创建虚拟环境(推荐)
# 安装虚拟环境工具(如果未安装)
sudo apt-get install -y python3-venv
# 创建虚拟环境
python3 -m venv oled_env
# 激活虚拟环境
source oled_env/bin/activate
# 安装所需库
pip install Adafruit_SSD1306 pillow -i https://mirrors.aliyun.com/pypi/simple/
6. 运行程序
python3 Oled_i2c.py 1
# 如果出现权限错误,请检查sudo配置或I2C设备权限
显示效果
程序成功运行后,OLED屏幕将分4行显示以下信息:
- 第一行:CPU使用率 + 系统时间
- 第二行:内存使用率 + 总内存
- 第三行:TF卡使用率 + 总容量
- 第四行:设备本地IP地址
相关链接

