import RPi.GPIO as GPIO import time import random # Set the GPIO pin numbering mode GPIO.setmode(GPIO.BCM) # Set the GPIO pin used for the servo motor servo_pin = 4 GPIO.setup(servo_pin, GPIO.OUT) # Create a PWM instance pwm = GPIO.PWM(servo_pin, 50) # PWM with 50Hz frequency # Start PWM pwm.start(0) def rotate_servo(angle): duty = angle / 18 + 2 GPIO.output(servo_pin, True) pwm.ChangeDutyCycle(duty) time.sleep(1) GPIO.output(servo_pin, False) pwm.ChangeDutyCycle(0) try: while True: random_number = random.randint(1, 10) print("Random number:", random_number) if random_number % 2 == 0: print("Rotating 90 degrees clockwise") rotate_servo(90) else: print("Rotating 90 degrees anticlockwise") rotate_servo(-90) time.sleep(1) # Wait for 1 second before generating the next random number except KeyboardInterrupt: pwm.stop() GPIO.cleanup()
servi
Adafruit Playground is a wonderful place to share what you find interesting. Have a cool project you are working on? Have a bit of code that you think others will find useful? Want to show off your electronics workbench? You have come to the right place.
Adafruit Playground is a safe place to share with the wonderful Adafruit community of makers and doers.
Click here to learn more about Adafruit Playground and how to get started.
This page (servi) was last updated on March 14, 2024.
Text editor powered by tinymce.