使用PCA9685和树莓派

时间:2019-04-22 10:21:06

标签: python raspberry-pi3 adafruit servo

我在树莓派上集成了360度伺服电机和PCA9685模块。现在,我正在尝试使用python将伺服电机旋转至特定角度。这是我尝试过的:

from __future__ import division
import time
import sys

# Import the PCA9685 module.
import Adafruit_PCA9685

# Initialise the PCA9685 using the default address (0x40).
pwm = Adafruit_PCA9685.PCA9685()

# Configure min and max servo pulse lengths
servo_min = 20  # Min pulse length out of 4096
servo_max = 900  # Max pulse length out of 4096

# Helper function to make setting a servo pulse width simpler.
def set_servo_pulse(channel, pulse):
    pulse_length = 1000000    # 1,000,000 us per second
    pulse_length //= 60       # 60 Hz
    print('{0}us per period'.format(pulse_length))
    pulse_length //= 4096     # 12 bits of resolution
    print('{0}us per bit'.format(pulse_length))
    pulse *= 1000
    pulse //= pulse_length
    pwm.set_pwm(channel, 0, pulse)

# Set frequency to 60hz, good for servos.
pwm.set_pwm_freq(60)

print('Moving servo on channel 0, press Ctrl-C to quit...')
try:
    while True:
        # Move servo on channel O between extremes.
        pwm.set_pwm(0, 0, servo_min)
        time.sleep(1)
        pwm.set_pwm(0, 0, 0) # to stop the servo continuous rotation
        time.sleep(1)
        pwm.set_pwm(0, 0, servo_max)
        time.sleep(1)
        pwm.set_pwm(0, 0, 0)
        time.sleep(1)
except KeyboardInterrupt:
    pwm.set_pwm(0, 0, 0)
    print("Exiting......")
    sys.exit(0)

该代码在旋转伺服电机时效果很好,但是我无法获得特定的角度旋转,例如60度旋转。任何帮助表示赞赏。

0 个答案:

没有答案