计时器不跳到默认值或下一个

2024-05-14 09:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中。代码确实运行所有单独的行。 区间1线路将在21.00和21.05小时之间运行 区间2线路将在22.00和22.05小时之间运行 标准脉冲线将在所有其他时间段上运行

问题: 代码不存在,即不从间隔1跳转->;标准脉冲->;间隔2等。它保持代码开始运行的时间范围

有人能帮我解决这个时间问题吗

代码如下:

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)

Tags: ofthe代码importdatetimetimeminnow
1条回答
网友
1楼 · 发布于 2024-05-14 09:58:44

根据文档,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)

相关问题 更多 >

    热门问题