from machine import Pin, PWM
import time
import sys
import select

# Setup
led = PWM(Pin(26))
led.freq(1000)
led.duty_u16(0)

button = Pin(27, Pin.IN, Pin.PULL_UP)

commands = "Commands: on, off, fade, blink, status, help"

print("RP2040 Serial Command Interface")
print(commands)

while True:
    # Check if there's incoming serial data
    if select.select([sys.stdin], [], [], 0)[0]:
        command = sys.stdin.readline().strip().lower()

        if command == "on":
            led.duty_u16(65535)
            print("LED: ON")

        elif command == "off":
            led.duty_u16(0)
            print("LED: OFF")

        elif command == "fade":
            print("LED: Fading...")
            for i in range(0, 65535, 500):
                led.duty_u16(i)
                time.sleep(.01)
            for i in range(65535, 0, -500):
                led.duty_u16(i)
                time.sleep(.01)
            led.duty_u16(0)
            print("LED: Fade complete")

        elif command == "blink":
            print("LED: Blinking 3 times...")
            for i in range(3):
                led.duty_u16(65535)
                time.sleep(0.5)
                led.duty_u16(0)
                time.sleep(0.5)
            print("LED: Blink complete")

        elif command == "status":
            btn = "PRESSED" if button.value() == 0 else "NOT PRESSED"
            print("Button: " + btn)

        elif command == "help":
            print(commands)

        else:
            print("Unknown command: " + command)

    time.sleep(0.1)
