MrGlasspoole
Posts: 9
Joined: Sat Dec 09, 2017 12:24 am

5110 LCD - code optimization, CPU usage

Thu May 24, 2018 5:42 pm

I never did much with Python and wonder if its normal that this small script uses 18% CPU on a Pi Zero.
I did remove the bars of CPU and RAM usage but that changed nothing.

Code: Select all

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from datetime import datetime
import locale
import psutil

import Adafruit_Nokia_LCD as LCD
import Adafruit_GPIO.SPI as SPI

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

locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
'de_DE.UTF-8'

def formatByte(b):
    if b < 1024:
        return str(b)
    if b < 1048576:
        return str(b / 1024) + "K"
    if b < 1073741824:
        return str(b / 1048576) + "M"
    return str(b / 1073741824) + "G"

def progressBar(draw, x, y, width, height, percent):
    fillWidth = width * percent
    draw.rectangle((x, y, x+width, y+height), outline=0, fill=255)
    draw.rectangle((x, y, x+fillWidth, y+height), outline=0, fill=0)

# Raspberry Pi hardware SPI config:
DC = 23
RST = 24
SPI_PORT = 0
SPI_DEVICE = 0

# Hardware SPI usage:
disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))

# Software SPI usage (defaults to bit-bang SPI interface):
#disp = LCD.PCD8544(DC, RST, SCLK, DIN, CS)

# Initialize library.
disp.begin(contrast=45)

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

while True:
    # Create blank image for drawing.
    # Make sure to create image with mode '1' for 1-bit color.
    image = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT))

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

    # Draw a white filled box to clear the image.
    draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline=255, fill=255)

    # Load a TTF font.
    font = ImageFont.truetype('/home/dietpi/python-scripts/upheavtt.ttf', 20)

    # Draw time.
    draw.text((0,0), time.strftime("%H:%M:%S"), font=font)

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

	# Draw CPU usage.
    draw.text((4,14), "CPU:", font=font)
    progressBar(draw, 29, 16, LCD.LCDWIDTH - 30, 6, psutil.cpu_percent() / 100.0)

	# Draw RAM usage.
    mem = psutil.virtual_memory()
    draw.text((4,22), "MEM:", font=font)
    progressBar(draw, 29, 24, LCD.LCDWIDTH - 30, 6, float(mem.used) / mem.total)

    # Draw date.
    draw.text((0,34), time.strftime("%a %d.%m.%Y"), font=font)

    # Display image.
    disp.image(image)
    disp.display()

    time.sleep(0.25)

Return to “Python”

Who is online

Users browsing this forum: Google [Bot], T-EGWZ34 and 9 guests