OLED Display am RaspberryPi 4

Dieser Beitrag behandelt die Anbindung eines 0,96″ OLED LCD Display an einem RaspberryPi 4 z.b. als System Monitor.

1. System auf neuen Stand bringen:

Als erstes müsst Ihr den Raspberry bzw. das Raspberry Pi OS updaten mit:

sudo apt-get update
sudo apt-get upgrade
sudo reboot

Nach einem Neustart müsst Ihr in den Einstellungen die I2C Schnittstelle aktivieren. Dazu geht ihr mit

sudo raspi-config

in die Einstellungen, dann wählt Ihr den Punkt 3 – Interface Options aus, geht dann auf Punkt P5 – I2C und bestätigt die Frage: Would you like the ARM I2C interface to be enabled? mit YES. Dann könnt Ihr mit Finish die Einstellungen verlassen.

2. Treiber / Libaries installieren:

Nun müsst Ihr noch einige Libaries installieren, evtl. sind diese schon installiert.

sudo apt install -y python3-dev
sudo apt install -y python3-pil
sudo apt install -y python3-pip
sudo apt install -y python3-setuptools
sudo apt install -y python3-rpi.gpio
sudo apt install -y i2c-tools

Dann könnt Ihr den RaspberryPi herunterfahren und das Display anschließen.

3. Display anschließen:

Ich nutze hier ein 0,96″ OLED Display I2C SSD1306 128x64Pixel.

Dieses hat einen GND, VCC, SCL & SDA Pin die dann einfach an den RaspberryPi angeschlossen werden. Ich habe den Ground an PIN6, VCC an PIN1, SCL an PIN5 & SDA an PIN3 angeschlossen. Ihr könnt aber bei GND und VCC frei wählen es ist auch egal ob 3.3V oder 5V.

Nachdem alles angeschlossen ist könnt Ihr den Pi starten und mit folgenden Befehl überprüfen ob das Display erkannt wurde:

i2cdetect -y 1

Ihr solltet dann diese Ausgabe bekommen.

Da das Display erkannt wurde könnt Ihr mit der Installation der Libary beginnen. Dazu muss gesagt werden dass es hier zwei verschiedene Libaries gibt einmal eine für den RaspberryPi 3 und einmal eine für den RaspberryPi 4 wobei wir hier jetzt nur den Pi 4 behandeln.

4. SSD1306 Python Libary installieren:

Dazu benutzen wir die Python Libary SSD1306:

sudo pip3 install adafruit-circuitpython-ssd1306

Wie gesagt es gibt hier auch noch eine andere Variante mit dem “alten” Adafruit Script/Libary diese ergänze ich vielleicht noch.

5. System Monitor Script erstellen:

Nachdem jetzt die SSD1306 Libary installiert ist können wir ein Python Script ablegen. Dieses lege ich in der Location /home/pi ab.

Das Script könnt Ihr auch manuell erstellen mit:

sudo nano /home/pi/stats.py

Dann fügt Ihr folgende Zeilen ein:

# SPDX-FileCopyrightText: 2017 Tony DiCola for Adafruit Industries
# SPDX-FileCopyrightText: 2017 James DeVito for Adafruit Industries
# SPDX-License-Identifier: MIT

# This example is for use on (Linux) computers that are using CPython with
# Adafruit Blinka to support CircuitPython libraries. CircuitPython does
# not support PIL/pillow (python imaging library)!

import time
import subprocess

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


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

# Create the SSD1306 OLED class.
# The first two parameters are the pixel width and pixel height.  Change these
# to the right size for your display!
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)

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

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

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

# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height - padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0


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

# Alternatively load a TTF font.  Make sure the .ttf font file is in the
# same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
# font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 9)

