LED and button projects help you learn how to control real things with your Raspberry Pi. They make hardware easy and fun to understand.
Why LED and button projects build hardware confidence in Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # LED pin GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin try: while True: button_state = GPIO.input(23) if button_state == GPIO.LOW: GPIO.output(18, GPIO.HIGH) # Turn LED on else: GPIO.output(18, GPIO.LOW) # Turn LED off time.sleep(0.1) finally: GPIO.cleanup()
Use GPIO.setmode(GPIO.BCM) to refer to pins by their Broadcom number.
Setup pins as input or output before using them.
GPIO.setup(18, GPIO.OUT) # Set pin 18 as output for LED
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set pin 23 as input with pull-up resistor for button
button_state = GPIO.input(23) if button_state == GPIO.LOW: GPIO.output(18, GPIO.HIGH) # Turn LED on
This program turns the LED on when the button is pressed and off when it is released. It prints the LED status to the screen.
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) LED_PIN = 18 BUTTON_PIN = 23 GPIO.setup(LED_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) print('Press the button to turn the LED on. Press Ctrl+C to stop.') try: while True: if GPIO.input(BUTTON_PIN) == GPIO.LOW: GPIO.output(LED_PIN, GPIO.HIGH) print('LED ON') else: GPIO.output(LED_PIN, GPIO.LOW) print('LED OFF') time.sleep(0.5) except KeyboardInterrupt: print('Program stopped by user.') finally: GPIO.cleanup()
Always clean up GPIO pins with GPIO.cleanup() to avoid warnings next time you run your program.
Use a pull-up or pull-down resistor to keep button input stable and avoid random signals.
Start with simple LED and button projects to build your confidence before trying complex hardware.
LED and button projects show how software controls hardware in a simple way.
They help you learn wiring, coding, and how inputs and outputs work together.
These projects build your confidence to explore more electronics with Raspberry Pi.