I am a new python and raspberry Pi user, I have run this regular code for ultrasonic sensor, the problem with it is that I have connected it to a system where it has continuous 5v input so it has no stop time --> resulting impossibility of stable distance measurement, I understood that I have to set a delay with time.sleep(1) somewhere to make it run for only 1 second for each measurement so it will get stable. My question is: where do I have to insert the delay? Is that answer right?
Code:
import RPi.GPIO as GPIO
import time
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#set GPIO Pins
GPIO_TRIGGER = 21
GPIO_ECHO = 20
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
return distance
if __name__ == '__main__':
try:
while True:
dist = distance()
print ("Measured Distance = %.1f cm" % dist)
time.sleep(1)
# Reset by pressing CTRL + C
except KeyboardInterrupt:
print("Measurement stopped by User")
GPIO.cleanup()
First sensor only needs :
# set Trigger after 0.01ms to LOW
time.sleep(0.001)
GPIO.output(GPIO_TRIGGER, False)
that delay and you can put a your delay in main loop(yes you can add any number of seconds here). Second, Please add resistors for stable results because Ultrasonic sensor I/o's value is 0-5 volts but Raspberry pi GPIO deals in 3.3 volt check diagram from here: https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/