SRF05超声波传感器停止工作并阻塞代码的技术求助
Hey there, let's break down why your 4-SRF05 setup on Raspberry Pi is getting stuck and stopping work. The core issue lies in the unguarded while loops waiting for the ECHO pin state—if a sensor loses signal (from interference, loose wiring, or no detectable target), your code will freeze indefinitely. Let's fix this step by step:
1. Add Timeout to Blocking Loops
This is the most critical fix to prevent permanent code blocking. Modify your SONAR function to exit loops if no signal is detected within a set time:
import time import RPi.GPIO as GPIO def SONAR(TRIG, ECHO, timeout=0.5): GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) # Reset trigger pin GPIO.output(TRIG, False) time.sleep(0.05) # Send trigger pulse GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) # Wait for ECHO rising edge with timeout pulse_start = time.time() while GPIO.input(ECHO) == 0: if time.time() - pulse_start > timeout: print(f"Sensor (TRIG {TRIG}, ECHO {ECHO}) timed out waiting for start pulse") return None # Signal failure instead of blocking pulse_start = time.time() # Wait for ECHO falling edge with timeout pulse_end = time.time() while GPIO.input(ECHO) == 1: if time.time() - pulse_end > timeout: print(f"Sensor (TRIG {TRIG}, ECHO {ECHO}) timed out waiting for end pulse") return None pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 return round(distance, 2)
Why this works:
- The
timeoutparameter (default 0.5s, adjust as needed) ensures your code won't hang forever if a sensor fails to respond. - Returning
Nonelets your main program skip invalid readings and keep running the other sensors.
2. Optimize Multi-Sensor GPIO Management
Sequential operation can cause GPIO state glitches if you re-setup pins repeatedly. Try these tweaks:
- Initialize all pins once at the start of your program instead of inside the
SONARfunction:# Main program initialization GPIO.setmode(GPIO.BCM) # Use GPIO.BOARD if you're using physical pin numbers SENSOR_CONFIGS = [ {"TRIG": 23, "ECHO": 24}, {"TRIG": 17, "ECHO": 27}, {"TRIG": 22, "ECHO": 5}, {"TRIG": 6, "ECHO": 13} ] # Pre-configure all sensor pins for sensor in SENSOR_CONFIGS: GPIO.setup(sensor["TRIG"], GPIO.OUT) GPIO.setup(sensor["ECHO"], GPIO.IN) GPIO.output(sensor["TRIG"], False) # Keep trigger low initially - Add small delays between sensors to avoid ultrasonic cross-interference:
while True: for sensor in SENSOR_CONFIGS: distance = SONAR(sensor["TRIG"], sensor["ECHO"]) if distance is not None: print(f"Sensor {sensor['TRIG']}: {distance} cm") else: print(f"Sensor {sensor['TRIG']} read failed") time.sleep(0.1) # Prevent signal overlap between sensors
3. Hardware Troubleshooting Tips
If sensors still stop working intermittently, check these physical issues:
- Secure wiring: Ensure SRF05 VCC is connected to Raspberry Pi's 5V pin, GND to GND, and TRIG/ECHO to GPIO pins—loose connections are a common culprit.
- Power supply: 4 SRF05s can draw peak current that weak power supplies can't handle. Use a powered USB hub for your Raspberry Pi to avoid voltage drops.
- Sensor placement: Keep sensors far enough apart to prevent their ultrasonic beams from overlapping, and avoid pointing them at highly absorbent surfaces (like soft fabric) that won't reflect signals.
4. Clean Up GPIO Resources
Always reset GPIO when your program exits to avoid pin state conflicts in future runs:
try: # Your main sensor reading loop here while True: # ... except KeyboardInterrupt: GPIO.cleanup() # Run this when you press Ctrl+C to exit
内容的提问来源于stack exchange,提问作者George Tsoufis

