import RPi.GPIO as GPIO
import time

# Pin configuration
servo_pin = 11  # Replace with the actual pin connected to the servo motor

# Setup GPIO
GPIO.setmode(GPIO.BOARD)  # Use physical pin numbering
GPIO.setup(servo_pin, GPIO.OUT)

# Setup PWM
frequency = 50  # Typical servo motors use a 50 Hz frequency
pwm = GPIO.PWM(servo_pin, frequency)
pwm.start(0)  # Start PWM with 0% duty cycle

# Helper function to set angle
def set_servo_angle(angle):
    """
    Sets the servo to the specified angle.
    :param angle: The desired angle (0 to 180 degrees)
    """
    duty_cycle = 2 + (angle / 18)  # Map 0-180 degrees to 2-12% duty cycle
    pwm.ChangeDutyCycle(duty_cycle)
    time.sleep(0.5)  # Allow the servo to reach the position
    pwm.ChangeDutyCycle(0)  # Stop sending signal to prevent jittering

try:
    while True:
        # Move servo to 0 degrees
        print("Moving to 0 degrees")
        set_servo_angle(0)

        # Move servo to 90 degrees
        print("Moving to 90 degrees")
        set_servo_angle(90)

        # Move servo to 180 degrees
        print("Moving to 180 degrees")
        set_servo_angle(180)

except KeyboardInterrupt:
    print("Stopping program")

finally:
    pwm.stop()  # Stop PWM
    GPIO.cleanup()  # Clean up GPIO