from machine import Pin, PWM
import time

# Define pins
LED_PIN = 2       # GP2
BTN1_PIN = 3      # GP3
BTN2_PIN = 4      # GP4
SERVO_PIN = 5     # GP5

# Initialize LED and buttons
led = Pin(LED_PIN, Pin.OUT)
btn1 = Pin(BTN1_PIN, Pin.IN, Pin.PULL_UP)
btn2 = Pin(BTN2_PIN, Pin.IN, Pin.PULL_UP)

# Initialize servo
servo = PWM(Pin(SERVO_PIN))
servo.freq(50)  # Standard servo frequency 50Hz

# Function to convert angle to duty cycle
def angle_to_duty(angle):
    # Standard servo: 0° = 1ms pulse, 180° = 2ms pulse in a 20ms period (50Hz)
    # This translates to duty cycles of 5% to 10%
    min_duty = int(0.05 * 65535)  # 5% duty cycle
    max_duty = int(0.10 * 65535)  # 10% duty cycle
    return min_duty + (max_duty - min_duty) * angle / 180

# Initial setup
current_angle = 90
servo.duty_u16(int(angle_to_duty(current_angle)))
led.value(0)  # LED off

# Main loop
while True:
    # Check Button 1 - Increase angle
    if not btn1.value():  # Button is active low
        time.sleep_ms(150)  # Debounce delay
        if not btn1.value():  # Check if button is still pressed
            if current_angle < 180:
                current_angle += 30
                if current_angle > 180:
                    current_angle = 180
                led.value(1)  # LED on
                servo.duty_u16(int(angle_to_duty(current_angle)))
                time.sleep(2)  # Keep LED on for 2 seconds
                led.value(0)  # LED off
            # Wait for button release
            while not btn1.value():
                time.sleep_ms(10)
    
    # Check Button 2 - Decrease angle
    if not btn2.value():  # Button is active low
        time.sleep_ms(150)  # Debounce delay
        if not btn2.value():  # Check if button is still pressed
            if current_angle > 0:
                current_angle -= 30
                if current_angle < 0:
                    current_angle = 0
                led.value(1)  # LED on
                servo.duty_u16(int(angle_to_duty(current_angle)))
                time.sleep(2)  # Keep LED on for 2 seconds
                led.value(0)  # LED off
            # Wait for button release
            while not btn2.value():
                time.sleep_ms(10)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT