Projet

Général

Profil

Raspberry Pi - Jauge Incluedo » listenerLED.py

Thomas-Alexandre Moreau, 21/02/2025 10:19

 
import keyboard
import time
from rpi_ws281x import PixelStrip, Color

# LED strip configuration:
LED_MAX = 8
counter = 0
LED_PIN = 18 # GPIO pin connected to the pixels (GPIO 18 is PWM-capable)
LED_BRIGHTNESS = 100 # Maximum brightness (0-255)
LED_FREQ_HZ = 800000 # Frequency of the PWM signal
LED_DMA = 10 # DMA channel to use
LED_INVERT = False # True to invert the signal
LED_CHANNEL = 0 # Use GPIO 0 as the PWM channel

# Initialize the LED strip
strip = PixelStrip(LED_MAX, LED_PIN, freq_hz=LED_FREQ_HZ, dma=LED_DMA, invert=LED_INVERT, brightness=LED_BRIGHTNESS, channel=LED_CHANNEL)
strip.begin()

# Function to turn off all LEDs
def turn_off_all_leds(strip):
for i in range(strip.numPixels()):
strip.setPixelColor(i, Color(0, 0, 0)) # Set each LED to black (off)
strip.show() # Apply the changes

# Define the callback function to track key presses
def on_key_event(e):
global counter
if e.event_type == keyboard.KEY_DOWN:
if e.name == 'up': # You can change 'up' to any key you want to detect
if counter < LED_MAX:
counter += 1
print(f"The 'up' key was pressed! counter = {counter}")
color_wipe(strip, counter, Color(255, 0, 0)) # Red color for the LED

elif e.name == 'down':
if counter > 0:
counter -= 1
print(f"The 'down' key was pressed! counter = {counter}")
color_wipe(strip, counter, Color(255, 0, 0)) # Red color for the LED

def color_wipe(strip, curCount, color):
"""Fill the entire strip with a color."""
turn_off_all_leds(strip) # Turn off all LEDs first
time.sleep(0.2) # Add a slight delay to ensure the LEDs are off

# Now light up the LEDs based on the current counter
for i in range(curCount):
strip.setPixelColor(i, color) # Set the LED to the desired color
strip.show() # Update the LEDs
time.sleep(0.05) # Adding a slight delay to avoid erratic behavior

# Initialize with all LEDs off
turn_off_all_leds(strip) # Ensure all LEDs are off initially
strip.show() # Apply the changes

def main():
# Start listening for key events
keyboard.hook(on_key_event)

# Wait indefinitely so the listener stays active
keyboard.wait('esc') # The program will stop when the 'esc' key is pressed

if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("Exiting...")
strip._cleanup() # Clean up when the program exits
(1-1/2)