Arduino Forum

Using Arduino => Sensors => Topic started by: Totemi1324 on Aug 14, 2019, 12:53 pm

Title: Troubles with HC-SR04 control?
Post by: Totemi1324 on Aug 14, 2019, 12:53 pm
Hello there,

I use the HC-SR04 ultrasonic sensor to measure distances. I connected the senor to the board via GPIO and found a Python code that returns the distance every 2 seconds. Here's my code:

Code: [Select]
#Import libraries
import RPi.GPIO as GPIO
import time
GPIO.setmode (GPIO.BCM)
#Assign GPIO pins
#Set direction of GPIO pins (IN / OUT)
def distance ():
    #let sensor start up
    time.sleep (1)

    # set trigger to HIGH
    # set trigger after 0.01ms to LOW
    time.sleep (0.00001)
    StartTime = time.time ()
    StopTime = time.time ()
    # save start time
    while GPIO.input (GPIO_ECHO) == GPIO.LOW:
        StartTime = time.time ()
    # save arrival time
    while GPIO.input (GPIO_ECHO) == GPIO.HIGH:
        StopTIme = time.time ()
    # Difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with sonic speed (34300 cm / s)
    # and divide by 2, since the signal travels there and back
    distance = (TimeElapsed * 34300) / 2
    return distance
if __name__ == '__main__':
        while true:
            distance = distance ()
            print ("Measured distance =% .1f cm"% distance)
            time.sleep (1)
        # Reset when canceled via CTRL + C
    except KeyboardInterrupt:
        print ("Measurement canceled by user")
        GPIO.cleanup ()

The code works and the sensor is returning the values, but my problem is: the values ​​are complete garbage. Here are e.g. the results for measuring in front of a flat wall which is 1m away:


Any idea what can cause this? It is not the case that this is not the case. Is the error in my code or the sensor? Can it be the sonic waves than ultrasonic ones, too? Would it help to shield the emitter and receiver outward to 3cm or so the sensor is coming to the sensor?

Thanks for the help in advance!
Title: Re: Troubles with HC-SR04 control?
Post by: meltDown on Aug 14, 2019, 02:46 pm
Perhaps I'm just being thick, but where's the Arduino in this mix?

Title: Re: Troubles with HC-SR04 control?
Post by: Totemi1324 on Aug 18, 2019, 10:52 am
Sorry, but it's nowhere. I'm using a Raspberry Pi to control the sensor. I just thought because the sensor technically is made for Arduinos, the people here would know something specific about the usage of it. Something I missed when I was connecting the sensor perhaps?
Title: Re: Troubles with HC-SR04 control?
Post by: groundFungus on Aug 18, 2019, 05:44 pm
This is an Arduion forum so, technically, Rpi and Python questions do not belong here.

That said, is the HC-SR04 ultrasonic sensor that you have specified to work at 3.3V?  The HC-SR04 ultrasonic sensors that I have used are all 5V devices and will not work well at lower supply voltage.