You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派Zero 2W超声波传感器输入引脚始终为0求助

Raspberry Pi Zero 2W 超声波传感器输入引脚始终为0的解决方法

硬件排查要点

  • Echo引脚分压问题:HC-SR04这类超声波传感器的Echo输出是5V,而树莓派GPIO仅支持3.3V输入,仅接1K电阻无法有效分压,会导致GPIO引脚因过压进入保护状态,始终返回0。正确做法是用1KΩ + 2KΩ的分压电阻,把Echo的5V信号降到3.3V左右再接入树莓派。
  • 传感器供电:务必给超声波传感器接树莓派的5V引脚供电,用3.3V供电会导致发射功率不足,无法触发回波,Echo引脚始终保持低电平。
  • 接线确认:Trig接树莓派输出引脚,Echo接分压后的输入引脚,传感器GND必须和树莓派GND共地,否则信号无法正常传输。

代码问题修正

你的代码存在3个关键问题,会导致引脚读值异常或程序卡死:

  1. 触发脉冲时长错误:HC-SR04需要10μs的触发脉冲,你用了1ms(0.001秒),过长的触发信号会让传感器工作异常。
  2. Echo信号检测逻辑错误:第一个while循环会持续覆盖start值,且如果引脚一直为0会无限循环,应该改为等待引脚变高时才记录起始时间。
  3. 缺少超时处理:如果传感器没检测到障碍物,程序会卡死在while循环里。

修正后的代码:

import RPi.GPIO as gp
import time
import signal
import sys

def handler(signum, frame):
    print('\n清理GPIO资源')
    time.sleep(0.5)
    gp.cleanup()
    sys.exit()

inputPin = 12  # Echo引脚(经分压后接入)
outputPin = 13 # Trig引脚
led = 7

gp.setmode(gp.BOARD)
gp.setup(outputPin, gp.OUT)
gp.setup(inputPin, gp.IN)
gp.setup(led, gp.OUT)
signal.signal(signal.SIGTSTP, handler)

# 发送符合要求的触发脉冲
gp.output(outputPin, True)
time.sleep(0.00001)  # 10μs触发脉冲
gp.output(outputPin, False)

print("开始检测回波...")
# 等待Echo变为高电平,添加5秒超时
start_timeout = time.time()
while gp.input(inputPin) == 0:
    if time.time() - start_timeout > 5:
        print("超时未检测到回波信号")
        gp.cleanup()
        sys.exit()
start = time.time()

# 等待Echo变为低电平,添加5秒超时
stop_timeout = time.time()
while gp.input(inputPin) == 1:
    if time.time() - stop_timeout > 5:
        print("回波信号超时")
        gp.cleanup()
        sys.exit()
stop = time.time()

# 计算距离并格式化输出
currentTime = stop - start
distance = currentTime / 0.000058  # 转换为厘米单位
print(f"距离:{distance:.2f} cm")

gp.cleanup()

额外验证步骤

  • 用万用表测量Echo引脚的输出电压,确认触发后有高低电平变化(如果没有,说明传感器本身或供电有问题)。
  • 单独测试GPIO输入功能:把输入引脚接3.3V,看是否能读到1;接GND是否读到0,确认GPIO输入功能正常。

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 19:32:20