import RPi.GPIO as GPIO
import time
# Set the GPIO mode
GPIO.setmode(GPIO.BCM)
# Define the GPIO pin for the LED
led_pin = 21
# Set the GPIO pin as output
GPIO.setup(led_pin, GPIO.OUT)
# Create PWM object with frequency 100 Hz
pwm = GPIO.PWM(led_pin, 100)
# Start PWM with 0% duty cycle
pwm.start(0)
try:
# Gradually increase brightness
for duty_cycle in range(0, 101, 5):
pwm.ChangeDutyCycle(duty_cycle)
time.sleep(0.1)
# Gradually decrease brightness
for duty_cycle in range(100, -1, -5):
pwm.ChangeDutyCycle(duty_cycle)
time.sleep(0.1)
finally:
# Clean up GPIO
pwm.stop()
GPIO.cleanup()