2017-06-30 94 views
0

我是樹莓派和python的新手,並且對某些代碼有點麻煩 我希望按下一個按鈕並讓該按鈕對應的gpio引腳觸發一個繼電器打開一段時間然後關閉。我使用下面的代碼工作,但是通過使用'time.sleep(my-variable)',它在一段時間內保留了樹莓派,我無法做任何其他事情。 我所追求的是能夠按下一個按鈕,讓繼電器動作10秒鐘,並在這10秒鐘內能夠按另一個按鈕來觸發另一個繼電器,並執行相同的操作,而不會捆綁piRaspberry 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 

感謝您的幫助

回答

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 
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...")