1

I've placed the sensor at top of tank and want to measure distance to the liquid.
The code following code runs but returns cosistent but incorrect values

'''

import RPi.GPIO as GPIO
import time

try:
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    TRIG = 23
    ECHO = 24
    maxTime = 1

    while True:
        GPIO.setup(TRIG,GPIO.OUT)
        GPIO.setup(ECHO,GPIO.IN)

        GPIO.output(TRIG,False)

        time.sleep(0.1)

        GPIO.output(TRIG,True)

        time.sleep(0.00001)

        GPIO.output(TRIG,False)

        pulse_start = time.time()
        timeout = pulse_start + maxTime
        while GPIO.input(ECHO) == 0 and pulse_start < timeout:
            pulse_start = time.time()

        pulse_end = time.time()
        timeout = pulse_end + maxTime
        while GPIO.input(ECHO) == 1 and pulse_end < timeout:
            pulse_end = time.time()

        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17165
        distance = round(distance/2.54, 2) 

        print(str(distance)+" inches")
except:
    GPIO.cleanup()

'''

The returned values are consistent but incorrect, since tank height is 44 inches.heres a sample of values

851.36 inches 851.1 inches 851.17 inches 851.31 inches 851.44 inches 851.09 inches 851.3 inches 851.39 inches 850.91 inches 851.27 inches

1
  • Is that a timeout from the sensor? Perhaps it always responds at the same time if no echo is detected. What distance is it rated for? I'm not even sure those sensors work reliably against water.
    – joan
    Aug 31 '20 at 8:28
1

You should move your GPIO.setup() commands outside the while loop, only needed once.

Your duration to distance calculation is wrong, should be:

distance = pulse_duration * 34300 / 2

You should ignore values where the timeout has been applied:

    ignore = False
    pulse_start = time.time()
    timeout = pulse_start + maxTime
    while GPIO.input(distance_echo)==0 and pulse_start < timeout:
        pulse_start = time.time()
    if pulse_start >= timeout:
        ignore = True
        
    pulse_end = time.time()
    timeout = pulse_end + maxTime
    while GPIO.input(distance_echo)==1 and pulse_end < timeout:
        pulse_end = time.time()
    if pulse_end >= timeout:
        ignore = True

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.