0

I'm making a robot that should avoid obstacles and im using a HC-SR04 to measure distances. My problem is that my readings are off by a large margin. when there is no obstacle in the way I get a constant measure around 100 cm, but when I place an object in front of the reader suddenly it goes up to about 2000 cm. I've tried using the gpiozero library aswell, but same thing keeps happening. Is the reader damaged or what can I try?

import RPi.GPIO as GPIO
import time
import signal
import sys

GPIO.setmode(GPIO.BCM)

pinTrigger = 12
pinEcho = 16

def close(signal, frame):

    GPIO.cleanup() 
    sys.exit(0)

signal.signal(signal.SIGINT, close)


GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)

while True:

    GPIO.output(pinTrigger, True)
    time.sleep(0.00001)
    GPIO.output(pinTrigger, False)

    startTime = time.time()
    stopTime = time.time()

    while 0 == GPIO.input(pinEcho):
        startTime = time.time()

    while 1 == GPIO.input(pinEcho):
        stopTime = time.time()


    TimeElapsed = stopTime - startTime
    distance = (TimeElapsed * 34300) / 2

    print ("Distance: %.1f cm" % distance)
    time.sleep(1)

enter image description here

  • Please try abyz.me.uk/rpi/pigpio/… and report the results. You will need to edit the file at the end, change sonar = sonar_trigger_echo.ranger(pi, 23, 18) to sonar = sonar_trigger_echo.ranger(pi, 12, 16). Run sudo pigpiod before running the script. – joan Aug 28 at 11:13
  • Im gettting values like this: (651 9164) (652 6555) (653 6547) (654 6370) (655 5) (656 8914) (657 8860) (658 8837) it seems to understand though when an object is very close, then I get the reading "5" or "10" @joan – Leobd Aug 28 at 11:43
  • The first number is the reading count, the second number is the echo round trip time in microseconds. Use (micros/1000000)*17015 to get distance in centimetres. Do the figures seem to follow as you slowly move an object to and fro? – joan Aug 28 at 11:53
  • n1 = sonar.read() n2 = n1 / 1000000 n3 = n2 * 17015 print(n3) constantly shows around 100cm, and when an object is around 10cm away it starts to read 0.08 cm @joan – Leobd Aug 28 at 12:08
  • There will be a minimum distance, perhaps it is 10 cms. Are you saying the readings don't vary as you move the object to and fro? – joan Aug 28 at 12:44

Your Answer

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

Browse other questions tagged or ask your own question.