ラズベリーパイと有機ELのSSD1306を用いて

作ったデジタル時計のプログラムです。画像の出力にはSSD1306とPILのライブラリ、時刻取得にはdatetimeを利用しています。

 

import board
import digitalio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
import datetime
import time


# Define the Reset Pin
oled_reset = digitalio.DigitalInOut(board.D4)

# Change these
# to the right size for your display!
WIDTH = 128
#HEIGHT = 32  # Change to 64 if needed
HEIGHT = 64  # Change to 64 if needed

# Use for I2C.
i2c = board.I2C()
oled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c, addr=0x3C, reset=oled_reset)


# Clear display.
oled.fill(0)
oled.show()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
image = Image.new("1", (oled.width, oled.height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a white background
draw.rectangle((0, 0, oled.width, oled.height), outline=0, fill=0)

#  font.
font = ImageFont.truetype('FreeSans.ttf',25)

# Draw Some Text
while True:
    today = datetime.datetime.now()
    text = today.strftime('%H:%M:%S')
    (font_width, font_height) = font.getsize(text)
    draw.text(
        (oled.width // 2 - font_width // 2, oled.height // 2 - font_height // 2),
        text,
        font=font,
        fill=255,
    )

    #Display image
    oled.image(image)
    oled.show()
    time.sleep(0.1)
    draw.rectangle((0, 0, oled.width, oled.height), outline=0, fill=0)