We control LED brightness to make lights dimmer or brighter smoothly. This helps save energy and create nice lighting effects.
0
0
LED brightness control in Raspberry Pi
Introduction
When you want to make a night light that gets dimmer over time.
To create mood lighting that changes brightness slowly.
When building a project that needs different light levels, like a lamp.
To show visual feedback by changing LED brightness based on sensor input.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO import time led_pin = 18 frequency = 1000 duty_cycle = 50 GPIO.setmode(GPIO.BCM) GPIO.setup(led_pin, GPIO.OUT) pwm = GPIO.PWM(led_pin, frequency) pwm.start(duty_cycle)
Use GPIO.PWM(pin, frequency) to create a PWM object controlling the LED.
duty_cycle is a number from 0 (off) to 100 (fully on) controlling brightness.
Examples
This sets up an LED on pin 18 with half brightness.
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 1000) # 1000 Hz frequency pwm.start(50) # 50% brightness
Use
ChangeDutyCycle to change LED brightness while running.Raspberry Pi
pwm.ChangeDutyCycle(75) # Change brightness to 75%
Stop PWM and clean up GPIO pins when done.
Raspberry Pi
pwm.stop() GPIO.cleanup()
Sample Program
This program slowly increases LED brightness from 0% to 100%, then back down to 0%, printing the brightness level each step.
Raspberry Pi
import RPi.GPIO as GPIO import time led_pin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(led_pin, GPIO.OUT) pwm = GPIO.PWM(led_pin, 1000) # 1000 Hz frequency pwm.start(0) # start with LED off try: for brightness in range(0, 101, 10): pwm.ChangeDutyCycle(brightness) print(f"LED brightness: {brightness}%") time.sleep(0.5) for brightness in range(100, -1, -10): pwm.ChangeDutyCycle(brightness) print(f"LED brightness: {brightness}%") time.sleep(0.5) finally: pwm.stop() GPIO.cleanup()
OutputSuccess
Important Notes
Make sure to connect the LED with a resistor to avoid damage.
Use GPIO.cleanup() to reset pins after your program ends.
Frequency controls how fast the LED turns on and off; 1000 Hz is smooth for eyes.
Summary
LED brightness is controlled by changing PWM duty cycle from 0 to 100%.
Use RPi.GPIO library to set up PWM on Raspberry Pi pins.
Always clean up GPIO pins after use to avoid issues.