Fareed Mohmed← Project library

Engineering · Raspberry Pi · Project 1 of 47 · Outputs · Start here

Blink an LED

The "hello world" of electronics. Switch an LED on and off once a second and see how Python talks to a GPIO pin.

▶ Open in the simulator

Raspberry Pi simulator drawing of the circuit for Blink an LED: the board, its power supply and the parts wired to the 40-pin header

Parts in this circuit

PartType
Red LEDLED

Wiring, pin by pin

Red = 5 V, orange = 3.3 V, black = GND, other colours = signals. “Pin” is the position on the 40-pin header; the GPIO number is what the code uses. Power the Pi from a 5.1 V supply and wire with the power off.

#ColourFrom (part and leg)To (header pin)
1ColouredRed LED - anode +Pin 11 (GPIO17)
2BlackRed LED - cathode -Pin 6 (GND)

Python code (gpiozero)

from gpiozero import LED
from time import sleep

led = LED(17)          # an LED on GPIO17

while True:
    led.on()
    print("LED on")
    sleep(1)
    led.off()
    print("LED off")
    sleep(1)

The same program with RPi.GPIO

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)      # use GPIO numbers, not pin positions
GPIO.setup(17, GPIO.OUT)    # GPIO17 is an output

try:
    while True:
        GPIO.output(17, GPIO.HIGH)
        print("LED on")
        time.sleep(1)
        GPIO.output(17, GPIO.LOW)
        print("LED off")
        time.sleep(1)
finally:
    GPIO.cleanup()          # always release the pins at the end

How the code works

You will learn

  • What a GPIO pin is and how to number it
  • Output: on, off
  • Why every LED needs a resistor

Try this

  • Make it blink faster: change the sleep times to 0.2.
  • Make the LED stay on for 3 seconds and off for 0.5 seconds.
  • Replace the loop with led.blink() and then pause(). What changes?

On a real Pi

  • Put a 220 to 470 ohm resistor in series with the LED. A GPIO pin can only give about 16 mA.
  • The long leg of the LED is the anode (+). It faces the GPIO pin. The short leg goes to GND.

Parts to buy

The links open a search on each store, so you see what is in stock today. Check the model, voltage and price before you order.

#ItemQtyBuy / compare
1Raspberry Pi 4 Model B
about 4000 to 9000 INR
1Robu.in Amazon.in ThinkRobotics
2Official 15 W USB-C power supply (5.1 V, 3 A)
Do not use an old phone charger
1Robu.in Amazon.in ThinkRobotics
3microSD card 32 GB, class 10 / A1 (with Raspberry Pi OS)
And a card reader to write it
1Robu.in Amazon.in ThinkRobotics
45 mm LED, red1Robu.in Amazon.in ThinkRobotics
5330 ohm resistor, 1/4 W
One per LED
1Robu.in Amazon.in ThinkRobotics
6Dupont jumper wires, male-to-female, 20 cm (pack of 40)1Robu.in Amazon.in ThinkRobotics
7Breadboard 830 points
For resistors and shared GND / 5 V
1Robu.in Amazon.in ThinkRobotics
All projects2. Button controls an LED →

This is a learning tool. The simulator checks the program logic, not the electrical design. Never put more than 3.3 V on a GPIO pin.