树莓派距离传感器的追溯

时间:2019-02-19 17:24:57

标签: python raspberry-pi

我正在使用下面的代码通过Pi进行距离感测

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

TRIG = 23 
ECHO = 24

print "Distance Measurement In Progress"

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

GPIO.output(TRIG, False)
print "Waiting For Sensor To Settle"
time.sleep(2)

GPIO.output(TRIG, True)
time.sleep(0.00001)
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)如果没有对象,它将正常运行

pi@raspberrypi:~/Desktop $ sudo python DS.py
Distance Measurement In Progress
Waiting For Sensor To Settle
Distance: 2334.34 cm

2)当我在两者之间放置一个对象时,它会给出错误消息:

pi@raspberrypi:~/Desktop $ sudo python DS.py
Distance Measurement In Progress
Waiting For Sensor To Settle
Traceback (most recent call last):
  File "DS.py", line 53, in <module>
    pulse_duration = pulse_end - pulse_start
NameError: name 'pulse_start' is not defined

1 个答案:

答案 0 :(得分:0)

我认为问题在于您没有声明变量,并且如果代码从不经过一会儿,则变量将永远不会被声明,请尝试下面的代码:

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

TRIG = 23
ECHO = 24

def configure_gpio():
  global TRIG, ECHO
  GPIO.setup(TRIG,GPIO.OUT)
  GPIO.setup(ECHO,GPIO.IN)
  GPIO.output(TRIG, False)
  print "Waiting For Sensor To Settle"
  time.sleep(2)

def take_measurement():
  global TRIG, ECHO
  pulse_start = pulse_end = 0

  print "Distance Measurement In Progress..."

  GPIO.output(TRIG, True)
  time.sleep(0.00001)
  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)

  return distance

if __name__ == "__main__":
  configure_gpio()
  distance = take_measurement()

  print "The distance is: ", distance, "cm"

我不确定,这是否可以解决您的问题,但我认为可能会对您有所帮助