Introduction
The Raspberry Pi's GPIO (General Purpose Input/Output) pins let you interact with the physical world using Python. In this tutorial, you'll learn to control LEDs — the foundational skill for all Pi hardware projects.
What You'll Need
- Raspberry Pi (any model with GPIO header)
- 1× LED
- 1× 330Ω resistor
- Breadboard and jumper wires
- Raspberry Pi OS installed
GPIO Pin Layout
The Raspberry Pi has 40 GPIO pins. We'll use GPIO 17 (physical pin 11) for this tutorial.
Wiring
- Connect GPIO 17 → 330Ω resistor → LED anode (long leg)
- Connect LED cathode (short leg) → GND (physical pin 6)
Python Code: Blink
import RPi.GPIO as GPIO
import time
LED_PIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
try:
while True:
GPIO.output(LED_PIN, GPIO.HIGH)
print("LED ON")
time.sleep(1)
GPIO.output(LED_PIN, GPIO.LOW)
print("LED OFF")
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()Run with: python3 blink.py
Python Code: Button-Controlled LED
Add a push button connected to GPIO 27 with a pull-down resistor.
import RPi.GPIO as GPIO
LED_PIN = 17
BUTTON_PIN = 27
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
try:
while True:
if GPIO.input(BUTTON_PIN):
GPIO.output(LED_PIN, GPIO.HIGH)
else:
GPIO.output(LED_PIN, GPIO.LOW)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()Important Notes
- Always use a resistor with LEDs to prevent burning them out
- GPIO pins output 3.3V (not 5V like Arduino)
- Always call
GPIO.cleanup()when done to reset pin states - The
BCMnumbering refers to the Broadcom chip pin numbers