计时器不会跳转到默认值或下一个间隔

时间:2017-01-01 21:00:35

标签: python servo adafruit

在以下代码中。代码确实运行单独的行。 区间1线将在21.00和21.05hr之间运行 Interval 2线将在22.00和22.05hr之间运行 标准脉冲线将在其他时间范围内运行。

问题: 代码确实不从区间1跳 - >标准脉冲 - >在代码开始运行时,它会一直运行时间帧。

有人可以帮我解决这个python时间问题吗?

这是代码:

from __future__ import division
from datetime import datetime, time

# Import the PCA9685 module.
import Adafruit_PCA9685

now = datetime.now()

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

servo_min = 300  # Min pulse length out of 4096
servo_max = 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.set_pwm(channel, 0, pulse)

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

while True:
    if now.time() >= time(21, 00, 00) and now.time() <= time(21, 05, 0):
        print "Interval 1"
        pwm.set_pwm(0, 0, servo_min)
    elif now.time() >= time(22, 00, 0) and now.time() <= time(22, 05, 0):
        print "Interval 2"
        pwm.set_pwm(0, 0, servo_min)
    else:
       print "Standard pulse"
       pwm.set_pwm(0, 0, servo_max)

1 个答案:

答案 0 :(得分:2)

通过文档,datetime.now()返回当前时间,因此now变量始终只在您启动程序时存储。尝试将now = datetime.now()置于你的while循环中。

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

while True:
    now = datetime.now()
    if now.time() >= time(21, 00, 00) and now.time() <= time(21, 05, 0):
        print "Interval 1"
        pwm.set_pwm(0, 0, servo_min)
    elif now.time() >= time(22, 00, 0) and now.time() <= time(22, 05, 0):
        print "Interval 2"
        pwm.set_pwm(0, 0, servo_min)
    else:
        print "Standard pulse"
        pwm.set_pwm(0, 0, servo_max)