Untitled

 avatar
unknown
python
a year ago
903 B
2
Indexable
import RPi.GPIO as GPIO
import time

# Set the GPIO mode to BCM
GPIO.setmode(GPIO.BCM)

# Define the GPIO pin connected to the servo
servo_pin = 18

# Set the GPIO pin as an output
GPIO.setup(servo_pin, GPIO.OUT)

# Create a PWM instance with a frequency of 50Hz
pwm = GPIO.PWM(servo_pin, 50)

def move_servo(angle):
    duty_cycle = (angle / 18) + 2
    pwm.start(duty_cycle)
    time.sleep(1)
    pwm.stop()

try:
    while True:
        # Get the desired angle from the user
        angle_str = input("Enter the angle (0 to 180): ")
        angle = int(angle_str)

        # Check if the angle is within the valid range
        if 0 <= angle <= 180:
            move_servo(angle)
        else:
            print("Invalid angle. Please enter a value between 0 and 180.")

except KeyboardInterrupt:
    print("\nProgram terminated by the user.")
finally:
    # Clean up GPIO settings
    GPIO.cleanup()
Leave a Comment