【问题标题】:using delay between actions使用动作之间的延迟
【发布时间】:2018-01-23 03:45:49
【问题描述】:

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

【问题讨论】:

    标签: python function loops delayed-execution


    【解决方案1】:

    除了使用 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 秒。

    【讨论】:

    • 这也类似于 time.sleep()。系统休眠 7 秒。所以在set_forbidden_list返回值的睡眠时间内,它不会使LED变暗。
    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2012-02-08
    • 2022-08-13
    • 1970-01-01
    • 2016-07-31
    相关资源
    最近更新 更多