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:
#Import libraries
import RPi.GPIO as GPIO
import time
#GPIO Mode (BOARD / BCM)
GPIO.setmode (GPIO.BCM)
#Assign GPIO pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24
#Set direction of GPIO pins (IN / OUT)
GPIO.setup (GPIO_TRIGGER, GPIO.OUT)
GPIO.setup (GPIO_ECHO, GPIO.IN)
def distance ():
#let sensor start up
GPIO.output (GPIO_TRIGGER, GPIO.LOW)
time.sleep (1)
# set trigger to HIGH
GPIO.output (GPIO_TRIGGER, GPIO.HIGH)
# set trigger after 0.01ms to LOW
time.sleep (0.00001)
GPIO.output (GPIO_TRIGGER, GPIO.LOW)
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__':
try:
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:
154.4cm
124.3cm
0.1cm
0.1cm
97.0cm
56.7cm
75.9cm
245.1cm
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!