Skip to content

Instantly share code, notes, and snippets.

@Kaurin
Created February 2, 2024 20:28
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/b63af9239b9ce598b18a18669f997cc9 to your computer and use it in GitHub Desktop.
Save Kaurin/b63af9239b9ce598b18a18669f997cc9 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, cpuLoad + 1), 0, 8)[: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.
    """
    return [
        (60, 180, 75) if number <= 2 else
        (255, 255, 0) if number <= 4 else
        (255, 140, 0) if number <= 6 else
        (255, 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 np.clip to ensure that the array generated in constructArray does not exceed the LED matrix size (8).
  2. Removed unnecessary comments and simplified the code where possible.
  3. Combined the list comprehensions in arrayToColor to make the code more concise.
  4. Adjusted the concatenate call to directly concatenate the arrays generated in the list comprehension.
  5. Improved formatting and readability.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment