0

我正在尝试使用 HC SR04 超声波传感器找到与附近物体的距离。我按照以下链接中的教程进行操作:

HC-SR04 Raspberry Pi 上的超声波测距传感器

我按照给定的方式复制了所有说明。我在尝试运行代码时遇到了问题。

import RPi.GPIO as GPIO
import time

# Setting the GPIO pins mode
GPIO.setmode(GPIO.BCM)

# Setting the pin values
TRIG = 23
ECHO = 24

# Assigning the pins to GPIO
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

# Allowing the sensor to settle down
GPIO.output(TRIG, False)
print('Waiting for thr sensor to settle down!!')
time.sleep(2)

# Sending a trigger pulse of 10 micro seconds duration
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

# Starting the measurement process
pulse_start = 0
pulse_end = 0

# Checking for the last timestamp at which the ECHO is OFF
while GPIO.input(ECHO) == 0:
    print('Running ECHO = 0 loop')
    pulse_start = time.time()

print('Pulse start: ',pulse_start)

# Checking for the last timestamp at which the ECHO is ON
while GPIO.input(ECHO) == 1:
    print('Running ECHO = 1 loop')
    pulse_end = time.time()

print('Pulse end: ',pulse_end)

# Calculating the pulse duration
pulse_duration = pulse_end - pulse_start

# Distance Calc
distance = round((343/2)*pulse_duration,2)
print('Distance: ', distance, 'm')

# Cleaning up the pins
GPIO.cleanup()

该代码似乎没有进入第一个 while 循环,其中正在检查 ECHO 引脚的低信号。这给我计算距离带来了问题。上述代码的输出如下:

代码输出

谁能指出问题可能是什么?

4

0 回答 0