0
0
Raspberry Piprogramming~5 mins

First GPIO program (LED blink) in Raspberry Pi

Choose your learning style9 modes available
Introduction

We use this program to make an LED light blink on and off. It helps us learn how to control hardware with code.

You want to test if your Raspberry Pi can control an LED.
You want to learn how to turn things on and off using code.
You want to create simple light signals or alerts.
You want to practice basic electronics with programming.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)

while True:
    GPIO.output(LED_PIN, GPIO.HIGH)  # Turn LED on
    time.sleep(1)                    # Wait 1 second
    GPIO.output(LED_PIN, GPIO.LOW)   # Turn LED off
    time.sleep(1)                    # Wait 1 second

Use GPIO.setmode(GPIO.BCM) to choose pin numbering by Broadcom chip.

GPIO.setup() sets the pin as output to control the LED.

Examples
This sets pin 17 as an output pin to control the LED.
Raspberry Pi
LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)
Turns the LED connected to pin 17 on and off.
Raspberry Pi
GPIO.output(17, GPIO.HIGH)  # LED on
GPIO.output(17, GPIO.LOW)   # LED off
Waits for half a second before the next action.
Raspberry Pi
time.sleep(0.5)
Sample Program

This program makes the LED connected to pin 17 blink on and off every second. It runs until you stop it with Ctrl+C. When stopped, it cleans up the GPIO pins.

Raspberry Pi
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)  # LED on
        time.sleep(1)                    # Wait 1 second
        GPIO.output(LED_PIN, GPIO.LOW)   # LED off
        time.sleep(1)                    # Wait 1 second
except KeyboardInterrupt:
    GPIO.cleanup()  # Clean up GPIO settings when program stops
OutputSuccess
Important Notes

Always clean up GPIO pins with GPIO.cleanup() to avoid warnings next time you run the program.

Make sure your LED is connected with a resistor to protect it from too much current.

Use try-except to safely stop the program with Ctrl+C.

Summary

This program controls an LED by turning it on and off repeatedly.

You learn how to set up GPIO pins and use delays to blink the LED.

Cleaning up GPIO pins is important to keep your Raspberry Pi safe.