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

基于超声波传感器触发目标检测模型的实现方法咨询

超声波触发目标检测模型的可行实现方案

一、阻塞式轮询触发函数

核心逻辑:循环读取超声波传感器的距离值,当距离低于设定阈值时,直接调用目标检测模型的推理函数。适合简单单任务场景,无需同时处理其他工作。
示例代码:

import RPi.GPIO as GPIO
import time
from your_model_module import run_object_detection  # 替换为你的模型推理函数

# 超声波传感器引脚配置
TRIG = 23
ECHO = 24

def init_ultrasonic():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(TRIG, GPIO.OUT)
    GPIO.setup(ECHO, GPIO.IN)

def get_distance():
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)
    
    start_time = time.time()
    stop_time = time.time()
    
    while GPIO.input(ECHO) == 0:
        start_time = time.time()
    while GPIO.input(ECHO) == 1:
        stop_time = time.time()
    
    time_elapsed = stop_time - start_time
    distance = (time_elapsed * 34300) / 2  # 转换为厘米单位
    return distance

def trigger_detection_on_proximity(threshold_cm=30):
    init_ultrasonic()
    try:
        while True:
            dist = get_distance()
            if dist < threshold_cm:
                print(f"检测到物体,距离:{dist:.2f}cm,启动目标检测")
                run_object_detection()
                time.sleep(2)  # 防重复触发,可按需调整间隔
            time.sleep(0.1)
    finally:
        GPIO.cleanup()

二、多线程异步触发函数

核心逻辑:单独开一个线程监听超声波传感器,主线程可同时处理其他任务(比如UI显示、数据记录),检测到近距离物体时异步启动模型推理,避免阻塞主流程。
示例代码:

import threading
import time
import RPi.GPIO as GPIO
from your_model_module import run_object_detection

TRIG = 23
ECHO = 24
running = True
threshold = 30

def init_ultrasonic():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(TRIG, GPIO.OUT)
    GPIO.setup(ECHO, GPIO.IN)

def get_distance():
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)
    
    start_time = time.time()
    stop_time = time.time()
    
    while GPIO.input(ECHO) == 0:
        start_time = time.time()
    while GPIO.input(ECHO) == 1:
        stop_time = time.time()
    
    time_elapsed = stop_time - start_time
    return (time_elapsed * 34300) / 2

def proximity_listener():
    init_ultrasonic()
    while running:
        dist = get_distance()
        if dist < threshold:
            print(f"物体接近,距离{dist:.2f}cm,启动检测")
            # 用新线程启动检测,避免阻塞监听线程
            detection_thread = threading.Thread(target=run_object_detection)
            detection_thread.start()
            time.sleep(1.5)
        time.sleep(0.1)
    GPIO.cleanup()

# 启动监听线程
listener_thread = threading.Thread(target=proximity_listener)
listener_thread.start()

# 主线程可处理其他任务
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    running = False
    listener_thread.join()

三、GPIO中断触发函数(硬件级优化)

核心逻辑:利用GPIO中断功能,监听超声波ECHO引脚的信号变化,触发距离计算与检测逻辑,适合对实时性要求高、不想用循环轮询浪费资源的场景。
示例代码:

import RPi.GPIO as GPIO
import time
from your_model_module import run_object_detection

TRIG = 23
ECHO = 24
start_time = 0
stop_time = 0
threshold = 30

def init_ultrasonic():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(TRIG, GPIO.OUT)
    GPIO.setup(ECHO, GPIO.IN)
    # 绑定ECHO引脚的上升沿/下降沿中断
    GPIO.add_event_detect(ECHO, GPIO.BOTH, callback=echo_callback)

def echo_callback(channel):
    global start_time, stop_time
    if GPIO.input(channel) == 1:
        start_time = time.time()
    else:
        stop_time = time.time()
        time_elapsed = stop_time - start_time
        distance = (time_elapsed * 34300) / 2
        if distance < threshold:
            print(f"中断触发检测,距离{distance:.2f}cm")
            run_object_detection()

def trigger_via_interrupt():
    init_ultrasonic()
    try:
        while True:
            GPIO.output(TRIG, True)
            time.sleep(0.00001)
            GPIO.output(TRIG, False)
            time.sleep(0.5)  # 超声波发射间隔
    except KeyboardInterrupt:
        GPIO.remove_event_detect(ECHO)
        GPIO.cleanup()

四、适配你现有方案的优化函数

针对你提到的“拍摄图片后触发OOP分类”,可以封装成模块化函数,直接替换上述方案中的run_object_detection()即可:

def capture_and_detect():
    # 调用拍照模块(以PiCamera为例)
    from picamera import PiCamera
    camera = PiCamera()
    camera.capture('/tmp/current_frame.jpg')
    camera.close()
    # 启动OOP分类模型推理
    from your_oop_model import ObjectDetector
    detector = ObjectDetector()
    results = detector.classify('/tmp/current_frame.jpg')
    print("检测结果:", results)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:20:28