树莓派SSD1306 OLED屏幕驱动-I2C接口

Zss 发表于:

1.有的时候需要查看到ip相关等信息时,没有电脑上面的非常不方便,特别在控制小车启动时,是否正常等等,需要看某些信息

所以买了一个oled的显示屏,10快钱,感觉挺好的,最开始的时候线接错地方了一直没有驱动起来

四根线的显示屏,i2c接口

接线:

 

2.安装工具

sudo apt-get install -y i2c-tools

 

3.raspi-config 里打开I2C开关,执行检测

选项5中似乎是

 

4.检测

sudo i2cdetect -y 1

出现如下

5.安装对应库文件

sudo python -m pip install –upgrade pip setuptools wheel

sudo apt-get install python-pil python3-pil

sudo pip install Adafruit-SSD1306

 

6.拉取测试文件

git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git

其中包含设备信息的状态显示代码,不过ip不是刷新多个接口的地址,更换接口地址不发生变化,我自己改了一下,优先显示usb接口地址 其次wlan 再是eth0

import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import re
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import subprocess
from subprocess import PIPE,Popen

RST = None     # on the PiOLED this pin isnt used
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
disp.begin()

disp.clear()
disp.display()

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()

def get_ip():
    def ip(eth):
        try:
            cmd = 'ifconfig %s'%eth
            result = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE)
            ip = re.findall('inet\s{1,5}(.*)\s{1,5}netmask',str(result.stdout.read()))[0].strip()
            return ip
        except:
            return 'Wait'
                
    run_ip = ip('usb0')
    if '.' in run_ip:
        return run_ip
    else:
        run_ip = ip('wlan0')    
        if '.' in run_ip:
            return run_ip
        else:
            run_ip = ip('eth0')
            if '.' in run_ip:
                return run_ip
            else:
                return 'None'

while True:
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    #cmd = "hostname -I | cut -d\' \' -f1"
    #IP = subprocess.check_output(cmd, shell = True )
    IP = get_ip()
    cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
    CPU = subprocess.check_output(cmd, shell = True )
    cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'"
    MemUsage = subprocess.check_output(cmd, shell = True )
    cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'"
    Disk = subprocess.check_output(cmd, shell = True )

    # Write two lines of text.

    draw.text((x, top),       str("IP: ") + str(IP),  font=font, fill=255)
    draw.text((x, top+8),     str(CPU), font=font, fill=255)
    draw.text((x, top+16),    str(MemUsage),  font=font, fill=255)
    draw.text((x, top+25),    str(Disk),  font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()
    time.sleep(.1)

还有很多可以显示的图案

https://github.com/rm-hull/luma.examples