from machine import Pin, time_pulse_us
import time
SOUND_SPEED=340
TRIG_PULSE_DURATION_US=10
trig_pin = Pin(15, Pin.OUT)
echo_pin = Pin(14, Pin.IN)
while True:
# Prepare the signal
trig_pin.value(0)
time.sleep_us(5)
# Create a 10 microseconds pulse
trig_pin.value(1)
time.sleep_us(TRIG_PULSE_DURATION_US)
trig_pin.value(0)
ultrasonic_duration = time_pulse_us(echo_pin, 1, 30000) # Return the propation time of the wave in 10 microseconds
# Included to handle the negative error that might occur if the object is not in range
if ultrasonic_duration > 0:
distance_cm = SOUND_SPEED * ultrasonic_duration / 20000
print(f"Distance : {distance_cm} cm")
else:
print("Out of range or sensor error")
time.sleep_ms(500)
# QUICK NOTES ABOUT THE SIMULATION
# I included the two resistors (as voltage dividers) as a precautionary measure
# for when building real-world projects. The echo pin from the HC-SR04 produces 5V
# but the Raspberry Pi operates with ~3.3V. In a real-world project, without the resistor,
# I would risk frying my board. So the resistors (1K and 2K ohms) prevent this by dissipating
# some of that so the board and the sensor work without risk of damaging each other.