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 I get a stream of similar measurements in the 17-18cm range irrespective of distance.

using It reaches print(“Calculating distance”) and then does nothing

using 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?
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.


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.


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

import RPi.GPIO as GPIO
import time


    PIN_ECHO = 11



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


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
# 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
    # Repeat the next indented block forever
    while True:
        # Set trigger to False (Low)
        GPIO.output(pinTrigger, False)
        # Allow module to settle
        # Send 10us pulse to trigger
        GPIO.output(pinTrigger, True)
        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

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

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

One from using gpiozero

from gpiozero import DistanceSensor
from time import sleep

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

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

except KeyboardInterrupt:

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(){
    pinMode(ECHOPIN, INPUT);
    pinMode(TRIGPIN, OUTPUT);
    digitalWrite(ECHOPIN, HIGH);
void loop(){
    digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
    digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
    digitalWrite(TRIGPIN, LOW); // Send pin low again
    int distance = pulseIn(ECHOPIN, HIGH,26000); // Read in times pulse
    distance= distance/58;
    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

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?