from machine import Pin, PWM, ADC
import time

# Pin definitions
LED_PIN = 2          # LED connected to GP2
BTN1_PIN = 3         # Button 1 connected to GP3
BTN2_PIN = 4         # Button 2 connected to GP4
POT1_PIN = 26        # Potentiometer 1 connected to GP26 (ADC0)
POT2_PIN = 27        # Potentiometer 2 connected to GP27 (ADC1)
POT3_PIN = 28        # Potentiometer 3 connected to GP28 (ADC2)
DEBOUNCE_DELAY = 150 # Debounce delay in milliseconds

# Initialize components
led = PWM(Pin(LED_PIN))
led.freq(1000)  # Set PWM frequency to 1kHz
btn1 = Pin(BTN1_PIN, Pin.IN, Pin.PULL_UP)
btn2 = Pin(BTN2_PIN, Pin.IN, Pin.PULL_UP)
pot1 = ADC(Pin(POT1_PIN))
pot2 = ADC(Pin(POT2_PIN))
pot3 = ADC(Pin(POT3_PIN))

# Global variables
manual_mode = True
last_debounce_time = 0
led_brightness = 0
min_brightness = 0
max_brightness = 0

# Set initial LED brightness to 0
led.duty_u16(0)

def map_value(value, from_min, from_max, to_min, to_max):
    """Map a value from one range to another"""
    return int((value - from_min) * (to_max - to_min) / (from_max - from_min) + to_min)

def handle_buttons():
    """Handle button presses with debouncing"""
    global manual_mode, last_debounce_time
    current_time = time.ticks_ms()
    
    if time.ticks_diff(current_time, last_debounce_time) > DEBOUNCE_DELAY:
        if btn1.value() == 0:  # Button 1 pressed (active low)
            manual_mode = False
            last_debounce_time = current_time
        elif btn2.value() == 0:  # Button 2 pressed (active low)
            manual_mode = True
            last_debounce_time = current_time

def manual_mode_operation():
    """Control LED brightness directly using potentiometer 1"""
    # Read pot1 value (0-65535) and set LED brightness
    pot1_value = pot1.read_u16()
    # Map pot value to LED brightness (0-65535 for duty_u16)
    led_brightness = pot1_value
    led.duty_u16(led_brightness)

def auto_mode_operation():
    """Cycle LED brightness between min and max values set by potentiometers 2 and 3"""
    # Read min/max brightness values from potentiometers
    min_brightness = pot2.read_u16()
    max_brightness = pot3.read_u16()
    
    # Ensure min_brightness <= max_brightness
    if min_brightness > max_brightness:
        min_brightness, max_brightness = max_brightness, min_brightness
    
    # Calculate step size for a smooth transition (about 50 steps)
    step_size = max(1, (max_brightness - min_brightness) // 50)
    
    # Fade up
    for brightness in range(min_brightness, max_brightness + 1, step_size):
        led.duty_u16(brightness)
        time.sleep_ms(20)
    
    # Fade down
    for brightness in range(max_brightness, min_brightness - 1, -step_size):
        led.duty_u16(brightness)
        time.sleep_ms(20)

# Main loop
while True:
    handle_buttons()
    
    if manual_mode:
        manual_mode_operation()
    else:
        auto_mode_operation()
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT