filmov
tv
Toggle an LED with a Button on Raspberry Pi 5 using Python

Показать описание
In this video, I demonstrate how to control an LED using a button with Raspberry Pi 5 and Python. The program toggles the LED on and off each time the button is pressed, using the gpiozero library for easy GPIO handling.
🔹 Hardware Used: Raspberry Pi 5, LED, Push Button, Resistor, Jumper Wires
🔹 Software: Python, GPIO Zero Library
🔹 Code Overview: The script assigns a Button to GPIO 25 and an LED to GPIO 18. When the button is pressed, the LED toggles (on/off) using the toggle() function.
Code:
from gpiozero import Button, LED
from time import sleep
# Pin Definitions
SWITCH_PIN = 25 # Button input pin
LED_PIN = 18 # LED output pin
# Create Button and LED objects
button = Button(SWITCH_PIN)
led = LED(LED_PIN)
# Function to toggle LED state
def toggleLED():
# Attach the toggle function to the button press event
# Keep the program running
try:
while True:
sleep(0.1) # Small delay to allow the button press event to trigger
except KeyboardInterrupt:
print("Exiting program...")
🔹 Hardware Used: Raspberry Pi 5, LED, Push Button, Resistor, Jumper Wires
🔹 Software: Python, GPIO Zero Library
🔹 Code Overview: The script assigns a Button to GPIO 25 and an LED to GPIO 18. When the button is pressed, the LED toggles (on/off) using the toggle() function.
Code:
from gpiozero import Button, LED
from time import sleep
# Pin Definitions
SWITCH_PIN = 25 # Button input pin
LED_PIN = 18 # LED output pin
# Create Button and LED objects
button = Button(SWITCH_PIN)
led = LED(LED_PIN)
# Function to toggle LED state
def toggleLED():
# Attach the toggle function to the button press event
# Keep the program running
try:
while True:
sleep(0.1) # Small delay to allow the button press event to trigger
except KeyboardInterrupt:
print("Exiting program...")