How ToIoT HardwaresRaspberry PiTutorials/DIY

Controlling an LED with Raspberry Pi GPIO

This guide shows how to control an LED using Raspberry Pi GPIO with both console commands and Python programming. We’ll also explore interfacing with a switch and sending email alerts based on switch input.

Switching LED On/Off from Raspberry Pi Console

In this example, the LED is connected to GPIO pin 18. You can connect it to any other GPIO pin, but ensure you modify the commands accordingly.

Step 1: Export GPIO Pin

echo 18 > /sys/class/gpio/export
cd /sys/class/gpio/gpio18

Step 2: Set Pin Direction to Output

echo out > direction

Step 3: Control LED State

  • Turn LED On:
echo 1 > value
  • Turn LED Off:
echo 0 > value

Python Program for Blinking LED

This Python code uses the RPi.GPIO library to blink an LED every second.

import RPi.GPIO as GPIO
import time

# Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

# Blinking LED Loop
try:
    while True:
        GPIO.output(18, True)  # Turn LED ON
        time.sleep(1)
        GPIO.output(18, False)  # Turn LED OFF
        time.sleep(1)
except KeyboardInterrupt:
    GPIO.cleanup()  # Clean up on exit

Interfacing an LED and Switch with Raspberry Pi

In this example, the LED is connected to GPIO pin 18, and the switch is connected to GPIO pin 25. The LED will toggle each time the switch is pressed.

from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

# Pin Setup
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  # Switch
GPIO.setup(18, GPIO.OUT)  # LED

state = False

def toggleLED():
    global state
    state = not state
    GPIO.output(18, state)

try:
    while True:
        if GPIO.input(25):
            toggleLED()
            sleep(0.5)  # Debounce delay
except KeyboardInterrupt:
    GPIO.cleanup()

Python Program for Sending an Email on Switch Press

This example demonstrates sending an email when a switch is pressed.

import smtplib
from time import sleep
import RPi.GPIO as GPIO

# Email Configuration
from_email = 'your-email@gmail.com'
recipient_list = ['recipient-email@gmail.com']
subject = 'Alert: Switch Pressed'
message = 'The switch was pressed on your Raspberry Pi.'
username = 'your-email@gmail.com'
password = 'your-email-password'
smtp_server = 'smtp.gmail.com:587'

# GPIO Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def send_email():
    header = f"From: {from_email}\nTo: {', '.join(recipient_list)}\nSubject: {subject}\n\n"
    full_message = header + message

    server = smtplib.SMTP(smtp_server)
    server.starttls()
    server.login(username, password)
    server.sendmail(from_email, recipient_list, full_message)
    server.quit()

try:
    while True:
        if GPIO.input(25):
            send_email()
            print("Email Sent Successfully")
            sleep(0.5)  # Debounce delay
except KeyboardInterrupt:
    GPIO.cleanup()

Important Note:

For Gmail, ensure you enable “Less Secure Apps” or generate an app password for SMTP access.

Conclusion

By following this guide, you can confidently:

  • Control an LED using Raspberry Pi’s GPIO pins.
  • Interface a switch to control devices or trigger alerts.
  • Use Python to write dynamic, real-world applications.

If you’d like further examples or advanced projects, let me know!


You may like also:

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin