Raspberry 4B 驱动 OLED

762 阅读2分钟

本文介绍在 Raspberry Pi 4B 上驱动 OLED 显示屏,并居中显示“Hello World”。 使用 I2C 接口的128x64 像素 OLED 屏幕(如 SSD1306 驱动的 128x64 像素 OLED)。

准备工作

所需材料

  • Raspberry Pi 4 Model B
  • SSD1306 I2C OLED 屏(128x64 像素)
  • 杜邦线4根

接线图

I2C

  • Data: (GPIO2);
  • Clock (GPIO3)

将 OLED 屏幕的引脚与 Raspberry Pi 连接:

  • VCC 接 Raspberry Pi 的 3.3V 引脚(1 号引脚)
  • GND 接 Raspberry Pi 的 GND 引脚(6 号引脚)
  • SCL 接 Raspberry Pi 的 SCL 引脚(5 号引脚,GPIO 3)
  • SDA 接 Raspberry Pi 的 SDA 引脚(3 号引脚,GPIO 2)

image.png

安装必要的库

在 Raspberry Pi 上安装驱动 OLED 屏幕所需的 Python 库。我们将使用 Adafruit_CircuitPython_SSD1306 库。

sudo apt update 
sudo apt install -y python3-pip python3-dev i2c-tools 
sudo pip3 install adafruit-circuitpython-ssd1306 
sudo pip3 install pillow

启用 I2C 接口

启用I2C 接口有2种方式,选择任意一种方式即可:

开启方法1:

1.打开 Raspberry Pi 的配置工具:

sudo raspi-config

2.选择 Interface Options,然后选择 I2C 并启用它。 3.重新启动 Raspberry Pi:

sudo reboot

开启方法2:

直接使用命令行开启:

sudo raspi-config nonint do_i2c 0

代码

1.安装 vim 工具,用以编写代码。

sudo apt install vim

生成文件,写入代码:

vim oled_hello_world.py

以下 Python 代码会在 OLED 屏幕上居中显示“Hello World”:

import board
import busio
import adafruit_ssd1306
from PIL import Image, ImageDraw, ImageFont

# OLED display size
WIDTH = 128
HEIGHT = 64

# Create the I2C interface.
i2c = busio.I2C(board.SCL, board.SDA)

# Create the SSD1306 OLED class.
# The first two parameters are the pixel width and pixel height. Change these if you have a different size display.
oled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c)

# 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", (WIDTH, HEIGHT))

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

# Load default font.
font = ImageFont.load_default()

# Define text to display
text = "Hello World"

# Get text bounding box
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]

# Calculate x and y coordinates to center the text
x = (WIDTH - text_width) // 2
y = (HEIGHT - text_height) // 2

# Draw the text
draw.text((x, y), text, font=font, fill=255)

# Display image
oled.image(image)
oled.show()

运行代码

将上述代码保存为 oled_hello_world.py 文件,并使用以下命令运行:

python3 oled_hello_world.py

这段代码将会在 OLED 屏幕上居中显示“Hello World”。

image.png

总结

通过以上步骤,你已经成功地在 Raspberry Pi 4 Model B 上驱动 OLED 屏幕,并居中显示“Hello World”。这个项目不仅介绍了基本的硬件连接,还涵盖了使用 Python 编写控制代码的全过程。你可以在此基础上进行更多的显示和控制实验。