while True:

    # Draw a black filled box to clear the image.
    draw.rectangle((0, 0, width, height), outline=0, fill=0)

    # Shell scripts for system monitoring from here:
    # https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load
    cmd = "hostname -I | cut -d\' \' -f1"
    #cmd = "hostname -I |cut -f 2 -d ' '"
    IP = subprocess.check_output(cmd, shell = True )
    cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
    CPU = subprocess.check_output(cmd, shell = True )
    cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'"
    MemUsage = subprocess.check_output(cmd, shell = True )
    cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'"
    Disk = subprocess.check_output(cmd, shell = True )
    cmd = "vcgencmd measure_temp |cut -f 2 -d '='"
    temp = subprocess.check_output(cmd, shell = True )

    #cmd = "hostname -I | cut -d' ' -f1"
    #IP = subprocess.check_output(cmd, shell=True).decode("utf-8")
    #cmd = 'cut -f 1 -d " " /proc/loadavg'
    #CPU = subprocess.check_output(cmd, shell=True).decode("utf-8")
    #cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%s MB  %.2f%%\", $3,$2,$3*100/$2 }'"
    #MemUsage = subprocess.check_output(cmd, shell=True).decode("utf-8")
    #cmd = 'df -h | awk \'$NF=="/"{printf "Disk: %d/%d GB  %s", $3,$2,$5}\''
    #Disk = subprocess.check_output(cmd, shell=True).decode("utf-8")

    # Write four lines of text.
    draw.text((x, top),  "IP: " + str(IP,'utf-8'), font=font, fill=255)
    draw.text((x, top+8),  str(CPU,'utf-8') + " " + str(temp,'utf-8') , font=font, fill=255)
    draw.text((x, top+16), str(MemUsage,'utf-8'), font=font, fill=255)
    draw.text((x, top+25), str(Disk,'utf-8'), font=font, fill=255)
    #draw.text((x, top),       "IP: " + str(IP),  font=font, fill=255)
    #draw.text((x, top+8),     str(CPU), font=font, fill=255)
    #draw.text((x, top+16),    str(MemUsage),  font=font, fill=255)
    #draw.text((x, top+25),    str(Disk),  font=font, fill=255)


    #draw.text((x, top + 0), "IP: " + IP, font=font, fill=255)
    #draw.text((x, top + 8), "CPU load: " + CPU, font=font, fill=255)
    #draw.text((x, top + 16), MemUsage, font=font, fill=255)
    #draw.text((x, top + 25), Disk, font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.show()
    time.sleep(0.1)

Um das ganze jetzt zu starten müsst Ihr nur noch diesen Befehl eingeben:

sudo python3 stats.py

Dann sollte auf dem Display ein System Monitor ausgegeben werden.

Mit STRG C beendet Ihr die Anzeige.

6. Zum automatischen Start hinzufügen:

Natürlich wollt Ihr warsch. das ganze automatisch starten. Dazu müssen wir in der rc.local Datei eine Zeile ergänzen. Dazu:

sudo nano /etc/rc.local

dann fügt Ihr vor dem exit 0 diese Zeile hinzu:

sudo python3 /home/pi/stats.py &

Speichert die Datei und geht auf Exit.

Jetzt könnt Ihr den RaspberryPi neu starten und das Display startet nach ein paar Sekunden eigenständig.

RaspberryPi 3 Methode:

Wie schon oben erwähnt ist die Installation mit einem Raspberry Pi 3 ein bisschen anders. Dazu befolgt die Punkte bist zu dem Punkt 4. An dieser Stelle müssen wir ein anders Script bzw. eine andere Libary verwenden.

Dazu gebt ihr dann folgenden Befehl ein um zu überprüfen ob git installiert ist:

sudo apt install -y git

Dann klont Ihr euch die Adafruit Libary von GitHub mit

git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git

Nach dem Download geht ihr dann in das neue Verzeichnis mit:

cd Adafruit_Python_SSD1306

und installiert dann das Script.

sudo python3 setup.py install

Jetzt könnt ihr mit

cd /home/pi/Adafruit_Python_SSD1306/examples

in den Ordner der Beispiele springen und dort einige Beispiele laufen lassen. Mit dir könnt Ihr euch die Beispiel Dateien anzeigen lassen. Wenn Ihr jetzt z.b diese Zeile ausführt… bekommt Ihr versch. Formen am Display angezeigt.

