用于定时风扇控制的 Python 模块 "Schedule" 有问题

Problem with Python module "Schedule" for timed fan control

我写了下面的代码来控制一个风扇。

import schedule
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)              
GPIO.setup(14, GPIO.OUT) #set pin 14 as output

def aan(): 
    GPIO.output(14,0)    #set pin 14 to "low", fan comes on
    print(time.strftime("%H:%M")+" aan") #print time in hours and minutes, aan=on in Dutch

def uit():
    GPIO.output(14,1)    #set pin 14 to "high", fan goes off
    print(time.strftime("%H:%M")+" uit") #print time in hours and minutes, uit=off in Dutch
    
schedule.every().hour.at(":00").do(aan)
schedule.every().hour.at(":01").do(uit)
schedule.every().hour.at(":15").do(aan)
schedule.every().hour.at(":16").do(uit)
schedule.every().hour.at(":30").do(aan)
schedule.every().hour.at(":31").do(uit)
schedule.every().hour.at(":45").do(aan)
schedule.every().hour.at(":46").do(uit)

try:
    while True:
        if int(time.strftime("%H")) in range(9,21): #only preform the schedule between 9 and 21 hours
            schedule.run_pending()
            time.sleep(1)
        else:
            time.sleep(1)

finally:
   print("clean up") 
   GPIO.cleanup() # cleanup all GPIO pins

它应该运行 在时间表中的 4 个指定时间持续 1 分钟。该代码有效,但我从终端的打印中注意到它也在 09:00 上出现了 4 次(见下文)。

09:00 aan
09:00 uit
09:00 aan
09:00 uit
09:00 aan
09:00 uit
09:00 aan
09:00 uit

我试过更改 :00“开启”和 :01“关闭”时间表,但这似乎没有什么不同。如果有人能帮助我,我将不胜感激!

我会以稍微不同的方式解决这个问题,如下图所示:

def fan():
    # Operate the fan 
    on_time = 60  # Runtime in seconds
    if int(time.strftime("%H")) in range(9,21): #only preform the schedule between 9 and 21 hours
        GPIO.output(14,0)    #set pin 14 to "low", fan comes on
        print(f'Turn on Fan at {time.strftime("%H:%M")}') 
        time.sleep(on_time)
        GPIO.output(14,1)    #set pin 14 to "high", fan goes off
        print(f'Turn Off Fan at {time.strftime("%H:%M")}')   

然后:

schedule.every().hour.at(":00").do(fan)
while True:
        run_pending()
        time.sleep(1)

else:
   print("clean up") 
   GPIO.cleanup() # cleanup all GPIO pins

我无法完全测试此代码,因为我没有您的风扇设备,但这似乎仅适用于打印语句。