进阶篇——树莓派OLED模块的使用 大量例程详解_oled例程_玩转智能机器人的博客-CSDN博客
官方教程
使用BDF需要知道字体的大小FONT_PIXEL ;打开BDF查看
luma.oled
库:github luma.examples-master
常用导入库
import sys
import random
from pathlib import Path
from PIL import ImageFont, Image, ImageSequence
from luma.core.render import canvas
from luma.core.sprite_system import framerate_regulator
常用结构
serial = spi(device=0, port=0)
device = ssd1306(serial)
with canvas(device) as draw:
draw.text((left, top), text=code, font=font, fill="white") //文字
使用函数
显示文字 draw.text()
draw.text(坐标位置,文本,字体,颜色)
font = ImageFont.truetype(font_path, size)
draw.text((left, top), text=code, font=font, fill="white")
示例代码:font_awesome.py
显示图像 display
//显示gif
def main():
regulator = framerate_regulator(fps=10)
img_path = str(Path(__file__).resolve().parent.joinpath('images', 'banana.gif'))
banana = Image.open(img_path)
size = [min(*device.size)] * 2
posn = ((device.width - size[0]) // 2, device.height - size[1])
while True:
for frame in ImageSequence.Iterator(banana):
with regulator:
background = Image.new("RGB", device.size, "white")
background.paste(frame.resize(size, resample=Image.LANCZOS), posn)
device.display(background.convert(device.mode))
示例代码:animated.py
画框,画圆ellipse, rectangle
canvas.ellipse((坐标位置sx,sy,ex,ey), fill=self._color)
canvas.rectangle(device.bounding_box, outline="white", fill="black")
draw.rectangle((x2, y2, x2 + 1, y2 + 1), fill=(0,255,0))
class Ball(object):
def __init__(self, w, h, radius, color):
self._w = w
self._h = h
self._radius = radius
self._color = color
self._x_speed = (random.random() - 0.5) * 10
self._y_speed = (random.random() - 0.5) * 10
self._x_pos = self._w / 2.0
self._y_pos = self._h / 2.0
def update_pos(self):
if self._x_pos + self._radius > self._w:
self._x_speed = -abs(self._x_speed)
elif self._x_pos - self._radius < 0.0:
self._x_speed = abs(self._x_speed)
if self._y_pos + self._radius > self._h:
self._y_speed = -abs(self._y_speed)
elif self._y_pos - self._radius < 0.0:
self._y_speed = abs(self._y_speed)
self._x_pos += self._x_speed
self._y_pos += self._y_speed
def draw(self, canvas):
canvas.ellipse((self._x_pos - self._radius, self._y_pos - self._radius,
self._x_pos + self._radius, self._y_pos + self._radius), fill=self._color)
def main(num_iterations=sys.maxsize):
colors = ["red", "orange", "yellow", "green", "blue", "magenta"]
balls = [Ball(device.width, device.height, i * 1.5, colors[i % 6]) for i in range(10)]
frame_count = 0
fps = ""
canvas = luma.core.render.canvas(device)
regulator = framerate_regulator(fps=0)
while num_iterations > 0:
with regulator:
num_iterations -= 1
frame_count += 1
with canvas as c:
c.rectangle(device.bounding_box, outline="white", fill="black")
for b in balls:
b.update_pos()
b.draw(c)
c.text((2, 0), fps, fill="white")
if frame_count % 20 == 0:
fps = "FPS: {0:0.3f}".format(regulator.effective_FPS())
示例:bounce.py
clock.py
line 画线
draw.line((cx, cy, cx + hrs[0], cy + hrs[1]), fill="white")
carousel.py
from luma.core.sprite_system import framerate_regulator
width
widget_width = device.width // 2
height
widget_height = device.height
rotate
device.rotate
bitmap 显示图像
logo = Image.open(img_path)
draw.bitmap((20, 0), logo, fill="white")
crawl.py
画线,画图操作 demo.py
import time
import datetime
from demo_opts import get_device
from luma.core.render import canvas
def primitives(device, draw):
# Draw some shapes
# First define some constants to allow easy resizing of shapes
padding = 2
shape_width = 20
top = padding
bottom = device.height - padding - 1
# Move left to right keeping track of the current x position for drawing shapes
x = padding
# Draw an ellipse 画椭圆
draw.ellipse((x, top, x + shape_width, bottom), outline="red", fill="black")
x += shape_width + padding
# Draw a rectangle 画矩形
draw.rectangle((x, top, x + shape_width, bottom), outline="blue", fill="black")
x += shape_width + padding
# Draw a triangle 三角形
draw.polygon([(x, bottom), (x + shape_width / 2, top), (x + shape_width, bottom)], outline="green", fill="black")
x += shape_width + padding
# Draw an X 画线
draw.line((x, bottom, x + shape_width, top), fill="yellow")
draw.line((x, top, x + shape_width, bottom), fill="yellow")
x += shape_width + padding
# Write two lines of text
left, t, right, bottom = draw.textbbox((0, 0), 'World!')
w, h = right - left, bottom - t
x = device.width - padding - w
draw.rectangle((x, top + 4, x + w, top + h), fill="black")
draw.rectangle((x, top + 16, x + w, top + 16 + h), fill="black")
draw.text((device.width - padding - w, top + 4), 'Hello', fill="cyan")
draw.text((device.width - padding - w, top + 16), 'World!', fill="purple")
# Draw a rectangle of the same size of screen
draw.rectangle(device.bounding_box, outline="white")
def main():
device = get_device()
print("Testing basic canvas graphics...")
for _ in range(2):
with canvas(device) as draw:
primitives(device, draw)
time.sleep(5)
print("Testing contrast (dim/bright cycles)...")
for _ in range(5):
for level in range(255, -1, -10):
device.contrast(level)
time.sleep(0.1)
time.sleep(0.5)
for level in range(0, 255, 10):
device.contrast(level)
time.sleep(0.1)
time.sleep(1)
print("Testing display ON/OFF...开关显示器")
for _ in range(5):
time.sleep(0.5)
device.hide()
time.sleep(0.5)
device.show()
print("Testing clear display..清屏.")
time.sleep(2)
device.clear()
print("Testing screen updates...")
time.sleep(2)
for x in range(40):
with canvas(device) as draw:
now = datetime.datetime.now()
draw.text((x, 4), str(now.date()), fill="white")
draw.text((10, 16), str(now.time()), fill="white")
time.sleep(0.1)
import time
from demo_opts import get_device
from luma.core.render import canvas
from luma.core import legacy
def main():
MY_CUSTOM_BITMAP_FONT = [
[
0x00, 0x3e, 0x08, 0x3e, 0x00, 0x3e, 0x2a, 0x22,
0x00, 0x3e, 0x20, 0x20, 0x00, 0x3e, 0x0a, 0x0e
]
]
device = get_device()
with canvas(device) as draw:
# Note that "\0" is the zero-th character in the font (i.e the only one)
legacy.text(draw, (0, 0), "\0", fill="white", font=MY_CUSTOM_BITMAP_FONT)
time.sleep(5)
dotmatrixtool.py
字体显示font_awesome.py
画点:game_of_life.py
draw.point((left, top), fill="white")
Image使用 greyscale.py
from PIL import Image
img_path = str(Path(__file__).resolve().parent.joinpath('images', 'balloon.png'))
balloon = Image.open(img_path) \
.transform(device.size, Image.AFFINE, (1, 0, 0, 0, 1, 0), Image.BILINEAR) \
.convert("L") \
.convert(device.mode)
while True:
# Image display
device.display(balloon)
device.display(balloon)
time.sleep(5)
图像合成 image_composition.py
invaders.py
jetset_willy.py
pi_logo.py 图像合成
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2020 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK
"""
Display the Raspberry Pi logo (loads image as .png).
"""
from pathlib import Path
from demo_opts import get_device
from PIL import Image
def main():
img_path = str(Path(__file__).resolve().parent.joinpath('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:
device = get_device()
main()
except KeyboardInterrupt:
pass
摄像头与显示 picamera_photo.py
picamera_video.py
显示气候weather.py
from demo_opts import get_device
from luma.core.legacy import show_message
from luma.core.legacy.font import proportional, SINCLAIR_FONT
try:
import feedparser
except ImportError:
print("The feedparser library was not found. Run 'sudo -H pip install feedparser' to install it.")
sys.exit()
def main(num_iterations=sys.maxsize):
# Go to https://www.bbc.com/weather and enter your town/city into
# the 'Find a forecast' box. Then when you click through, substitute
# the location_id below
location_id = 2647428
weather_rss_url = f"https://weather-broker-cdn.api.bbci.co.uk/en/forecast/rss/3day/{location_id}"
device = get_device()
while num_iterations > 0:
num_iterations -= 1
feed = feedparser.parse(weather_rss_url)
msg = feed["feed"]["title"]
show_message(device, msg, fill="white", font=proportional(SINCLAIR_FONT))
time.sleep(1)
for items in feed["items"]:
msg = items["title"]
msg = msg.split(",")[0]
show_message(device, msg, fill="white", font=al)
time.sleep(1)
for msg in items["description"].split(","):
show_message(device, msg, fill="white", font=proportional(SINCLAIR_FONT))
time.sleep(1)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
显示欢迎界面welcome.py
draw.multiline_text((left, top), text=t, font=font, fill=color,
align="center", spacing=-2)