如何在Raspberry Pi 3上制作HC-SR04超声波测距传感器?

时间:2019-01-21 13:41:32

标签: python-3.x raspberry-pi3

我有一个使用HC-SR04和Raspberry Pi 3测量距离的Python代码。该代码一次打印一个值,我希望该代码每秒在Raspberry Pi上打印/更新距离测量值,直到键盘为止中断。

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 个答案:

答案 0 :(得分:0)

#!/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()