Raspberry Pi Program to Control LED with Button
gpiozero library to control an LED with a button on Raspberry Pi by creating LED and Button objects and linking the button press to turn the LED on or off, e.g., button.when_pressed = led.on and button.when_released = led.off.Examples
How to Think About It
Algorithm
Code
from gpiozero import LED, Button from signal import pause led = LED(17) # Connect LED to GPIO17 button = Button(2) # Connect button to GPIO2 button.when_pressed = led.on button.when_released = led.off print('Press the button to control the LED') pause()
Dry Run
Let's trace pressing and releasing the button through the code
Program starts
LED connected to GPIO17 is off; button connected to GPIO2 is waiting for press.
Button pressed
button.when_pressed triggers led.on(), LED turns on.
Button released
button.when_released triggers led.off(), LED turns off.
| Event | LED State |
|---|---|
| Program start | Off |
| Button pressed | On |
| Button released | Off |
Why This Works
Step 1: Setup GPIO pins
The LED and Button objects link to specific GPIO pins to control hardware.
Step 2: Button press event
When the button is pressed, the program runs led.on() to light the LED.
Step 3: Button release event
When the button is released, the program runs led.off() to turn the LED off.
Alternative Approaches
import RPi.GPIO as GPIO import time LED_PIN = 17 BUTTON_PIN = 2 GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) try: while True: if GPIO.input(BUTTON_PIN) == GPIO.LOW: GPIO.output(LED_PIN, GPIO.HIGH) else: GPIO.output(LED_PIN, GPIO.LOW) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()
from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(2, hold_time=2) button.when_held = led.toggle print('Hold button for 2 seconds to toggle LED') pause()
Complexity: O(1) time, O(1) space
Time Complexity
The program reacts to button events without loops that depend on input size, so it runs in constant time.
Space Complexity
Only a few variables for GPIO pins and objects are used, so space is constant.
Which Approach is Fastest?
Using gpiozero event handlers is more efficient than polling loops because it waits for hardware events.
| Approach | Time | Space | Best For |
|---|---|---|---|
| gpiozero event handlers | O(1) | O(1) | Simple, efficient event-driven control |
| RPi.GPIO polling loop | O(1) | O(1) | Basic control, easy to understand but less efficient |
| gpiozero hold_time toggle | O(1) | O(1) | Advanced button event handling with long press |