0

I am currently working on a ultrasonic sensor (and Temperature but that is not important for this question) on my raspberry Pi, This is how I got it set up due to space constraint I am unable to use a breadboard. I have used the ultrasonic sensor before on a Arduino and it was working perfectly fine but I am new to raspberry and python coding so please do correct me if there is anything wrong with what I am doing.

Edit

Yes, I did solder the resistor to the Raspberry Pi it self as the board is only used for this function.

enter image description here

Below is the script that I am using to calculate the distance, it takes the reading of the last 10 value and calculate the average of said values.

import RPi.GPIO as GPIO
import time, sys
import statistics 
GPIO.setmode(GPIO.BCM)


log=__import__("logger")

TRIG = 23
ECHO = 24

log.log("Settng up Distance module...","distance.py")

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
history=[]

total=0
count=0
distance=0
avg=0
dist=[]
distlist=[]
scan=False

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

def status():
    history=[]

    starttime=time.time()
    for i in range(10):
        GPIO.output(TRIG, False)
        time.sleep(0.1)
        #print("Waiting for sensor to settle...")
        #print("Please wait...")

        # ==========
        # GPIO Setup
        # ==========
        GPIO.output(TRIG, True)
        time.sleep(0.00001)
        GPIO.output(TRIG, False)

        #print("Sending...")
        start=time.time()
        pulse_start=start
        while GPIO.input(ECHO)==0 and pulse_start-start<=0.0005:
            pulse_start=time.time()
        if round(pulse_start-start,3)>=0.300:
            print(timeout)
        else:
            #print("Receiving...")
            pulse_end=0
            pulse_duration=0
            while GPIO.input(ECHO)==1 and pulse_duration<2:
                pulse_end=time.time()
                pulse_duration=pulse_end-pulse_start
                #print("Measuring...")

        pulse_duration=pulse_end-pulse_start

        # ====================
        # Calculating Distance
        # ====================
        distance=pulse_duration*17150
        distance=round(distance,2)
        history.append(distance)
    validcount=0
    total=0
    print(history)
    for i in history:
        if i<150:
            validcount+=1
            total+=i
    if validcount>1:
        avg_dist=round(total/validcount,2)
        print("Average distance:",avg_dist)
        if avg_dist<=50:
            return([avg_dist,True,avg_dist,avg_dist])
        else:
            return([avg_dist,False,avg_dist,avg_dist])
    else:
        print("Timeout")
        return([999,False,999,999])
    
while True: print(status()); time.sleep(1)

Below are the readings that I got from the sensor when I am standing close to it.

Average distance: -4590081542678.66
[-4590081542678.66, True, -4590081542678.66, -4590081542678.66]
[185.12, 341.6, 17.71, 188.05, 185.94, 185.55, 188.08, 185.58, 184.6, 185.09]
Timeout
[999, False, 999, 999]
[185.58, 186.09, 185.2, 184.4, 185.11, 185.6, 185.56, 186.47, 186.81, 187.24]
Timeout
[999, False, 999, 999]
[187.71, 186.07, 185.59, 185.6, 185.12, 185.61, 185.56, 186.83, 186.41, 184.68]
Timeout
[999, False, 999, 999]
[2243.37, 2245.42, 22.79, 24.57, 2245.48, 2243.77, 2245.33, 2245.12, 2245.18, 2245.28]
Average distance: 23.68
[23.68, True, 23.68, 23.68]
[2244.04, 2246.04, 348.54, 348.56, 348.58, 349.46, 349.44, 348.51, 350.32, 348.05]
Timeout
[999, False, 999, 999]
[348.65, 104.17, 103.76, 100.39, 348.94, 99.49, 348.99, 348.5, 348.14, 348.59]
Average distance: 101.95
[101.95, False, 101.95, 101.95]
[2244.2, 2245.87, 2246.03, 2246.21, 2243.82, 2246.09, 2245.4, 2245.17, 2245.98, 2245.81]
Timeout
[999, False, 999, 999]
[2243.19, 2245.8, 2245.89, 2245.82, 2245.66, 2245.76, 2245.65, 2245.69, 2245.58, 2245.89]
Timeout
[999, False, 999, 999]
[2242.55, 2245.85, 25.14, 24.11, 23.9, 23.2, 2243.35, 2246.04, 2246.33, 2245.93]
Average distance: 24.09
[24.09, True, 24.09, 24.09]
[2243.13, 19.03, 18.33, 17.64, 2246.25, 2244.32, 2245.29, 2245.44, 2245.78, 2246.06]
Average distance: 18.33
[18.33, True, 18.33, 18.33]
[2242.59, 2245.8, 2245.47, 2245.62, 2245.73, 2245.8, 2245.86, 2246.05, 2246.22, 2245.91]
Timeout
[999, False, 999, 999]
[2243.81, 2246.36, 2246.1, 2246.07, 2246.09, 2246.05, 2246.13, 2245.92, 2246.07, 2246.3]
Timeout
[999, False, 999, 999]
[2243.94, 2246.02, 2246.03, 2246.21, 2246.15, 2245.89, 2245.9, 2245.99, 2245.96, 2245.99]
Timeout
[999, False, 999, 999]
[2242.87, 2245.97, 18.78, 17.93, 17.81, 2243.93, 2246.01, 2245.86, 2245.95, 2246.04]
Average distance: 18.17

