
import machine
import random
import time

# Set up PWM on A0 (GP26), A1 (GP27), A2 (GP28)
led_pins = [26, 27, 28]
pwm_leds = [machine.PWM(machine.Pin(p)) for p in led_pins]
moon = machine.Pin(1, machine.Pin.OUT)

# Set PWM frequency (1000 Hz works well for LEDs)
for pwm in pwm_leds:
    pwm.freq(1000)

def set_brightness(pwm, brightness):
    """Set brightness 0-100% -> duty cycle 0-65535"""
    duty = int((brightness / 100) * 65535)
    pwm.duty_u16(duty)

def twinkle():
    # Pick a random target brightness for each LED
    targets = [random.randint(0, 100) for _ in pwm_leds]
    # Get current brightness levels
    current = [int(pwm.duty_u16() / 65535 * 100) for pwm in pwm_leds]
    
    # Smoothly transition to target brightness
    steps = 20
    for step in range(steps + 1):
        for i, pwm in enumerate(pwm_leds):
            brightness = current[i] + (targets[i] - current[i]) * step // steps
            set_brightness(pwm, brightness)
        time.sleep_ms(30)  # Controls fade speed (~600ms total per twinkle)

# Main loop
moon.on()
while True:
    twinkle()
    time.sleep_ms(random.randint(0, 200))  # Random pause between twinkles
    

