Issue with Weatherproof Ultrasonic Sensor

Having some issues getting the DFRobot weatherproof ultrasonic sensor set up with a Raspberry Pi Zero. I have tried several configurations and variants of code and am getting either unusual or no results.

For example:

using gpiozero and the setup and code from https://projects.raspberrypi.org/en/projects/physical-computing/14 I get a stream of similar measurements in the 17-18cm range irrespective of distance.

using https://pimylifeup.com/raspberry-pi-distance-sensor/ It reaches print(“Calculating distance”) and then does nothing

using https://www.raspberrypi-spy.co.uk/2012/12/ultrasonic-distance-measurement-using-python-part-1/ just hangs

With the second setup from pimylifeup, I achieved one single reading which looked successful.

The ultrasonic sensor is also acting strangely. The LED has, at various times, lit up and stayed lit, flickered to indicate trigger at appropriate times but still returned no distance, and stayed dark. There have also been several occasions where the ultrasonic device has been emitting a constant sound.

Any suggestions welcome!

Hi Leon

Just so we are on the same page is this the sensor you are using?
https://core-electronics.com.au/weatherproof-ultrasonic-sensor-with-separate-probe.html
That is a 5V sensor so it will need to be powered with 5V and also have the inputs and outputs scaled to 3.3V so they can still safely interface with the Pi.

Morning Clinton

That’s the one. I have the VCC connected to the 5V out pin on the pi, and a 1k and 2k resistor voltage divider in between echo and gnd.

Leon

After a bit of a dig I found in the product wiki that it appears that this unit needs a different timing to get the ranger to trigger. This DFR wiki page should help you get it working.
https://wiki.dfrobot.com/Weather_-_proof_Ultrasonic_Sensor_with_Separate_Probe_SKU___SEN0208

Thanks,

Starting to suspect this is a hardware issue. I have pulled it apart and used an Arduino Uno wired exactly as the wiki shows, and copy/pasted the code from the wiki into Arduino IDE and uploaded.

I can hear the tell-tale click of the ultrasonic, but the monitor is showing an unchanging stream of 0cm. Obviously the echo is not picking anything up, as it seems that the trigger is working.

And one more attempt on the Arduino with the code from https://forum.arduino.cc/index.php?topic=448906.0 which uses the same timings (2us and 10us) -

Now a reading of 22cm over and over, with occasional drop outs to 9cm and 3cm…

Very strange!

Hi Leon,

Please post the code that you are using here rather than the links so we can look over it. Remember to use the preformatted text option “</>”

Hi, as I said, I’ve tried a few variants. I’ll post them in a couple of posts. This is the code using RPi.GPIO and connected to the Pi Zero on a breadboard with a 330 and 470 ohm resistor voltage divider.

#!/usr/bin/python
import RPi.GPIO as GPIO
import time

try:
    GPIO.setmode(GPIO.BOARD)

    PIN_TRIGGER = 7
    PIN_ECHO = 11

    GPIO.setup(PIN_TRIGGER, GPIO.OUT)
    GPIO.setup(PIN_ECHO, GPIO.IN)

    GPIO.output(PIN_TRIGGER, GPIO.LOW)
    time.sleep(0.000002)
    GPIO.output(PIN_TRIGGER, GPIO.HIGH)
    time.sleep(0.00001)
    GPIO.output(PIN_TRIGGER, GPIO.LOW)

    while GPIO.input(PIN_ECHO)==0:
        pulse_start_time = time.time()

    while GPIO.input(PIN_ECHO)==1:
        pulse_end_time = time.time()
    

    pulse_duration = pulse_end_time - pulse_start_time
    distance = round(pulse_duration * 17150, 2)
    print("Distance: "+str(distance)+"cm")

finally:
    GPIO.cleanup()

This is another variant using RPi.GPIO

import RPi.GPIO as GPIO # Import the GPIO Library
import time # Import the Time library
# Set the GPIO modes
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define GPIO pins to use on the Pi
pinTrigger = 23
pinEcho = 24
print("Ultrasonic Measurement")
# Set pins as output and input
GPIO.setup(pinTrigger, GPIO.OUT) # Trigger
GPIO.setup(pinEcho, GPIO.IN) # Echo
try:
    # Repeat the next indented block forever
    while True:
        # Set trigger to False (Low)
        GPIO.output(pinTrigger, False)
        # Allow module to settle
        time.sleep(0.5)
        # Send 10us pulse to trigger
        GPIO.output(pinTrigger, True)
        time.sleep(0.00001)
        GPIO.output(pinTrigger, False)
        # Start the timer
        StartTime = time.time()
        # The start time is reset until the Echo pin is taken high (==1)
        while GPIO.input(pinEcho)==0:
            StartTime = time.time()
            # Stop when the Echo pin is no longer high - the end time
        while GPIO.input(pinEcho)==1:
            StopTime = time.time()
            # If the sensor is too close to an object, the Pi cannot
            # see the echo quickly enough, so it has to detect that
            # problem and say what has happened
            if StopTime-StartTime >= 0.04:
                print("Hold on there! You're too close for me to see.")
                StopTime = StartTime
                break

        # Calculate pulse length
        ElapsedTime = StopTime - StartTime
        # Distance pulse travelled in that time is
        # time multiplied by the speed of sound (cm/s)
        Distance = ElapsedTime * 34326
        # That was the distance there and back so halve the value
        Distance = Distance / 2
        print("Distance: %.1f cm" % Distance)
        time.sleep(0.5)

