舵机防抖代码

舵机防抖控制

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
signal = 18
GPIO.setup(signal, GPIO.OUT)
frequency = 50
pwm = GPIO.PWM(signal, frequency)
def get_duty(direction):
    duty = (1/18)*direction + 2.5
    return duty

if __name__ == '__main__':
    try:
        pwm.start(0)
        while True:
            direction = float(input("Please input a direction between 0 and 180:"))
            duty = get_duty(direction)
            pwm.ChangeDutyCycle(duty)
            time.sleep(0.04)     #防抖
            pwm.ChangeDutyCycle(0)     #防抖
    except Exception as e:
        print('An exception has happened',e)        
    finally:
        pwm.stop()
        GPIO.cleanup()

修正角度

import RPi.GPIO as GPIO
import random
import time
GPIO.setmode(GPIO.BCM)
signal = 18
GPIO.setup(signal, GPIO.OUT)
frequency = 50
pwm = GPIO.PWM(signal, frequency)
def get_duty(direction):
    duty = (1/18)*direction + 2.5
    return duty

if __name__ == '__main__':
    try:
        pwm.start(0)
        while True:
            direction = float(input("Please input a direction between 0 and 180:"))
#            direction =  random.randint(0,0)
            print(direction)
            duty = get_duty(direction)
            for i in range(1,20):
                pwm.ChangeDutyCycle(duty)
                time.sleep(0.04)
            pwm.ChangeDutyCycle(0)
    except Exception as e:
        print('An exception has happened',e)        
    finally:
        pwm.stop()
        GPIO.cleanup()