树莓派3使用HC-SR04超声波测距

HC-SR04超声波模块工作原理
采用IO口TRIG触发测距,给至少10us的高电平信号;
模块自动发送8个40khz的方波,自动检测是否有信号返回;
有信号返回,通过IO口ECHO输出一个高电平,高电平持续的时间就是超声波从发射到返回的时间。测试距离=(高电平时间*声速(340M/S))/2;
参考信息:

程序:


#!/usr/bin/python3
import time
import RPi.GPIO as GPIO

trigger_pin = 16
echo_pin = 18

GPIO.setmode(GPIO.BOARD)
GPIO.setup(trigger_pin,GPIO.OUT)
GPIO.setup(echo_pin,GPIO.IN)

def send_trigger_pulse():
    GPIO.output(trigger_pin,True)
    time.sleep(0.00015)
    GPIO.output(trigger_pin,False)

def wait_for_echo(value,timeout):
    count = timeout
    while GPIO.input(echo_pin) != value and count>0:
        count = count-1

def get_distance():
    send_trigger_pulse()
    wait_for_echo(True,10000)
    start = time.time()
    wait_for_echo(False,10000)
    finish = time.time()
    pulse_len = finish-start
    distance_cm = pulse_len/0.000058
    return distance_cm

while True:
    print("距离 = %f cm"%get_distance())
    time.sleep(1)
GPIO.cleanup()


电路连接图:









测试数据:




猜你喜欢

转载自blog.csdn.net/oAlevel/article/details/79228381