# HC-SR04 sensor - beginners gpiozero coding problems

New here and to robotics and have encountered my first 2 problems. Following instructions in a book, I have fitted 1 HR-SR04 ultra sound detector but could not get the code given to work, seems to get stuck in the first while loop, so never getting a return time :

import gpiozero
import time

TRIG = 23
ECHO = 24

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

robot = gpiozero.Robot(left=(17,18), right=(27,22))

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)

return(round_distance)

while True:
dist = get_distance(trigger,echo)
if dist <= 15:
robot.right(0.3)
time.sleep(0.25)
else:
robot.forward(0.3)
time.sleep(0.1)


I then found some sample code using RPi.GPIO - which worked,returning values down to 3-4cm, so I know the sensor is ok. I also found the GPIOzero docs and tried the following code:

from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(echo=18, trigger=17)
while True:
print('Distance: ', sensor.distance * 100)
sleep(1)


This code worked in that it would detect an obstacle, but wouldn't return a value less than 10cm.

So my 2 questions (after 2 days of trying to figure this out myself!):

1. Why does the first code not work? I have seen almost exactly the same code repeated elsewhere as how to use the sensor but I just cannot get it to work for me.
2. Why does the second code, using gpiozero not return a value less than 10cm?

I know this is probably very basic stuff, but would greatly appreciate some advice/explanations/pointers.

Your code looks fine but maybe the problem is about your circuit. I dont know if you did but you should connect a voltage divider to HC SR04's Echo pin. The reason for this is that the sensor works at 5V but your Raspberry is working at 3.3V. You can use 2K and 1K resistor with 2K is the one connected to GND. 