How to make HC-SR04 Ultrasonic Range Sensor on the Raspberry Pi 3?

220 views Asked by At

I have a Python code that measures distance using HC-SR04 and Raspberry Pi 3. The code prints one value at a time and I would like the code to print/update the distance measurements every second on the Raspberry Pi until the keyboard interrupt.

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

TRIG = 23
ECHO = 24

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.output(TRIG, False)
time.sleep(0.00001)

GPIO.output(TRIG, True)
time.sleep(1)
GPIO.output(TRIG, False)

while GPIO.input(ECHO) == 0:
  pulse_start = time.time()

while GPIO.input(ECHO) == 1:
  pulse_end = time.time()

pulse_duration = pulse_end - pulse_start

distance = pulse_duration *  17150

distance = round(distance, 2)

print("Distance:",distance," cm")

GPIO.cleanup()
1

There are 1 answers

0
Koxo On BEST ANSWER
#!/usr/bin/python
import RPi.GPIO as GPIO
import time

def getDistance:
      GPIO.output(PIN_TRIGGER, GPIO.HIGH)

      time.sleep(0.00001)

      GPIO.output(PIN_TRIGGER, GPIO.LOW)

      while GPIO.input(PIN_ECHO)==0:
            pulse_start_time = time.time()
      while GPIO.input(PIN_ECHO)==1:
            pulse_end_time = time.time()

      pulse_duration = pulse_end_time - pulse_start_time
      distance = round(pulse_duration * 17150, 2)
      return distance


GPIO.setmode(GPIO.BOARD)

PIN_TRIGGER = 7
PIN_ECHO = 11

GPIO.setup(PIN_TRIGGER, GPIO.OUT)
GPIO.setup(PIN_ECHO, GPIO.IN)

GPIO.output(PIN_TRIGGER, GPIO.LOW)

print "Waiting for sensor to settle"

time.sleep(2)

while True:
    print(getDistance())        

finally:
      GPIO.cleanup()