0

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.

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). The caveat is, if someone forgets the object there, or leaves it there for 10s, it will log twice, which we can't have. 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.

LukeVenter
  • 439
  • 6
  • 20

1 Answers1

-1

Use a flag to check that the distance went to more than 15 or not

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
nekomatic
  • 5,988
  • 1
  • 20
  • 27
Abhimanyu singh
  • 397
  • 3
  • 9