alaudet / hcsr04sensor

Python module for measuring distance and depth (metric or imperial) with a Raspberry Pi and HC-SR04 sensor

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Crashes from time to time

magdesign opened this issue · comments

Thanks for this library.
I am using it on a RPi3 with your metric_distance.py script.

But quite often it crashes with following error:

File "/usr/local/lib/python2.7/dist-packages/hcsr04sensor/sensor.py", line 93, in raw_distance
    time_passed = sonar_signal_on - sonar_signal_off
UnboundLocalError: local variable 'sonar_signal_off' referenced before assignment

Any ideas?

Would help to see your code and know how far you are measuring.

I have seen this happen under two circumstances. If you are measuring distance greater that 12 or 13 feet you will start seeing this error at times. The second time I have seen it is when you take your reading samples too quickly.

Say you increase the speed of the sample readings as follows with sample_wait passed to raw_distance. The default if adding nothing is wait 0.1 seconds. But in some instances it may be better to take these sample readings a little quicker as follows;

value = sensor.Measurement(17, 27)
raw_measurement = value.raw_distance(sample_wait=0.001)

I have seen it throw the error of trying to read samples too quickly. Basically starting the next reading before it received the pulse from the previous reading. you need to play around with it, find that sweet spot. Generally you should not get any any errors using the defaults if your distance is under 10 feet.

EDIT Nevermind, you are using my code. How far are you measuring?

I am measuring distances between 10cm up to 3.2m
and I am measuring in a constant while True loop with sleep (0.1)

Here my code: https://gist.github.com/magdesign/0a0be5a94c9dbd34ece2f14cc60a6e65

So I might increase the sleep value to get rid of the problem...?

That's a good place to start.

Also 3.2 metres is 10 and half feet so depending on the area around it could start to give problems already.

Here is a link to the HCSR04 sensor technical guide. https://www.linuxnorth.org/raspi-sump/HC-SR04Users_Manual.pdf

The ranging distance says 2cm – 400 cm/1" 13ft, but these are cheap sensors and there is some error in there as well.

You may also want to try increasing sample_wait to .3 or .5 if speed of readings is not an issue.

Speed indeed matters.
I think i need to look for another solution.
Thanks for your help.

Hi! Im getting this error too. I looked at code a bit, and wonder, isn't that mean, that beam return too quickly, and while GPIO.input(self.echo_pin) == 0 just not enter? Isn't adding: sonar_signal_off = time.time() before while, solve the problem?
Also according to this post: https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi
GPIO.output(self.trig_pin, GPIO.LOW)
time.sleep(sample_wait)
shouldn't be done only once to warm up sensor and then read readings continuously?