3

I tried to use a HC-SR04 distance sensor on my raspberry pi robot, but it doesn't work and I don't know where the problem is. Here is my python code. The program stops in the first while loop.

VCC is connected to PIN 2.
Ground is connected to PIN 6.
Echo is connected to PIN 38 with a 1K resistor.
Trig is connected to PIN 37.

import RPi.GPIO as gp
import time

inputPin = 38 # connect to echo via 1K resistor
outputPin = 37 # connect to trig

gp.setmode(gp.BOARD)
gp.setup(outputPin,gp.OUT)
gp.setup(inputPin,gp.IN)

gp.output(outputPin,True)
time.sleep(0.001)
gp.output(outputPin,False)
time.sleep(0.5)

while gp.input(inputPin) == 0:
        start = time.time()
while gp.input(inputPin) == 1:
        stop = time.time()

currentTime = stop - start
distance = currentTime / 0.000058

print("Distance is " + str(distance) + " cm")
gp.cleanup()
  • If the program stops in the first loop, it is probably because the setup of your input pin is not correct. Did you test it somehow? – Bex Feb 26 '15 at 10:45
1

There are a couple of problems with the setup and trigger pulse. First you should set the trigger pin to low for a second or so before sending the trigger pulse, add:

gp.output(outputPin, False)
time.sleep(1)

before the following:

gp.output(outputPin,True)
time.sleep(0.001)
gp.output(outputPin,False)
time.sleep(0.5)

The second issue is the length of the trigger pulse you are sending change:

gp.output(outputPin,True)
time.sleep(0.001)

to:

gp.output(outputPin,True)
time.sleep(0.00001)

You can probably remove the following line as well:

time.sleep(0.5)

after setting the pin to false.

I also think your caclulation for the distance is incorrect:

distance = currentTime / 0.000058

References and more details available from the following tutorials: http://www.bytecreation.com/blog/2013/10/13/raspberry-pi-ultrasonic-sensor-hc-sr04 https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi

| improve this answer | |
  • I don't understand why there are so many poorly implemented versions of such simple software on the www. Both the ones you link have the same error. start time and end time should both be set before entering their respective loops. – joan Feb 25 '15 at 21:13
  • @joan lazy programmers, nor do they agree on the scaling factor for the distance. – Steve Robillard Feb 25 '15 at 21:32

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.