Raspberry Pi Program to Blink LED with Python
RPi.GPIO library in Python to blink an LED by setting a GPIO pin as output and toggling it on and off with GPIO.output(pin, GPIO.HIGH) and GPIO.output(pin, GPIO.LOW) inside a loop with delays.Examples
How to Think About It
Algorithm
Code
import RPi.GPIO as GPIO import time LED_PIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) try: for _ in range(5): # Blink 5 times GPIO.output(LED_PIN, GPIO.HIGH) # LED on print("LED ON") time.sleep(1) # Wait 1 second GPIO.output(LED_PIN, GPIO.LOW) # LED off print("LED OFF") time.sleep(1) # Wait 1 second finally: GPIO.cleanup() # Reset GPIO settings print("GPIO cleaned up")
Dry Run
Let's trace blinking the LED 2 times through the code
Setup GPIO
Set GPIO mode to BCM and configure pin 18 as output.
First blink ON
Set pin 18 HIGH to turn LED on; print 'LED ON'; wait 1 second.
First blink OFF
Set pin 18 LOW to turn LED off; print 'LED OFF'; wait 1 second.
Second blink ON
Set pin 18 HIGH again; print 'LED ON'; wait 1 second.
Second blink OFF
Set pin 18 LOW; print 'LED OFF'; wait 1 second.
Cleanup
Call GPIO.cleanup() to reset pins; print 'GPIO cleaned up'.
| Iteration | LED State | Printed Output |
|---|---|---|
| 1 | ON | LED ON |
| 1 | OFF | LED OFF |
| 2 | ON | LED ON |
| 2 | OFF | LED OFF |
Why This Works
Step 1: GPIO Setup
We use GPIO.setmode(GPIO.BCM) to refer to pins by their GPIO numbers and GPIO.setup() to set the LED pin as output so we can control it.
Step 2: Blinking Loop
Inside the loop, GPIO.output(pin, GPIO.HIGH) powers the LED on, and GPIO.output(pin, GPIO.LOW) turns it off, with time.sleep() pauses to make the blinking visible.
Step 3: Cleanup
Calling GPIO.cleanup() resets the GPIO pins to a safe state to avoid warnings or conflicts when running other programs.
Alternative Approaches
from gpiozero import LED from time import sleep led = LED(18) for _ in range(5): led.on() print("LED ON") sleep(1) led.off() print("LED OFF") sleep(1)
import RPi.GPIO as GPIO import time LED_PIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) pwm = GPIO.PWM(LED_PIN, 1000) # 1kHz frequency pwm.start(0) try: for duty_cycle in range(0, 101, 20): pwm.ChangeDutyCycle(duty_cycle) print(f"LED brightness {duty_cycle}%") time.sleep(1) finally: pwm.stop() GPIO.cleanup()
Complexity: O(n) time, O(1) space
Time Complexity
The program runs a loop for n blinks, so time grows linearly with the number of blinks.
Space Complexity
Uses a fixed amount of memory for GPIO setup and variables, so space is constant.
Which Approach is Fastest?
All approaches run in similar time; gpiozero is simpler but adds a small overhead, PWM adds complexity for brightness control.
| Approach | Time | Space | Best For |
|---|---|---|---|
| RPi.GPIO basic blink | O(n) | O(1) | Simple on/off blinking |
| gpiozero library | O(n) | O(1) | Beginner-friendly, easy code |
| RPi.GPIO with PWM | O(n) | O(1) | Controlling LED brightness |
GPIO.cleanup() at the end to reset pins and avoid warnings.