Raspberry – LED

Introduction

In this course, we’ll look at a simple example of how to use the Raspberry Pi’s GPIOS by connecting a

LED. We’ll see how to make it flash and vary its brightness using PWM.

Here’s the circuit for connecting your LED to the Raspberry Pi:

The board has GPIOS which operate at +3.3V. We therefore use a 220 ohm resistor to limit the LED input current.

Programming

Here is the program to make the LED blink:

import RPi.GPIO as GPIO
import time

# Pin configuration
led_pin = 17

# Initial GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)

try:
    # Flash LED for 10 seconds
    for j in range(10):
        GPIO.output(led_pin, GPIO.HIGH) # Turn on LED
        time.sleep(0.5) # Wait 0.5 seconds
        GPIO.output(led_pin, GPIO.LOW) # Turn off LED
        time.sleep(0.5) # Wait 0.5 seconds

finally:
    # Clean GPIO resources
    GPIO.cleanup()

Here is the program to vary the brightness of the LED:

import RPi.GPIO as GPIO
import time

# Pin configuration
led_pin = 17

# Initial GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)

# PWM configuration
pwm_frequency = 1000 # PWM frequency in Hertz
pwm = GPIO.PWM(led_pin, pwm_frequency)

try:
    pwm.start(0) # Start PWM with 0% duty cycle

    # Dim the LED for 10 seconds
    for duty_cycle in range(0, 101, 5):
        pwm.ChangeDutyCycle(duty_cycle)
        time.sleep(0.5)

    for duty_cycle in range(100, -1, -5):
        pwm.ChangeDutyCycle(duty_cycle)
        time.sleep(0.5)

finally:
    # Clean GPIO resources
    pwm.stop()
    GPIO.cleanup()