0

So im trying to make my Robot move by itself and then make a turn until the path is clear using the HC-SR04 Ultrasonic Rangefinder, but my problem is that my readings are off with a large margin, about 100 cm this is the code that I am running. What should I try? is the Rangefinder damaged?

import RPi.GPIO as GPIO
import gpiozero
import time

GPIO.setmode(GPIO.BOARD)

Motor1A = 12
Motor1B = 16
Motor1E = 18

Motor2A = 11
Motor2B = 13
Motor2E = 15

GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)

GPIO.setup(Motor2A,GPIO.OUT)
GPIO.setup(Motor2B,GPIO.OUT)
GPIO.setup(Motor2E,GPIO.OUT)

TRIG = 16
ECHO = 20

trigger = gpiozero.OutputDevice(TRIG)
echo = gpiozero.DigitalInputDevice(ECHO)

def get_distance(trigger, echo):
    trigger.on()
    time.sleep(0.00001)
    trigger.off()

    while echo.is_active == False:
        pulse_start = time.time()

    while echo.is_active == True:
        pulse_end = time.time()

    pulse_duration = pulse_end - pulse_start

    distance = 34300 * (pulse_duration/2)

    round_distance = round(distance,1)

    print("Distance: ", round_distance)

    return(round_distance)

while True:
    dist = get_distance(trigger,echo)
    if dist <= 16:
        print ("Changing route")
        GPIO.output(Motor1A,GPIO.LOW)
        GPIO.output(Motor1B,GPIO.HIGH)
        GPIO.output(Motor1E,GPIO.HIGH)

        GPIO.output(Motor2A,GPIO.HIGH)
        GPIO.output(Motor2B,GPIO.LOW)
        GPIO.output(Motor2E,GPIO.HIGH)
    else:
        GPIO.output(Motor1A,GPIO.HIGH)
        GPIO.output(Motor1B,GPIO.LOW)
        GPIO.output(Motor1E,GPIO.HIGH)

        GPIO.output(Motor2A,GPIO.HIGH)
        GPIO.output(Motor2B,GPIO.LOW)
        GPIO.output(Motor2E,GPIO.HIGH)
  • 1
    Could be dozens of reasons. I suggest you use RPi.GPIO or gpiozero. Not both. If you want an answer to your question you need to give details of the actual versus expected readings as well as photos of your wiring. – joan Aug 17 at 10:28
  • Your sensor might be aged. My quick and dirty troubleshooting approach is to find another similar sensor to compare and cross calibrate. – tlfong01 Aug 17 at 12:17
  • Or object too small or not reflective, or not ... , not, ... BTW, are your senor mounted on a car with six motors? No motors might help. – tlfong01 Aug 17 at 12:55

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.