sudo python3 shapes.py

Jetzt könnt Ihr wieder diese stats.py erstellen mit:

sudo nano /home/pi/stats.py

Und fügt dann diesen Inhalt ein:

# Copyright (c) 2017 Adafruit Industries
# Author: Tony DiCola & James DeVito
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import subprocess

# Raspberry Pi pin configuration:
RST = None     # on the PiOLED this pin isnt used
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# Beaglebone Black pin configuration:
# RST = 'P9_12'
# Note the following are only used with SPI:
# DC = 'P9_15'
# SPI_PORT = 1
# SPI_DEVICE = 0

# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

# 128x64 display with hardware I2C:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

# Note you can change the I2C address by passing an i2c_address parameter like:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)

# Alternatively you can specify an explicit I2C bus number, for example
# with the 128x32 display you would use:
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2)

# 128x32 display with hardware SPI:
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

# 128x64 display with hardware SPI:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

# Alternatively you can specify a software SPI implementation by providing
# digital GPIO pin numbers for all the required display pins.  For example
# on a Raspberry Pi with the 128x32 display you might use:
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, sclk=18, din=25, cs=22)

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

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

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

# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0


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

# Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
# font = ImageFont.truetype('Minecraftia.ttf', 8)

while True:

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load
    cmd = "hostname -I | cut -d\' \' -f1"
    #cmd = "hostname -I |cut -f 2 -d ' '"
    IP = subprocess.check_output(cmd, shell = True )
    cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
    CPU = subprocess.check_output(cmd, shell = True )
    cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'"
    MemUsage = subprocess.check_output(cmd, shell = True )
    cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'"
    Disk = subprocess.check_output(cmd, shell = True )
    cmd = "vcgencmd measure_temp |cut -f 2 -d '='"
    temp = subprocess.check_output(cmd, shell = True )

    # Write two lines of text.

    draw.text((x, top),  "IP: " + str(IP,'utf-8'), font=font, fill=255)
    draw.text((x, top+8),  str(CPU,'utf-8') + " " + str(temp,'utf-8') , font=font, fill=255)
    draw.text((x, top+16), str(MemUsage,'utf-8'), font=font, fill=255)
    draw.text((x, top+25), str(Disk,'utf-8'), font=font, fill=255)
    #draw.text((x, top),       "IP: " + str(IP),  font=font, fill=255)
    #draw.text((x, top+8),     str(CPU), font=font, fill=255)
    #draw.text((x, top+16),    str(MemUsage),  font=font, fill=255)
    #draw.text((x, top+25),    str(Disk),  font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()
    time.sleep(.1)

Dann könnt Ihr oben mit Punkt 6. fortfahren.

4 Gedanken zu “OLED Display am RaspberryPi 4

  1. Wie muss ich diese Zeile abändern damit ich anstelle vom Root einen speziefischen mount Punkt angezeigt bekomme ? In Meinem Fall möchte ich /dev/sda5 anzeigen ?

    cmd = “df -h | awk ‘$NF==\”/\”{printf \”Disk: %d/%dGB %s\”, $3,$2,$5}'”

  2. Hallo,
    ich experimentiere jetzt schon seit einiger Zeit mit diversen OLEDs herum.
    Zwei davon habe ich von SPI auf I2C umgebaut, augenscheinlich basieren sie aber leider auf dem SH1106, ich habe immer lediglich eine Pixelsuppe erhalten. Diverse andere Anleitungen haben auch nicht zum Erfolg geführt.
    Jetzt habe ich noch ein drittes Display, leider auch mit SPI-Interface aber zumindest angeblich mit SSD1306.

    Gibt es eine Möglichkeit den Typen des Chips auszulesen?
    Was muss am Skript geändert werden, um die SPI-Schnittstelle zu nutzen?

    Danke
    Martin

  3. Hallo Das hat super geklappt, nur stehen bei mir alle Anzeigen auf dem Kopf. Gibt es eine möglichkeit das display zu drehen? Das wäre der Hammer vielen Dank.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert