Translate

How to Blink an LED with Raspberry Pi 4: A Complete Beginner's Guide

 After understanding the Raspberry Pi 4 Pin Diagram, it is time for our first practical experiment. In electronics, blinking an LED is the "Hello World" of hardware. Unlike an Arduino, where code runs instantly on power-up, the Raspberry Pi is a full computer. To control its pins, we need to write a simple script in Python.

1. Components Required

To build this project, you will need:

  • Raspberry Pi 4 (with Raspberry Pi OS installed)
  • One LED (any color)
  • One 220Ω Resistor (Red-Red-Brown)
  • Breadboard and Jumper Wires

2. The Circuit and Connection

Important: Power off your Raspberry Pi before making connections. We use a resistor to protect the Pi's GPIO pins from drawing too much current (they only handle 3.3V).

Wiring Step-by-Step:

  1. LED Anode (Long Leg): Connect to GPIO 18 (Physical Pin 12).
  2. LED Cathode (Short Leg): Connect to one end of the 220Ω Resistor.
  3. Other end of Resistor: Connect to any GND pin (Physical Pin 6 is easiest).

3. Software Setup (Using Thonny IDE)

To write our Python code, we use Thonny. It is simple and built into the Raspberry Pi OS.

  1. Click the Raspberry Icon (Start Menu) > Programming > Thonny Python IDE.
  2. Click File > New to open a fresh script.

4. The Python Code

from gpiozero import LED
from time import sleep

# Define the LED connected to GPIO 18
led = LED(18)

print("Program is running... Press the Red Stop button to quit.")

while True:
    led.on()        # Turn the LED ON
    print("LED is ON")
    sleep(1)        # Wait for 1 second
    
    led.off()       # Turn the LED OFF
    print("LED is OFF")
    sleep(1)        # Wait for 1 second

5. Code Explanation (Line-by-Line)

  • from gpiozero import LED: Imports the tool to control the LED.
  • from time import sleep: Imports the function to create delays.
  • led = LED(18): Tells the Pi the LED is on GPIO 18.
  • while True: An infinite loop to keep the program running.
  • led.on() / led.off(): Controls the power to the pin.
  • sleep(1): Pauses for 1 second.

6. Running the Project

  1. Click Save and name your file led_blink.py.
  2. Click the Green Play Button in Thonny.
  3. Result: Your LED will start blinking!

Pro-Tip for Students: Always Shutdown your Raspberry Pi from the menu before pulling the power cable to prevent SD card corruption!


🚀 Projects to Try Next

Now that you have mastered the basic blink, try these challenges:

  1. Change the Speed: Change sleep(1) to sleep(0.2) for a fast blink.
  2. Double Blink: Connect a second LED to GPIO 24 and make them blink alternately.
തുടക്കക്കാർക്കായി ഇലക്ട്രോണിക്സ് ലളിതമായി പഠിക്കാം.

Empowering students in Kerala with hands-on technical skills.