前言
操作oled屏幕去显示一些东西。这里主要是参考微信公众号“Py学习笔记”大佬去进行操作。
流程
1、参考文档去进行接线,安装驱动
安装相关依赖包
apt install python3-libgpiod
sudo pip3 install Adafruit-Blinka
sudo pip3 install adafruit-circuitpython-ssd1306
3、写python代码
这里直接抄的参考文档的。就不多说了。
import time
import subprocess
from board import *
import busio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
i2c = busio.I2C(I2C2_SCL, I2C2_SDA)
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
# 清屏
disp.fill(0)
disp.show()
width = disp.width
height = disp.height
# 单色位图
image = Image.new("1", (width, height))
# 定义绘图对象
draw = ImageDraw.Draw(image)
# 绘制一个黑色填充的矩形以清屏
draw.rectangle((0, 0, width, height), outline=0, fill=0)
# 定义一些常量
padding = -2
top = padding
bottom = height - padding
x = 0
# 定义字体
font = ImageFont.load_default()
while True:
draw.rectangle((0, 0, width, height), outline=0, fill=0)
# 调用命令显示IP、CPU、内存、存储等信息
cmd = "hostname -I | cut -d' ' -f1"
IP = subprocess.check_output(cmd, shell=True).decode("utf-8")
cmd = 'cut -f 1 -d " " /proc/loadavg'
CPU = subprocess.check_output(cmd, shell=True).decode("utf-8")
cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%s MB %.2f%%\", $3,$2,$3*100/$2 }'"
MemUsage = subprocess.check_output(cmd, shell=True).decode("utf-8")
cmd = 'df -h | awk \'$NF=="/"{printf "Disk: %d/%d GB %s", $3,$2,$5}\''
Disk = subprocess.check_output(cmd, shell=True).decode("utf-8")
draw.text((x, top + 0), "IP: " + IP, font=font, fill=255)
draw.text((x, top + 8), "CPU: " + CPU, font=font, fill=255)
draw.text((x, top + 16), MemUsage, font=font, fill=255)
draw.text((x, top + 25), Disk, font=font, fill=255)
# 显示信息
disp.image(image)
disp.show()
time.sleep(0.1)
2、修改代码、安装依赖包
直接运行这里会有报错,原因是machine这个包是micropython才有的,咱们使用的标准的python(Cpython),没有这个模块。
参考文档去修改busio.py文件。
使用from adafruit_blinka.microcontroller.generic_linux.i2c import (去替换from adafruit_blinka.microcontroller.generic_micropython.i2c import (就ok。
操作oled的demo代码中使用了PIL,需要安装pillow包
- sudo pip3 install pillow
也可以安装iic的工具去检查一下iic的连接情况
- sudo apt install i2c-tools
- sudo i2cdetect -y 2
看起来检查出来了iic设备0.0(我其实不太懂这个工具的原理,以后需要再研究。)
运行效果
其他
这里用top -p查看这个python驱动oled的进程,cpu使用率还挺高的,那感觉用这种方式去做监控比较划不来,或者更新调低一点0.0