Python有兩個可以用的OLED庫
- Adafruit_Python_SSD1306庫—>只支持SSD1306
- Luma.oled庫—>支持SSD1306 / SSD1322 / SSD1325 / SSD1331 / SH1106
i2c接線
OLED引腳 | 樹莓派物理BOARD引腳 |
---|---|
VCC | 1號 |
GND | 6號 |
SCL | 5號 |
SDA | 3號 |
接好線后就是像一個L型的。
接線方式如下圖,按顏色對應:
開啟i2c功能
sudo apt-get install -y python-smbus
sudo apt-get install -y i2c-tools
sudo raspi-config
打開樹莓派配置選擇5 Interfacing Options。
選擇P5 I2C回車激活I2C。
按回車啟動就得了。
查看i2c地址
sudo i2cdetect -y 1
然后你能看到下面的地址,3c就是oled屏的i2c地址了,說明已經成功開啟i2c啦
– 安裝Luma.oled庫
終端輸入下面命令。
sudo apt-get install python-dev python-pip libfreetype6-dev libjpeg-dev
pip install --upgrade luma.oled
如果安裝Luma.oled庫時出現紅字錯誤,請繼續執行命令重試,那是因為網絡問題下載一個叫Pillow的庫不成功。注:如果你需要安裝Python3的Luma.oled庫的則按下面對應的Python3版本修改上面的命令進行安裝。
pip ⇒ pip3
python ⇒ python3
python-dev ⇒ python3-dev
python-pip ⇒ python3-pip
安裝好Luma.oled庫后新建文件命名為oled.py,復制粘貼下面代碼。參考這里使用說明
from luma.core.interface.serial import i2c, spi
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
# rev.1 users set port=0
# substitute spi(device=0, port=0) below if using that interface
serial = i2c(port=1, address=0x3C)
# substitute ssd1331(...) or sh1106(...) below if using that device
device = sh1106(serial)#這里改ssd1306, ssd1325, ssd1331, sh1106
with canvas(device) as draw:
draw.rectangle(device.bounding_box, outline="white", fill="black")
draw.text((30, 40), "Hello World", fill="white")
如果你的oled驅動芯片是其它型號找到device = sh1106(serial),把sh1106改成庫支持的其它型號。
樹莓派上用Python2打開oled.py運行就能看到下圖的Hello World。
能驅動成功后我們去下載Luma.oled的examples代碼。
然后是examples里面的例子怎么用呢?如果是非ssd1306芯片直接運行還是花屏的,因為那個examples的代碼需要修改。
下面以pi_logo.py為例參考上面那個Hello World的例子修改成自己OLED芯片型號的(文件放在在examples內)。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-17 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK
"""
Display the Raspberry Pi logo (loads image as .png).
"""
import os.path
from PIL import Image
from luma.core.interface.serial import i2c, spi
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
def main():
img_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'images', 'pi_logo.png'))
logo = Image.open(img_path).convert("RGBA")
fff = Image.new(logo.mode, logo.size, (255,) * 4)
background = Image.new("RGBA", device.size, "white")
posn = ((device.width - logo.width) // 2, 0)
while True:
for angle in range(0, 360, 2):
rot = logo.rotate(angle, resample=Image.BILINEAR)
img = Image.composite(rot, fff, rot)
background.paste(img, posn)
device.display(background.convert(device.mode))
if __name__ == "__main__":
try:
serial = i2c(port=1, address=0x3C)
device = sh1106(serial)
main()
except KeyboardInterrupt:
pass
Python運行上面的程序oled屏會出現一個能旋轉的樹莓派LOGO。
參考文章:
https://shumeipai.nxez.com/2017/09/13/solve-the-raspberry-pi-drive-oled-problem.html