def read_distance():
"""Reads distance from HC-SR04."""
# Send trigger pulse
try:
trigger.off()
sleep(0.000002) # Ensure it's low
trigger.on()
sleep(0.00002) # 20 microsecond pulse
trigger.off()
print("[DEBUG] Trigger pulse sent")
# Measure echo pulse
pulse_duration = time_pulse_us(echo, 1, 23529) # Timeout for 400 cm range
print(f"[DEBUG] Pulse duration (us): {pulse_duration}")
if pulse_duration < 0 or pulse_duration > 23529: # Invalid duration
print("[ERROR] Pulse duration out of range or timeout")
return None
# Calculate distance
distance = (pulse_duration * 0.0343) / 2 # Convert to cm
return round(distance, 2)
except Exception as e:
print("[ERROR] Exception occurred:", str(e))
return None