How to make this sensor keep taking readings once its when_in_range function has been activated?

12 Views Asked by At

I've got my ultrasonic distance sensor (RCWL-1601) plugged into to my raspberry pi and can get it to show readings no problem. However, I want the program to continuously take readings once the when_in_range function has been activated.

What I struggle with is when I use when_in_range, and define it as a function, the sensor seems to just read one value which is printed over and over again, rather than refreshing the reading.

#!/usr/bin/env python3

from signal import pause
from time import sleep
from gpiozero import DistanceSensor

dist_sensor = DistanceSensor(echo=23, trigger=24, max_distance=4, threshold_distance=0.4)

def dough_in_range(sensor):
        while True:
                print("%.0f" % (dist_sensor.distance *100))
                sleep(1)

def dough_out_of_range(sensor):
        print("Dough out of range")

print("Hit  CTRL+C to exit./n")
dist_sensor.when_in_range = dough_in_range
dist_sensor.when_out_of_range = dough_out_of_range
pause()        

Hit  CTRL+C to exit./n
Dough out of range
40
40
40
40
40
40
40

As you can see the same reading just repeats. I'm aware that the function will not exit as a result of the while loop but I would expect it to carry on taking new readings? Any ideas on how to troubleshoot this?

Thanks

I've tried lots of different loops that I would expect would cause a new reading to be taken but it seems that once the function is activated, no new readings are taken.

0

There are 0 best solutions below