0
0
Raspberry Piprogramming~7 mins

LED toggle with button in Raspberry Pi

Choose your learning style9 modes available
Introduction

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.

You want to turn a light on or off with a simple press.
You are making a small project that needs a switch to control an LED.
You want to learn how buttons and LEDs work together on a Raspberry Pi.
You want to practice reading button presses and controlling outputs.
Syntax
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.

Examples
This shows how to set up an LED pin and turn it on or off.
Raspberry Pi
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.output(LED_PIN, True)  # Turn LED on
GPIO.output(LED_PIN, False) # Turn LED off
This shows how to set up a button pin with a pull-up resistor and check if it is pressed.
Raspberry Pi
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')
Sample Program

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.

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

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()
OutputSuccess
Important Notes

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.

Summary

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.