Raspberry Pi GPIO: Control LEDs with Python — Complete Beginner Guide
GPIO Basics

Raspberry Pi GPIO: Control LEDs with Python — Complete Beginner Guide

📅 2024-01-15 RaspControl Team 20 min read
Time
20 min
Difficulty
Beginner
Hardware
Any Pi
Language
Python
Code
GitHub ✓
← Back to Tutorials

Controlling an LED with GPIO is the classic "Hello World" of Raspberry Pi hardware projects. It seems simple, but it teaches you everything you need to know about GPIO pins, Python programming, and basic electronics.

Raspberry Pi GPIO
GPIO pins on Raspberry Pi — your gateway to the physical world

What You'll Need

🔧 Parts List

  • 1× LED (any color, 5mm)
  • 1× 330Ω resistor (orange-orange-brown bands)
  • 2× jumper wires (male-to-female)
  • 1× breadboard
  • Raspberry Pi (any model with GPIO)

Understanding GPIO Pins

Your Raspberry Pi has 40 GPIO pins. Some are power pins (3.3V, 5V, GND) and some are programmable I/O pins. We'll use GPIO 18 (Physical pin 12) for this project.

💡 Why Use a Resistor?

An LED without a resistor will draw too much current and burn out (and possibly damage your Pi). The 330Ω resistor limits current to a safe ~10mA.

Wiring the Circuit

  1. 1

    Connect GPIO 18 to Resistor

    From GPIO pin 18 (physical pin 12) to one end of the 330Ω resistor via a jumper wire.

  2. 2

    Connect Resistor to LED

    From the other end of the resistor to the long leg (anode +) of the LED.

  3. 3

    Connect LED to Ground

    From the short leg (cathode -) of the LED back to any GND pin on the Pi.

Python Code

First, install the GPIO library if it's not already installed:

pi@raspberrypi:~ $
$ pip3 install RPi.GPIO Successfully installed RPi.GPIO-0.7.1

Basic LED Blink

import RPi.GPIO as GPIO import time # Setup GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # Blink 10 times try: for i in range(10): GPIO.output(18, GPIO.HIGH) # ON time.sleep(0.5) GPIO.output(18, GPIO.LOW) # OFF time.sleep(0.5) finally: GPIO.cleanup() # Always cleanup!

Found this helpful? Share it! 👇