2017-08-15 62 views
0

我正試圖使用​​pyserial庫來溝通python到arduino。在下面的代碼中,我只是顯示了幾個函數,我試圖根據這些函數返回的值打開或關閉LED。我想要做的是,當python告訴打開LED,我想讓LED燈開啓7秒,但在那段時間裏,如果set_forbidden_list返回任何值,我希望LED立即關閉並保持關閉狀態直到set_forbidden_list變空。任何幫助將非常感激。使用動作之間的延遲

def openthedoor(set_accepted_list,set_list_ant_id,set_forbidden_list,set_accepted_list_frozen): 
    if(((len(set_accepted_list)) >0) & (set_forbidden_list == set()) & ((set_accepted_list_frozen == None) or ((set_accepted_list_frozen & set_accepted_list)== set_accepted_list))): 
     use_door(1) 
     delay_for_goodant(1) 
     print "open the gate" 
    else: 
     use_door(0) 
     delay_for_goodant(0) 
     print "close the gate" 
    set_for_comparison = set(set_accepted_list & set_list_ant_id) 
    list_for_comparison = list(set_for_comparison) 
    return set_for_comparison,list_for_comparison  

def establishing_connection(): 
    print ser.read(); 
    ser.write('1') 

last_action = -1 

def use_door(activate): 
    global last_action 
    if(last_action != activate): 
     send_data(activate) 
    last_action = activate 

def send_data(data): 
    if (data ==0): 
     print "manga" 
     return True 
    else: 
     print "muringa" 
     return False 

def delay_for_goodant(data): 
    print "thenga" 
    global ser 
    try: 
     if (ser == None): 
      ser = serial.Serial("COM1",9600,timeout = 0) 
      print "reconnect" 
      incoming_data = ser.readline() 
     else:       ## for turning off the LED 
      ser.write('0') 
      time.sleep(0) 
      incoming_data2 = ser.readline() 
    except IOError: 
     ser = None 

回答

0

而不是使用time.sleep(7)完全停止7秒,你可以做什麼程序是睡一個循環不斷檢查是否有在set_forbidden_​​list任何值內幾毫秒。另外time.sleep(0)與不寫它完全一樣好。

for i in range(700): 
    time.sleep(0.01); 
    if len(set_forbidden_list)==0: 
     #switchon the LED 

上面的循環運行700次,而每次它等待0.01秒,總共高達7秒。

+0

這也類似於time.sleep()。系統休眠7秒鐘。所以在'set_forbidden_​​list'返回一個值的睡眠時間,它不會使LED變暗。 – mudaliyar