一、实验目标
给树莓派添加一个小的OLED屏幕,用来显示网口IP地址、CPU/MEM利用率和当前时间。
二、实验器材
1、oled屏通讯方式采用IIC通讯;
2、树莓派5,开启I2C功能;
3、杜邦线4根,采用I2C通信,连接树莓派的I2C pin引脚。
三、实现代码
字体文件拷贝到代码目录。
from luma.core.interface.serial import i2c, spi
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
import netifaces
import time
import psutil
from PIL import ImageFont
font = ImageFont.truetype('./msyh.ttc', 11, encoding='unic')
WIDTH = 128
HEIGHT = 32
def getIPAddr():
ip_addresses = {}
for interface in netifaces.interfaces():
if interface != 'lo':
try:
addrs = netifaces.ifaddresses(interface)
ip_addresses[interface] = addrs[netifaces.AF_INET][0]['addr']
except:
ip_addresses[interface] = '0.0.0.0'
return ip_addresses
def getCPU():
return psutil.cpu_percent()
def getMem():
free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
return int(memory * 100)
def getCurDate():
curDate = time.strftime("%Y年%m月%d日",time.localtime())
return curDate
def getCurTime():
curTime = time.strftime("%H:%M:%S",time.localtime())
return curTime
def mydraw(draw,x,y,message):
draw.text((x,y), message, font=font, fill='white')
disp = ssd1306(i2c(port=1, address=0x3C), rotate=2, width=WIDTH, height=HEIGHT)
while True:
with canvas(disp) as draw:
ipAddr = getIPAddr()
mydraw(draw, 0, 0, f"有线 : {ipAddr['eth0']}")
mydraw(draw, 0,16, f"无线 : {ipAddr['wlan0']}")
time.sleep(5)
disp.clear()
with canvas(disp) as draw:
cpuPer = getCPU()
memPer = getMem()
mydraw(draw, 0,0, f"CPU利用率:{cpuPer} %")
mydraw(draw, 0,16, f"Mem利用率:{memPer} %")
time.sleep(2)
disp.clear()
with canvas(disp) as draw:
mydraw(draw,0,0, f"{getCurDate()}")
mydraw(draw,0,16, f"{getCurTime()}")
time.sleep(2)
disp.clear()