HC-SR04 模块实现超声波测距代码
时间: 2024-12-18 21:27:18 浏览: 7
HC-SR04是一种常见的超声波传感器模块,常用于非接触式的距离测量。它的工作原理是通过发送超声波脉冲然后接收反射回来的信号,计算出两点之间的距离。以下是使用Python编写的基本HC-SR04测距代码示例,假设已连接到GPIO针脚:
```python
import RPi.GPIO as GPIO
import time
# 设置GPIO引脚
TRIG_PIN = 18
ECHO_PIN = 23
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG_PIN, GPIO.OUT) # TRIG作为输出
GPIO.setup(ECHO_PIN, GPIO.IN) # ECHO作为输入
def distance_cm():
GPIO.output(TRIG_PIN, False)
time.sleep(2)
GPIO.output(TRIG_PIN, True)
time.sleep(0.00001)
GPIO.output(TRIG_PIN, False)
start_time = time.time()
while GPIO.input(ECHO_PIN) == 0:
start_time = time.time()
stop_time = time.time()
while GPIO.input(ECHO_PIN) == 1:
stop_time = time.time()
elapsed_time = stop_time - start_time
distance = (elapsed_time * 34300) / 2 # 速度34300 cm/s,在空气中近似
return round(distance, 2)
if __name__ == "__main__":
try:
while True:
print(f"Distance: {distance_cm()} cm")
time.sleep(1) # 控制测量频率
except KeyboardInterrupt:
GPIO.cleanup() # 退出时清理GPIO资源
阅读全文