An LED class helps you control a light on your Raspberry Pi easily. It lets you turn the light on, off, or blink it with simple commands.
0
0
LED class and methods in Raspberry Pi
Introduction
When you want to turn an LED light on or off using your Raspberry Pi.
When you want to make an LED blink to show a signal or alert.
When you are learning how to control hardware with code.
When building a project that needs simple light feedback.
When testing if your Raspberry Pi pins are working correctly.
Syntax
Raspberry Pi
class LED: def __init__(self, pin): # Setup the pin for output pass def on(self): # Turn the LED on pass def off(self): # Turn the LED off pass def blink(self, times, interval): # Blink the LED a number of times with delay pass
The __init__ method sets up the LED on a specific pin.
Methods like on(), off(), and blink() control the LED's behavior.
Examples
This creates an LED on pin 17 and turns it on.
Raspberry Pi
led = LED(17)
led.on()This creates an LED on pin 18 and turns it off.
Raspberry Pi
led = LED(18)
led.off()This makes the LED on pin 22 blink 3 times with half a second between on and off.
Raspberry Pi
led = LED(22) led.blink(3, 0.5)
Sample Program
This program creates an LED object on pin 17. It turns the LED on for 1 second, then off, then blinks it 3 times with half-second intervals. Finally, it cleans up the GPIO pins.
Raspberry Pi
import time import RPi.GPIO as GPIO class LED: def __init__(self, pin): self.pin = pin GPIO.setmode(GPIO.BCM) GPIO.setup(self.pin, GPIO.OUT) def on(self): GPIO.output(self.pin, GPIO.HIGH) def off(self): GPIO.output(self.pin, GPIO.LOW) def blink(self, times, interval): for _ in range(times): self.on() time.sleep(interval) self.off() time.sleep(interval) # Example usage led = LED(17) print("Turning LED on") led.on() time.sleep(1) print("Turning LED off") led.off() print("Blinking LED 3 times") led.blink(3, 0.5) GPIO.cleanup()
OutputSuccess
Important Notes
Always call GPIO.cleanup() at the end to reset the pins safely.
Use the BCM pin numbering mode for clarity and consistency.
Make sure your LED is connected with a resistor to avoid damage.
Summary
An LED class makes controlling lights on Raspberry Pi simple and organized.
Use on(), off(), and blink() methods to control the LED.
Remember to clean up GPIO pins after your program finishes.