Ultrasonic Distance Sensor - RCWL-1601 -

Hi All,

I am trying to get the sensor working on a raspberry pi 3b using the code below. However, receiver is consistently energising the echo pin. As the echo pin is constantly high, the code is stuck at the calculation line.

Just wondering if I have missed anything?

import RPi.GPIO as GPIO
import time

try:
    GPIO.setmode(GPIO.BOARD)

    PIN_TRIGGER = 18
    PIN_ECHO = 22
    

    GPIO.setup(PIN_TRIGGER, GPIO.OUT)
    GPIO.setup(PIN_ECHO, GPIO.IN)
    
    GPIO.output(PIN_TRIGGER, GPIO.LOW)
    
    print("Waiting for sensor to settle")
    print(GPIO.input(PIN_ECHO))
    time.sleep(2)

    print ("Calculating distance")
    print(GPIO.input(PIN_ECHO))  # This line should print 0 but it is printing 1.
    
    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:",distance,"cm")

finally:
    GPIO.cleanup()

Regards,
Fu

2 Likes

Hi Fu,

What does your circuit look like? I came across this guide that PiHut made for use on a Raspberry Pi: HC-SR04 Ultrasonic Range Sensor on the Raspberry Pi | The Pi Hut

For timing dependent stuff like this I would outsource it to a microprocessor, like a Pico or use a fully baked sensor with one embeded like the PiicoDev Distance sensor

1 Like