2

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/.

2
  • Whatever your module does is unclear. Maybe you should post documentation OR better still use an existing library like RPi.GPIO or gpiozero. It is unclear why you feel the need to lock anything.
    – Milliways
    Jan 13, 2023 at 11:55
  • I needed some of the code in gpio for other modules. I'll provide the source code though.
    – allen546
    Jan 13, 2023 at 13:19

2 Answers 2

1

The sensor is unlikely to work properly when powered from 3V3.

You need to power from 5V and use a resistor divider to drop the echo 5V to a Pi GPIO safe 3V3.

4
  • sorry, but I know almost nothing when it comes to circuits, so please explain the voltage-divider. And I'm afraid the battery powering the pi gives 7.2V instead of 5 and my pi doesn't burn :). But the hc-sr04 I'm not sure if it could tolerate the higher voltage.
    – allen546
    Jan 13, 2023 at 13:16
  • Feeding 7.2V into the Pi 5V rail will destroy the Pi straight away. As for voltage divider do a search. Unless you are using a non-standard SR04 it needs 5V.
    – joan
    Jan 13, 2023 at 13:20
  • Your HAT must convert the voltage to 5V (probably using a BEC/UBEC). Look up the details of the HAT where you bought it.
    – joan
    Jan 13, 2023 at 15:42
  • yeah, I found out later and I thought the hat powered 7.2v because the script that came with it said 7.2v.
    – allen546
    Jan 16, 2023 at 4:59
1

I am assuming as others that you have the older version of the HC-SR04. My suggestion is to purchase a new model of the HC-SR04, it will work on 3V3 elimination all the level translation etc. Check on this link: https://www.seeedstudio.com/blog/2019/11/04/hc-sr04-features-arduino-raspberrypi-guide/

From other comments I do not know if the Pi is operational or not. You will need to check that first to be sure everything is functional.

Two suggestions, there are two books you should try to read, they are the Electronics and Raspberry Pi cookbooks. They contain a lot of information and if I remember the Raspberry Pi cookbook has something similar to your circuit it it.

1
  • The Pi is certainly operational, it's been communicating with several other i2c devices. And how do you tell the diference between the older version and the newer version? PS. I bought the HC-SR04 about 1 and a half year ago.
    – allen546
    Jan 17, 2023 at 5:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.