Raspberry Pi LEDs | CCC

This page contains code to control the Paspberry Pi 5 LEDs

Code to select and Blink One LED


import gpiod
from time import sleep

#Assign the varable 'chip' to the Raspberry Pi 5's board chip.
chip = gpiod.Chip('gpiochip4')

#Each LED needs to have these three lines of code.
#1) A varaible specifying which Pin will be used.
PIN_18 = 18
#2) A variable specifying which PIN will be used for the LED. I named the variable the color of the LED.
red = chip.get_line(PIN_18)
#3) Define how the PIN will be used: It will be an LED and the type will send current out when active using "red.set_value([0,1])" 0=off and 1=on.
red.request(consumer='LED',type=gpiod.LINE_REQ_DIR_OUT)

#This function will turn off all LEDs using [varable].set_value(0)
def all_off():
    #Suspend the program to make sure the LED has time to light up.
    sleep(.1)
    #Turn off the LEDs. Each LED needs to be set to 0 "off".
    red.set_value(0)

print("Press Ctrl + c to stop.")
pattern = input(f"Select a pattern: \n 1=Red Blink \n\n")

try:
    while True:
        #Red Blink
        if pattern == '1':
            print('Red Blink')
            red.set_value(1)
            sleep(1)
            all_off()
            sleep(1)

except KeyboardInterrupt:
    #Turn off any LEDs that may be lit.
    all_off()
    #Let the Raspberry Pi know the PINs are no longer being used. Each pin needs to be listed.
    red.release()
    #Free up the memory being used by the 'chip' variable.
    chip.close()