# Gradually changes the brightness of the onboard LED using PWM (Pulse Width Modulation) on GP25.

import time
from machine import Pin, PWM

# Construct PWM object attached to onboard LED pin (GPIO 25)
pwm = PWM(Pin(25))

# Set the PWM frequency (50 Hz provides smooth dimming without visible flicker)
pwm.freq(50)

# Variables to control smooth brightness fading
duty = 0          # Initial duty cycle value (0 = completely off, 65535 = full brightness)
step = 500        # Increment step per loop iteration
direction = 1     # 1 for brightening (fade in), -1 for dimming (fade out)

while True:
    # Increment or decrement the duty cycle
    duty += direction * step
    
    # Check upper boundary (16-bit max is 65535) and reverse direction
    if duty > 65535:
        duty = 65535
        direction = -1
    
    # Check lower boundary (minimum 0) and reverse direction
    elif duty < 0:
        duty = 0
        direction = 1
        
    # Write the 16-bit duty cycle value to PWM hardware
    pwm.duty_u16(duty)
    
    # Delay between duty cycle updates
    time.sleep(0.05)
    
    # Output relative duty cycle percentage (0.0 to 1.0) to console
    print("Duty cycle: ", duty / 65535)