PWM

Pulse Width Modulation - If you flip an LED on and off quickly enough, you can control the brightness!

Code

"""
PWM Demo Code
Breadstick Innovations
April 26, 2024
https://learn.breadstick.ca/breadstick/breadsticks/raspberry-breadstick/code-examples/pwm

duty_cycle is a 16-bit integer
2^16 = 65536 values
0 is one of those values,
so the range is 0-65535.

range(start,stop,step)
range(0,10,1) = 0,1,2,3,4,5,6,7,8,9
range(10,0,-1) = 10,9,8,7,6,5,4,3,2,1
"""

from board import *
from pwmio import PWMOut
from time import sleep

led_5 = PWMOut(D5, frequency=500, duty_cycle=0)

while True:
    for i in range(0,65535,100):
        led_5.duty_cycle = i
        sleep(0.001)
    for i in range(65535,0,-100):
        led_5.duty_cycle = i
        sleep(0.001)

Last updated