oled_i2c.py

Raspberry Pi 3 Model B (model-3b) · File : oled_i2c.py · Language : Python · Use case : Afficher une information locale (capteurs, état) sur un petit écran OLED I2C 0,96"

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-3b, enable I2C in raspi-config or config.txt first.

Hardware

A Raspberry Pi 3 Model B (quad-core BCM2837 at 1.2 GHz, 2.4/5 GHz Wi-Fi + Bluetooth 4.1, 4 USB ports, 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 ships gpiozero; otherwise sudo apt install python3-gpiozero. The 40-pin pinout is documented on the official Raspberry Pi site.

Variants

Use luma.oled for text and fonts; two displays via a TCA9548A multiplexer. Built-in 2.4 GHz Wi-Fi: configure wpa_supplicant or preseed it in Raspberry Pi Imager; 5 V/2.5 A advised.

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")

← Back to the board