Pulsing LED on the Raspberry Pi
FunduinoLast updated on
Eine LED per PWM heller und dunkler werden lassen – mit Python und gpiozero
You need this
Raspberry Pi 4 Model B - 2 GB RAM, 1,5 GHz, WLAN, gebraucht
44,90 € *Item no. F23110180About the product — Raspberry Pi 4 Model B - 2 GB RAM, 1,5 GHz, WLAN, gebraucht
Breadboard 830 Kontakte - Steckbrett für Arduino, lötfrei
2,90 € *Item no. FUN-1010553About the product — Breadboard 830 Kontakte - Steckbrett für Arduino, lötfrei
Breadboardkabel männlich-männlich - 40 Stück, 20 cm
1,74 € *Item no. FUN-1010558About the product — Breadboardkabel männlich-männlich - 40 Stück, 20 cm
LED 5 mm - 100 Stück, 5 Farben, 2 V
1,97 € *Item no. F23107316About the product — LED 5 mm - 100 Stück, 5 Farben, 2 V
Widerstandssortiment 100 Stück - 5 Werte 100 Ω bis 10 kΩ, 0,5 W
1,72 € *Item no. F23107216About the product — Widerstandssortiment 100 Stück - 5 Werte 100 Ω bis 10 kΩ, 0,5 W
All 5 parts together 53,23 € *
* All prices include statutory VAT, plus shipping costs.
Brightness via pulse-width modulation
Connect the LED
The program
pulsating_led.py
# Include the library for the LED with PWM
from gpiozero import PWMLED
from time import sleep
LED = PWMLED(23) # The LED is connected to GPIO 23 (Pin 16)
# Fade steps: determines the speed of the "fade".
FadeSteps = 0.02
# Brightness: the value output via PWM.
# 0 means off, 1 means full brightness. 0 is just an arbitrary starting value.
Brightness = 0
while True:
# The LED is controlled at the current brightness here.
LED.value = Brightness
# Now the value is changed: the fade steps
# are added to the previous brightness.
Brightness = Brightness + FadeSteps
# The LED should maintain its brightness only very briefly.
# Reducing this value makes the pulsing faster.
sleep(0.025)
# As soon as the brightness reaches 1 or 0, the sign
# of the fade steps changes. The LED then gets darker or brighter again.
if Brightness >= 1:
Brightness = 1
FadeSteps = -FadeSteps
if Brightness <= 0:
Brightness = 0
FadeSteps = -FadeStepsRate the instructions