I have a raspberry pi 4 and a HC-SR04 ultrasonic distance sensor. I want to use it in a raspberry-pi based robot. The other features look fine, the robot can move, et cetera.
But my code for the distance sensor does not work. I have the VCC pin of the sensor wired to a 3.3V pin on the Pi, the GND wired to the ground, the TRIG on pin 15 (BCM Mode), and the ECHO on pin 14. I have most of the other pins wired to different pieces of hardware, but if the problem is in the wiring please tell me.
The problem is that my code keeps getting stuck on the while
loop which means to me that the ECHO pin is stuck on HIGH.
Here is my code:
import gpio
import time
class ResourceLock():
def __init__(self):
self.locked = False
def lock(self):
while True:
if not self.locked:
self.locked = True
return
def unlock(self):
self.locked = False
class HC_SR04():
usage_lock = ResourceLock()
def __init__(self):
self.setup(15, 14)
def setup(self, pin_trig, pin_echo):
gpio.initialize_GPIO()
gpio._GPIO.setup(pin_echo, gpio.IN)
gpio._GPIO.setup(pin_trig, gpio._GPIO.OUT)
gpio.config(pin_trig, gpio.LOW)
self.pin_trig = pin_trig
self.pin_echo = pin_echo
def get_distance(self):
self.usage_lock.lock()
gpio.config(self.pin_trig, gpio.LOW)
time.sleep(1.5) # This is so the sensor doesn't get confused
while gpio._GPIO.input(self.pin_echo) == 0:
time.sleep(0.001)
gpio.config(self.pin_trig, gpio.HIGH)
time.sleep(0.00001)
gpio.config(self.pin_trig, gpio.LOW)
while gpio._GPIO.input(self.pin_echo) == 1:
sig = time.time()
self.usage_lock.unlock()
print(locals()) # DEBUG
tl = sig - nosig
distance = tl / 0.000058
return distance
# gpio.py
import RPi.GPIO as _GPIO
def initialize_GPIO():
_GPIO.setmode(_GPIO.BCM)
_GPIO.setwarnings(False)
HIGH = True
LOW = False
IN = _GPIO.IN
def config(pin, state):
_GPIO.output(pin, state)
class LED():
def __init__(self, pin):
self.pin = pin
_GPIO.setup(pin, _GPIO.OUT)
def on(self):
_GPIO.output(self.pin, HIGH)
def off(self):
_GPIO.output(self.pin, LOW)
cleanup = _GPIO.cleanup
initialize_GPIO()
# set systemexit hook
import atexit
atexit.register(cleanup)
*Note: the gpio
module is my own wrapper on RPi.GPIO - I don't use it much except to configure an output pin HIGH
and LOW
Any help would be apprieciated, as I have no idea what's the problem and I did a search already and found sites like https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/.
gpio
for other modules. I'll provide the source code though.