import time
time.sleep(0.1) # Wait for USB to become ready
from machine import Pin, PWM
import utime
import math
# Function to create an RGB LED structure
def create_rgb_led(red_pin, green_pin, blue_pin):
led = {
'red': PWM(Pin(red_pin)),
'green': PWM(Pin(green_pin)),
'blue': PWM(Pin(blue_pin))
}
# Set frequency for all colors
for color in led.values():
color.freq(1000)
return led
# Initialize two RGB LEDs
led1 = create_rgb_led(16, 17, 18)
led2 = create_rgb_led(15, 14, 13)
# Pre-calculate the duty values based on a sine wave
sine_duties = [int((1 - (math.sin(math.radians(i)) + 1) / 2) * 65535) for i in range(360)]
# Dictionary to keep track of the current position for each color of each LED
current_positions = {
led1['red']: 0, led1['green']: len(sine_duties) // 2, led1['blue']: len(sine_duties) - 1,
led2['red']: 0, led2['green']: len(sine_duties) // 2, led2['blue']: len(sine_duties) - 1
}
# Rate table with entries for each permutation of rates
rate_table = [
{color: 1 for color in current_positions}, # All colors fade at the same rate
{color: 2 if 'green' in color.pin else 4 for color in current_positions}, # Custom rates per LED color
{color: 4 if 'blue' in color.pin else 1 for color in current_positions} # Another custom rate configuration
]
print(rate_table)
# Index to keep track of the current rate configuration
rate_index = 0
def apply_fade(color, tick_count):
# Check if it's time to update this color based on its rate
if tick_count % rate_table[rate_index][color] == 0:
color.duty_u16(sine_duties[current_positions[color]])
current_positions[color] = (current_positions[color] + 1) % len(sine_duties)
# Main loop
tick_count = 0
while tick_count < 5:
for led in [led1, led2]:
for color in led.values():
apply_fade(color, tick_count)
tick_count += 1
utime.sleep(0.1) # Control the update rate for all LEDs here
# Change rate configuration after some time
if tick_count % 1000 == 0: # Change rate every 1000 ticks
rate_index = (rate_index + 1) % len(rate_table)