使伺服系统以正弦曲线移动(Python)

时间:2015-08-18 10:00:00

标签: python sin

我正试图找到一种方法让我的伺服器像罪恶波一样移动。我已经设法让它们从一个位置跳到另一个位置我不知道如何使它们以正确的频率和幅度在正弦曲线中平滑移动:/

向伺服器发送命令的代码如下,我使用Adafruit伺服库向我的伺服器发送命令。

#!/usr/bin/python

from Adafruit_PWM_Servo_Driver import PWM
import time

# ===========================================================================
# Example Code
# ===========================================================================

# Initialise the PWM device using the default address
pwm = PWM(0x40)
# Note if you'd like more debug output you can instead run:
#pwm = PWM(0x40, debug=True)

servoMin = 150  # Min pulse length out of 4096
servoMax = 600  # Max pulse length out of 4096

def setServoPulse(channel, pulse):
  pulseLength = 1000000                   # 1,000,000 us per second
  pulseLength /= 60                       # 60 Hz
  print "%d us per period" % pulseLength
  pulseLength /= 4096                     # 12 bits of resolution
  print "%d us per bit" % pulseLength
  pulse *= 1000
  pulse /= pulseLength
  pwm.setPWM(channel, 0, pulse)

pwm.setPWMFreq(60)                        # Set frequency to 60 Hz
while (True):
  # Change speed of continuous servo on channel O
  pwm.setPWM(0, 0, servoMin)
  time.sleep(1)
  pwm.setPWM(0, 0, servoMax)
  time.sleep(1)

真的很感激帮助!

干杯,

大卫

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您只需要以正弦波方式生成servoMinservoMax之间的值。

类似(更新):

from math import pi, sin

MS_IN_SECOND = 1000

# lower and upper amplitude value boundaries
lb = servoMin
ub = servoMax
zero = (lb + ub) / 2

max_amplitude = ub - zero

# set the amplitude, comes with a safeguard
amplitude = min(max_amplitude, 100) 

# set the frequency, i.e. how many times per second (actual, or scaled)
# the wave crosses 'zero'
freq = 1

# sleep duration (in milliseconds!) is a resolution for
# the values produced in 1 second period. If you need more 
# discrete points - decrease the duration, and vise-verse.
sleep_duration = 50

# automatically calculated step - the difference between
# two discrete points of the wave.
step = 2 * pi * freq / (MS_IN_SECOND / sleep_duration)

i = 0
while(True):
    val = zero + amplitude * sin(i)
    pwm.setPWM(0, 0, int(val))
    i += step
    sleep(sleep_duration)