oled_i2c.py
The 128x64 SSD1306 OLED wires to the I2C bus (GPIO2/GPIO3, pins 3 and 5) and boots with a command sequence. The script brings the bus up, clears the framebuffer, then hands over. On the model-4b, enable I2C in raspi-config or config.txt first.
Hardware
A Raspberry Pi 4 Model B (quad-core BCM2711 at 1.5 GHz, USB-C 5 V/3 A, dual micro-HDMI, 5 GHz Wi-Fi, 40-pin GPIO). One 4-pin SSD1306 I2C OLED module, dupont wires.
Wiring
VCC to 3.3 V, GND to GND, SDA to GPIO2 (pin 3), SCL to GPIO3 (pin 5). The J8 40-pin header groups these pins at the corner.
How it works
smbus writes control byte 0x00 (command) or 0x40 (data) then payload bytes to address 0x3C; the sequence sets pump charge, contrast and scan.
Running it
Copy the script to the board (scp), then run it with python3 (or bash). Raspberry Pi OS Bookworm ships gpiozero; otherwise sudo apt install python3-gpiozero. Use a 5 V/3 A USB-C supply to avoid undervoltage throttling.
Variants
Use luma.oled for text and fonts; two displays via a TCA9548A multiplexer. Use the official 5 V/3 A USB-C supply: otherwise the USB 3 ports are throttled.
oled_i2c.py
# oled_i2c.py — affiche texte et courbe sur OLED SSD1306 en I2C.
# Deps: sudo apt install python3-smbus i2c-tools (activer i2c_arm)
import time
import smbus
ADDR = 0x3C
bus = smbus.SMBus(1)
def cmd(c):
bus.write_byte_data(ADDR, 0x00, c)
def data(buf):
bus.write_i2c_block_data(ADDR, 0x40, buf)
for c in [0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0x00, 0x40, 0x8D, 0x14,
0xA1, 0xC8, 0xDA, 0x12, 0x81, 0xFF, 0xD9, 0xF1, 0xDB, 0x40,
0xA4, 0xA6, 0xAF]:
cmd(c)
data([0xF0] * 1024) # efface le framebuffer 128x64
print("OLED initialise, i2cdetect -y 1 pour verifier")