# If you press CTRL+C, cleanup and stop
except KeyboardInterrupt:
    # Reset GPIO settings
    GPIO.cleanup()

One from raspberrypi.org using gpiozero

from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(echo=17, trigger=4)

try:
    while True:
        print("Distance to nearest object is: "+str(sensor.distance)+"m")
        sleep(5)

except KeyboardInterrupt:
    print("Exit")

And the sketch for Arduino Uno which comes from the DFRobot Wiki suggested by Clinton

```
#define ECHOPIN 2// Pin to receive echo pulse
#define TRIGPIN 3// Pin to send trigger pulse
void setup(){
    Serial.begin(9600);
    pinMode(ECHOPIN, INPUT);
    pinMode(TRIGPIN, OUTPUT);
    digitalWrite(ECHOPIN, HIGH);
}
void loop(){
    digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
    delayMicroseconds(2);
    digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
    delayMicroseconds(10);
    digitalWrite(TRIGPIN, LOW); // Send pin low again
    int distance = pulseIn(ECHOPIN, HIGH,26000); // Read in times pulse
    distance= distance/58;
    Serial.print(distance);
    Serial.println("   cm");
    delay(50);// Wait 50mS before next ranging
}
```

So it has all been zero except for the one from the Arduino forum that was mostly 22 with drops to 9 and 3 cms? Have you tried printing the start and stop times in a few of these to see if there is something strange going on there? What surface are you using to test the sensor distance against?

I have tried removing all superfluous code just in case there was an issue with the pi outstripping the sensor or interfering. I have not tried printing stop and stop times.

I’ve tested against a variety of surfaces from my hand, to the wall, to the ceiling, floor, table, and various items around my desk, all with the same results.

Given that the LED is flashing (on the Uno) and I can hear the click, it definitely seems as though the trigger is working, but the echo is not receiving anything. The only difference came when I changed pins of the arduino from 2 and 3 to 12 and 13, though as I said it just went from all 0s to all 22s, so still not much use!

20cm seems to be close to the minimum range of the sensor, I’m not sure which code you used from that forum but maybe it had the minimum in there.
I found a YouTube video of someone who has one working with git code that might be worth a shot.
If it is still not playing nice, it may be hardware and you should reply to your order email with a link to this thread and some photos of the distance sensor.

1 Like

Ok I tried one more configuration with the pi using different code which incorporated a timeout if the echo didn’t read. It just returns multiple # and periodic readings of 19.5cm irrespective of where the sensor is pointing. The code this time came from https://raspberrypi.stackexchange.com/questions/33955/how-to-use-jsn-sr04t-on-a-raspberry-pi

Won’t paste the code here as the indents get all messed up and I haven’t the time to reformat.

Thanks for the help but looks like it’s time to think about swapping the sensor.

I don’t know if all your code has this kind of test in it
if StopTime-StartTime >= 0.04:

This looks wrong to me. I think the right test is .le. not .ge. (Sorry can’t find the arrows on my android keyboard)

Sorry not exactly sure what you’re saying, and also not sure which part of my code you are referring to

In your post “another variant using RPi.GPIO”

Part of the code is

#stop when the Echo pin is no longer high - the end time 
while GPIO.input(pinEcho)==1: StopTime = time.time() 
# If the sensor is too close to an object, the Pi cannot 
# see the echo quickly enough, so it has to detect that 
# problem and say what has happened 
if StopTime-StartTime >= 0.04: 
    print("Hold on there! You're too close for me to see.") 
    StopTime = StartTime break

The test on the length of pulse looks backwards to me. The test in the code is >= 0.04:
I think it should be <=0.04

If an object is too close,

Oh I see, thanks. That’s sort of the opposite of a timeout I suppose. In the end the most reliable looking code is the one in my final post with the link, but it still doesn’t work

Hi Leon,

Try removing this from your last shared sketch
“digitalWrite(ECHOPIN, HIGH)”
It’s strange that you would be receiving 0cm with each of these. Try changing your timeout thresholds on the code that always returns 19.5 and see if that fixed value changes.

Also, have you tried turning the trim pot on the back to see if that changes your results?