We use an LED toggle with a button to turn an LED on or off by pressing a button. It helps us control lights or signals easily.
LED toggle with button in Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) LED_PIN = 18 BUTTON_PIN = 17 GPIO.setup(LED_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) led_state = False while True: button_state = GPIO.input(BUTTON_PIN) if button_state == GPIO.LOW: led_state = not led_state GPIO.output(LED_PIN, led_state) time.sleep(0.3) # debounce delay
GPIO.BCM means we use the Broadcom pin numbering on the Raspberry Pi.
Pull-up resistor means the button input reads HIGH when not pressed, LOW when pressed.
GPIO.setup(LED_PIN, GPIO.OUT) GPIO.output(LED_PIN, True) # Turn LED on GPIO.output(LED_PIN, False) # Turn LED off
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) button_state = GPIO.input(BUTTON_PIN) if button_state == GPIO.LOW: print('Button pressed')
This program waits for you to press the button. Each press switches the LED on or off. It also prints the LED state to the screen. When you stop the program, it cleans up the pins safely.
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) LED_PIN = 18 BUTTON_PIN = 17 GPIO.setup(LED_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) led_state = False print('Press the button to toggle the LED. Press Ctrl+C to exit.') try: while True: button_state = GPIO.input(BUTTON_PIN) if button_state == GPIO.LOW: led_state = not led_state GPIO.output(LED_PIN, led_state) print(f"LED is now {'ON' if led_state else 'OFF'}") time.sleep(0.3) # debounce delay except KeyboardInterrupt: print('\nExiting program.') finally: GPIO.output(LED_PIN, False) GPIO.cleanup()
Use a small delay after detecting a button press to avoid reading the same press multiple times (debounce).
Always clean up GPIO pins at the end to avoid warnings or errors next time you run the program.
You can control an LED by reading a button press on Raspberry Pi.
Use GPIO pins with proper setup for input (button) and output (LED).
Toggle the LED state each time the button is pressed, with a small delay to avoid errors.