Innovative Practice【Raspberry Pi Development】==HC-SR04

Getting to Know Raspberry Pi Series Articles

树莓派小车小白从0到1开发之路,大家如果有兴趣可以共同讨论


1. Ultrasonic ranging module HC-SR04

insert image description here##

1.1 Wiring rules

  • VCC: It is the power supply of HC-SR04 ultrasonic distance sensor, connected to 5V pin.
  • Trig (Trigger): The pin is used to trigger the ultrasonic pulse.
  • Echo: The echo pin produces a pulse when a reflected signal is received. The length of the pulse is proportional to the time required to detect the transmitted signal.
  • GND: ground.

1.2 Sample code

import RPi.GPIO as GPIO
import time

# 定义GPIO引脚编号
trig_pin = 16
echo_pin = 18

# 初始化GPIO引脚状态
GPIO.setmode(GPIO.BOARD)  # 设置物理引脚模式
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)


def distance():
    # 发送10us的高电平脉冲
    GPIO.output(trig_pin, GPIO.HIGH)
    time.sleep(0.00001)
    GPIO.output(trig_pin, GPIO.LOW)

    # 计算脉冲宽度
    while not GPIO.input(echo_pin):
        pass
    pulse_start = time.time()
    while GPIO.input(echo_pin):
        pass
    pulse_end = time.time()
    pulse_duration = pulse_end - pulse_start
    # 计算距离并返回
    speed_of_sound = 34300  # 声速,单位是厘米/秒
    distance = pulse_duration * speed_of_sound / 2
    return distance


try:
    while True:
        dist = distance()
        print(f"Distance: {
      
      dist:.2f} cm")
        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()  # 清除所有GPIO引脚的状态

Guess you like

Origin blog.csdn.net/IWICIK/article/details/130466371