0
0
Raspberry Piprogramming~5 mins

Single LED control in Raspberry Pi

Choose your learning style9 modes available
Introduction

We use single LED control to turn a light on or off with a Raspberry Pi. It helps us learn how to control hardware with code.

To make a simple indicator light for a project.
To learn how to control physical devices with programming.
To test if your Raspberry Pi's GPIO pins work correctly.
To create a basic alert system that lights up when something happens.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO
import time

LED_PIN = 18

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

GPIO.output(LED_PIN, GPIO.HIGH)  # Turn LED on
# ... wait or do something ...
GPIO.output(LED_PIN, GPIO.LOW)   # Turn LED off

GPIO.cleanup()

Use GPIO.setmode(GPIO.BCM) to refer to pins by their Broadcom number.

Always call GPIO.cleanup() at the end to reset pins safely.

Examples
This line sends power to the LED pin, lighting it up.
Raspberry Pi
GPIO.output(LED_PIN, GPIO.HIGH)  # Turns the LED on
This line stops power to the LED pin, turning it off.
Raspberry Pi
GPIO.output(LED_PIN, GPIO.LOW)  # Turns the LED off
This prepares the pin to send power to the LED.
Raspberry Pi
GPIO.setup(LED_PIN, GPIO.OUT)  # Sets the pin as output
Sample Program

This program turns the LED on for 3 seconds, then turns it off. It shows how to control the LED with simple commands.

Raspberry Pi
import RPi.GPIO as GPIO
import time

LED_PIN = 18

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

print('LED will turn on for 3 seconds...')
GPIO.output(LED_PIN, GPIO.HIGH)  # Turn LED on

time.sleep(3)  # Wait 3 seconds

GPIO.output(LED_PIN, GPIO.LOW)   # Turn LED off
print('LED is now off.')

GPIO.cleanup()
OutputSuccess
Important Notes

Make sure your LED is connected with a resistor to avoid damage.

Use the correct GPIO pin number matching your wiring.

Run the program with sudo if you get permission errors.

Summary

Single LED control lets you turn a light on or off using Raspberry Pi code.

You set the pin as output, then send HIGH or LOW signals to control the LED.

Always clean up GPIO settings after your program finishes.