So what my program does is take the last 10 digits from the sensor and calculate the average of that value in the list but as you can see even when I am standing close to it the readings are over the range of THOUSANDS.

I am aware of this questionDistance Sensor (HC-SR04) Recording Inconsistent Values page and while it did give me insight to the problem it is unfortunate no solution has been found.I am speculating however that the problem lies in the pulse triggered for over 6 seconds which results in a high value as mentioned in the linked page but I am unsure if that's the only problem or how to fix it.

I would appreciate any feedback, suggestion or answer. Thank you in advance.

yong jie
  • 85
  • 10
  • 1
    Not sure how long the echo times are that you are trying to measure, but you may have difficulty if they are too short on the Raspberry Pi which is non real-time and runs a Linux kernel which is busy doing other things - unlike an Arduino which is just a microcontroller dedicated purely to doing just your loop and no other processes... – Mark Setchell Nov 20 '20 at 09:33
  • @MarkSetchell Sorry for the late reply, I am still very new to all this so if i understand correctly by what you're saying, i have to play around with the echo time to make it work? As currently I am quite lost on what I am suppose to do. – yong jie Nov 25 '20 at 07:45

1 Answers1

0

so after doing some troubleshooting on my part I have found that the solder on my resistor to on the raspberry pi board was not soldered on properly, so I after giving it proper solder, it was giving consistent readings now but the issue with high value did not change. it will still give high value so what I did to work around this problem is by having a filter, to filter out high value.

    for i in history:
    if i<150:
        validcount+=1
        total+=i
if validcount>1:
    avg_dist=round(total/validcount,2)
    print("Average distance:",avg_dist)
    if avg_dist<=50:
        return([avg_dist,True,avg_dist,avg_dist])
    else:
        return([avg_dist,False,avg_dist,avg_dist])
else:
    print("Timeout")
    return([999,False,999,999])

and by speeding up the rate of which the data is being read.

  for i in range(10):
    GPIO.output(TRIG, False)
    time.sleep(0.1)
    #print("Waiting for sensor to settle...")
    #print("Please wait...")

    # ==========
    # GPIO Setup
    # ==========
    GPIO.output(TRIG, True)
    time.sleep(0.00001) #lowered the delay on the reading
    GPIO.output(TRIG, False)

    #print("Sending...")
    start=time.time()
    pulse_start=start
    while GPIO.input(ECHO)==0 and pulse_start-start<=0.0005:
        pulse_start=time.time()
    if round(pulse_start-start,3)>=0.300:
        print(timeout)
    else:
        #print("Receiving...")
        pulse_end=0
        pulse_duration=0
        while GPIO.input(ECHO)==1 and pulse_duration<2:
            pulse_end=time.time()
            pulse_duration=pulse_end-pulse_start
            #print("Measuring...")

    pulse_duration=pulse_end-pulse_start

    # ====================
    # Calculating Distance
    # ====================
    distance=pulse_duration*17150
    distance=round(distance,2)

This effectively gave faster reading where if one valid value appears it will ignore all the sudden high values. I hope this helps with other people having the same problem.

yong jie
  • 85
  • 10