简体   繁体   English

if语句条件内的while循环

[英]while loop within if statement condition

I'm really struggling to finish the last part of my code. 我真的很难完成我的代码的最后一部分。

Here's some background. 这是一些背景。 This code looks for an object that's in front of it via an ultrasonic sensor, and if there is, it logs that onto an internet database via http_get, if there isn't an object, it just keeps looking every 2s. 该代码通过超声波传感器查找在其前面的对象,如果存在,它将通过http_get将其记录到互联网数据库中,如果没有对象,它将每2秒钟查找一次。

I have everything waxed, except for if someone leaves an object there for a long time. 我把所有东西都打蜡了,除非有人在那儿长时间放置物体。 Have a look at the code and it will make sense. 看看代码,这将是有道理的。 (This is just a portion of the code). (这只是代码的一部分)。

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)

So now, as you can see, if someone leaves the object there for less than 5 seconds, that will only log once (the count of the object is crucial). 因此,正如您所看到的,如果有人将对象留在那里的时间少于5秒钟,那只会记录一次(对象的计数至关重要)。 The caveat is, if someone forgets the object there, or leaves it there for 10s, it will log twice, which we can't have. 需要注意的是,如果有人忘记了该对象,或者将该对象留在那里10秒钟,它将记录两次,这是我们无法做到的。 So, I kind of need something like this, but syntactically correct. 所以,我有点需要类似的东西,但是在语法上是正确的。

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).

I hope this is clear enough for you guys. 我希望这对你们来说足够清楚。

Let me know if there needs to be any clarification somewhere. 让我知道是否需要在任何地方进行澄清。

Use a flag to check that the distance went to more than 15 or not 使用标记检查距离是否超过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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM