我是Raspberry pi和python的新手,在使用一些代码时遇到了一些麻烦,我希望按下一个按钮,并让对应于该按钮的gpio引脚触发继电器打开一段给定的时间,然后关闭。我让它在下面的代码中工作,但是通过使用'time.sleep(my-variable)‘,它在这段时间内保持了树莓派,而我不能做任何其他的事情。我追求的是能够按下一个按钮,让继电器动作10秒,在这10秒内,能够按下另一个按钮,启动另一个继电器,并在不捆绑圆周率的情况下做同样的事情。
我下面的代码首先检查input_state_LHS是否等于false,然后清除液晶屏,在一行上向液晶屏写入文本,然后在下一行上写入我的变量(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谢谢你的帮助
发布于 2017-06-30 13:07:09
您需要的功能位于Python标准库类threading.Timer中。当您启动计时器时,它会启动另一个线程,该线程由一个时间延迟组成,然后调用您指定的函数。与在此时停止主线程的time.sleep()不同,有了计时器,主线程将继续运行。
下面是您想要的大致内容:
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发布于 2017-07-03 23:43:56
在这里,这将不断循环代码,直到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...")https://stackoverflow.com/questions/44838432
复制相似问题