🌌

Raspberry Pi Pico WでOLED

に公開

概要

SSD1309のOLEDを使ってGemini Apiの返答を表示させてみました。
micropythonを使用して制御しています。

ピン配置

今回はSPIで通信したので以下のピンで接続しました。

ピン番号 機能/GPIO OLED
40 VBUS VCC
38 GND GND
25 GP19 DIN
24 GP18 CLK
22 GP17 CS
16 GP13 DC
17 GP12 RST

SSD1309ドライバ

SSD1309のドライバは下記のものを使用させていただきました。
https://github.com/rdagger/micropython-ssd1309

コード

Raspberry Pi Pico Wでのwifi接続と、Gemini apiへのリクエストを送る簡単なコードを実装しました。

main.py
from machine import Pin, SPI
from ssd1309 import Display
from xglcd_font import XglcdFont
import urequests
import ujson
import network
import time

CS = Pin(17)
CLK = Pin(18)
DIN =Pin(19)
DC = Pin(13)
RST = Pin(12)

LED = Pin('LED',Pin.OUT)
spi = SPI(id=0, baudrate=10000000, mosi=DIN, sck=CLK ,polarity=1, phase=1)

SSID = 'ZZZZ-ZZZZZ'
PW = 'XXXXXXX'

def connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(SSID, PW)
    while not wlan.isconnected():
        time.sleep(1)
    print('Connected to WiFi')
    print(wlan.ifconfig()[0])
    return wlan

def requests():
    url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=gemini_api_key'
    header = {'Content-Type': 'application/json'}
    contents = {"contents": [{"parts":[{"text": "short quote of the day"}]}]}
    response = urequests.post(url,data = ujson.dumps(contents).encode("utf-8"),headers=header)
    res = response.json()['candidates'][0]['content']['parts'][0]['text']
    print(res)
    return res

def wrap_text(s, width):
    return [s[i:i+width] for i in range(0, len(s), width)]

def draw_multiline_text(display, text, font, x=126, y=50, rotate=180):
    result = wrap_text(text, width=18)
    for i in range(len(result)):
        line = result[i]
        line_height = 10
        display.draw_text(x, y - i * line_height, line, font, rotate=rotate)
        
display = Display(spi, dc=DC, rst=RST, cs=CS)
bally = XglcdFont('fonts/Bally7x9.c',7,9)

wlan = connect()
res = str(requests())

display.clear()
display.clear_buffers()
draw_multiline_text(display,res,bally )

display.present()
print('Done.')

Discussion