Skip to content

Instantly share code, notes, and snippets.

@Kaurin
Created February 2, 2024 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kaurin/eefe0a556aa7dfd22b0fe0d2ee991778 to your computer and use it in GitHub Desktop.
Save Kaurin/eefe0a556aa7dfd22b0fe0d2ee991778 to your computer and use it in GitHub Desktop.

Certainly! Here's a further optimized version of the code:

"""
Sense Hat CPU LED Matrix monitor.

Author: M. Manojlovic (synchromatik@gmail.com)

This script uses the Sense HAT and displays CPU load information on the LED matrix.
"""

from sense_hat import SenseHat
from scipy.interpolate import interp1d
import time
import psutil
import numpy as np 

sense = SenseHat()

def constructArray(cpuLoad):
    """
    Constructs an array representing the LED matrix configuration based on CPU load.

    Parameters:
    - cpuLoad (float): The CPU load value (percentage).

    Returns:
    - np.ndarray: An array representing the LED matrix configuration.
    """
    return np.clip(np.arange(1, min(cpuLoad + 1, 9)), 0, 8)

def arrayToColor(arr):
    """
    Converts an array of numbers to a list of RGB colors.

    Parameters:
    - arr (list): List of numbers.

    Returns:
    - list: List of RGB tuples corresponding to the input numbers.
    """
    color_map = {
        0: (60, 180, 75),   # Green
        1: (255, 255, 0),   # Yellow
        2: (255, 140, 0),   # Orange
        3: (255, 0, 0)      # Red
    }
    return [color_map.get(number, (0, 0, 0)) for number in arr]

print('Script running, check LEDs')

while True:
    percorelinear = interp1d([0, 100], [0, 8])(psutil.cpu_percent(percpu=True)).round(0).tolist() 
    load = arrayToColor(np.concatenate([constructArray(i) for i in percorelinear]))
    sense.set_pixels(load * 2)
    time.sleep(1)

Optimizations made:

  1. Used min(cpuLoad + 1, 9) in constructArray to avoid creating arrays larger than the LED matrix size (8).
  2. Created a color_map dictionary to map numbers to RGB tuples in arrayToColor.
  3. Simplified the color selection by directly using color_map.get in the list comprehension.
  4. Removed unnecessary comments and further improved formatting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment