0

在下面的代码中。该代码确实运行所有单独的行。间隔 1 线将在 21.00 和 21.05 小时之间运行 间隔 2 线将在 22.00 和 22.05 小时之间运行 标准脉冲线将在所有其他时间范围内运行。

问题:代码没有从间隔 1 跳 -> 标准脉冲 -> 间隔 2 等。它继续运行代码开始运行时的时间范围。

有人可以帮我解决这个 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)
4

1 回答 1

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)
于 2017-01-01T21:20:14.427 回答