###########################
### Code in MicroPython ###
###########################

# Modules of the XIAO-RP2040 for GPIOs control and PWM generation
from machine import Pin, PWM

# Set pin 3 as LED output
led = Pin(3, Pin.OUT)

# Set pin 0 as servo output
servo = PWM(Pin(0))
# Set servo frequency
servo.freq(50)

# Function that converts an angle (0–180) to a duty cycle
def set_angle(angle):
    # Safety if values are under 0 or above 180
    if angle < 0:
        angle = 0
    if angle > 180:
        angle = 180

    # Servo pulse width range : ~500µs to ~2500µs
    min_us = 500
    max_us = 2500

    # Angle to pulse width conversion
    pulse_us = min_us + (max_us - min_us) * angle / 180

    # Pulse width to PWM duty conversion
    # RP2040 PWM : 16-bit (0–65535), 20ms period = 20000µs
    duty = int(pulse_us * 65535 / 20000)

    # Send PWM signal
    servo.duty_u16(duty)

# Infinite loop
while True:
    # Variable that reads the shell's data
    shell = input()
    
    # If the shell reads "LED ON"
    if shell == "LED ON":
        # Turns LED ON
        led.value(1)

    # If the shell reads "LED OFF"
    elif shell == "LED OFF":
        # Turns LED OFF
        led.value(0)
        
    # If the shell reads a value between 0 and 180
    elif 0 <= int(shell) <= 180:
        # Sets servomotor angle
        set_angle(int(shell))