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()