2017-03-09 239 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。感谢编辑。 –