top of page

Control an LED with a Button

Updated: Oct 11

We teach and learn by making !


At Haruki Robotics Lab, students learn how to combine electronics and coding to create real‑world effects. In this beginner‑friendly project, we use Python and the RPi.GPIO library to make an LED blink. This experiment introduces core skills in electronics, programming loops, and hardware control.


ree
ree
ree

Python Code

import RPi.GPIO as GPIO
import time
# Pin setup

LedPin = 17   # LED connected to GPIO17
BtnPin = 18   # Button connected to GPIO18

GPIO.setmode(GPIO.BCM)
GPIO.setup(LedPin, GPIO.OUT)
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

led_on = False
print("Press the button to toggle LED. Press Ctrl+C to quit.")

try:
    while True:
        button_state = GPIO.input(BtnPin)
        if button_state == GPIO.LOW:  # button pressed
            led_on = not led_on
            GPIO.output(LedPin, led_on)
            if led_on:
                print("LED ON")
            else:
                print("LED OFF")
            time.sleep(0.3)  # debounce delay
        time.sleep(0.05)  # small loop delay
except KeyboardInterrupt:

    pass

finally:
    GPIO.output(LedPin, GPIO.LOW)
    GPIO.cleanup()
    print("Program ended, GPIO cleaned up.")


How It Works

  • BtnPin = 18: defines GPIO 18 for the push‑button input.

  • GPIO.setup(BtnPin, GPIO.IN): sets the button pin as an input.

  • GPIO.add_event_detect(): listens for a falling edge — when the button is pressed — and runs the function swLed.

  • swLed(): toggles Led_status and updates the LED accordingly.

  • GPIO.output(LedPin, GPIO.HIGH): turns the LED off (since the circuit is active‑low).


Learning Goals

  • Understand how buttons work as input sensors.

  • Use callbacks and interrupts in Python to respond instantly to inputs.

  • Combine input (button) and output (LED) in a simple circuit.


Experiment Variations

  • Change the LED or button pins to explore different GPIO numbers.

  • Modify the callback function to make the LED flash each time the button is pressed.

  • Add multiple LEDs for a tiny light show controlled by one button.

  • Use GPIO.PWM to fade the brightness instead of turning it fully ON or OFF.


Troubleshooting Tips

  • Check that your button is wired correctly with one side to ground and one to GPIO 18.

  • If the LED doesn’t switch, make sure the resistor and LED are oriented properly.

  • Use sudo python3 button_led.py to run the program with the right permissions.


At Haruki Robotics Lab, we teach and learn by making. With this project, students combine coding logic with physical interaction — a key step toward building interactive robots and smart devices.

Comments


bottom of page