使用动作之间的延迟

时间:2017-08-15 08:28:16

标签: python function loops delayed-execution

我试图使用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

1 个答案:

答案 0 :(得分: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秒。