2017-03-09 182 views
0

我真的很努力完成我的代碼的最後一部分。while循環內if語句條件

這是一些背景。該代碼通過超聲波傳感器查找位於其前面的對象,如果存在,則通過http_get將其記錄到Internet數據庫中,如果沒有對象,則每隔2秒查看一次。

我已經把所有東西打蠟了,除非有人長時間留下物體。看看代碼,它會有道理。 (這只是代碼的一部分)。

while True: 

#Setting the pins and taking the reading. 
#In a while loop so that it continually does it. 

    trig=machine.Pin(5,machine.Pin.OUT) 
    trig.low() 
    time.sleep_ms(2) 
    trig.high() 
    time.sleep_ms(10) 
    trig.low() 
    echo=machine.Pin(4,machine.Pin.IN) 
    while echo.value() == 0: 
    pass 
    t1 = time.ticks_us() 
    while echo.value() == 1: 
    pass 
    t2 = time.ticks_us() 
    cm = (t2 - t1)/58.0 
    print(cm) #cm is the output that I use to determine if the object is there or not. 

    if cm >= 15: #This means there is nothing there. 
     time.sleep(1) 
    elif cm <= 15: #Because the distance is less than 15cm, something is there, and it logs it. 
     http_get('URL') 
     time.sleep(5) 

所以,現在,你可以看到,如果有人離開對象爲有不到5秒鐘,將只記錄一次(對象的數量是至關重要的)。需要注意的是,如果有人在那裏忘記了物體,或者在那裏留下了10秒,它會記錄兩次,這是我們不能擁有的。所以,我需要類似這樣的東西,但語法正確。

def checking(): 

    if cm >= 15: 
     time.sleep(1) 
    elif cm <= 15: 
     http_get('URL') 
     time.sleep(5) 

     while: cm <= 15: 
      keep sensing but not logging. 
      then, if the distance changes to back to more than 15cm, 
      return back to the top. (because the object would be gone). 

我希望這是明確的足夠你們。

讓我知道是否需要有任何澄清的地方。

回答

-1

使用標誌檢查的距離去超過15或不

flag_reset = 0 

while True: 

    (your_code) 

    if cm >15: 

     time.sleep(1) 
     flag_reset = 0 

    elif cm <=15 and flag_reset == 0: 

     do_something() 
     flag_reset = 1 
+0

這一工程 - 感謝這麼多。我不確定爲什麼 - 謹慎解釋? – LukeVenter

+0

嘗試思考每次對象到達時執行什麼,保持幾秒鐘,然後再次消失。 – nekomatic

+0

@nekomatic。感謝編輯。 –