Raspberry pi按钮延迟到中继的时间

时间:2017-06-30 04:06:22

标签: python if-statement raspberry-pi

我是Raspberry pi和python的新手,并且在使用某些代码时遇到了一些麻烦 我希望按下一个按钮并使与该按钮对应的gpio引脚触发继电器打开一段给定的时间然后关闭。我有它使用下面的代码,但通过使用'time.sleep(我的变量)'它持有覆盆子pi持续时间,我无法做任何其他事情。 我所追求的是能够按下一个按钮并使继电器动作10秒钟,并且在那10秒内能够按下另一个按钮来触发另一个继电器并执行相同的操作而不会占用pi

下面的代码首先检查input_state_LHS是否等于false,然后清除LCD显示,将文本写入LCD的一行,然后在下一行写入我的变量值(LHS_feedtime),然后用在下一行time.sleep上的时间,这是我想要摆脱的位,但我无法找出代码来做到这一点。

if input_state_LHS == False:
        ## calls the LCD_Clear function which has to be in the same folder as this file
        mylcd.lcd_clear()
        mylcd.lcd_display_string("LHS Feedtime",1,2)
        mylcd.lcd_display_string(str(round(LHS_feedtime, 2)) + " sec" , 2,5)
        GPIO.output(27, GPIO.input(12) )
        time.sleep(LHS_feedtime)
        mylcd.lcd_clear()
        mylcd.lcd_display_string("Flatson Feeding", 1)
        mylcd.lcd_display_string("Systems", 2,4)
        GPIO.output(27, GPIO.input(12) )
        menuitem = 0

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您需要的功能在Python标准库类threading.Timer中。启动计时器时,它会启动另一个线程,该线程包括一个时间延迟,然后调用您指定的函数。与time.sleep()相反,在此时停止主线程,使用Timer,主线程将继续运行。

这大致是你想要的:

from threading import Timer

def turn_off_lcd():
        mylcd.lcd_clear()
        mylcd.lcd_display_string("Flatson Feeding", 1)
        mylcd.lcd_display_string("Systems", 2,4)
        GPIO.output(27, GPIO.input(12) )

if input_state_LHS == False:
        ## calls the LCD_Clear function which has to be in the same folder as this file
        mylcd.lcd_clear()
        mylcd.lcd_display_string("LHS Feedtime",1,2)
        mylcd.lcd_display_string(str(round(LHS_feedtime, 2)) + " sec" , 2,5)
        GPIO.output(27, GPIO.input(12) )
        t = Timer(LHS_feedtime, turn_off_led)
        t.start()
        menuitem = 0

答案 1 :(得分:0)

在这里,这将不断循环代码,直到10秒过去。但它会不断打印“10秒没有通过”(你可以删除这一行。)正如你将注意到的,这段代码不使用time.sleep(),所以不会保持脚本。

import time

#Get the initial system time
timebuttonpressed = time.strftime("%H%M%S")
elapsedtime = time.strftime("%H%M%S")

while True:
    elapsedtime = time.strftime("%H%M%S")
    if input_state_LHS == False:
        #Get the new system time, but only set timesample2
        timebuttonpressed = time.strftime("%H%M%S")

        ## calls the LCD_Clear function which has to be in the same folder as this file
        mylcd.lcd_clear()
        mylcd.lcd_display_string("LHS Feedtime",1,2)
        mylcd.lcd_display_string(str(round(LHS_feedtime, 2)) + " sec" , 2,5)
        GPIO.output(27, GPIO.input(12) )

    #Check if 10 seconds have passed
    if((int(elapsedtime) - int(timebuttonpressed)) == 10):
        timebuttonpressed = time.strftime("%H%M%S")
        mylcd.lcd_clear()
        mylcd.lcd_display_string("Flatson Feeding", 1)
        mylcd.lcd_display_string("Systems", 2,4)
        GPIO.output(27, GPIO.input(12) )
        menuitem = 0

    print("10 seconds havent passed...")