# Import necessary libraries
from machine import Pin, time_pulse_us
import time
# Defining the trigger and echo pin locations
trigger_pin = 5
echo_pin = 18
# Defining Speed of Sound Constant
speed_sound = 0.034
# Mentioning Which is the input pin and which is the output
trigger = Pin(trigger_pin, Pin.OUT)
echo = Pin(echo_pin, Pin.IN)
# Main loop
while True:
# Send a 10 microsecond pulse to trigger the sensor, to send waves for 10 microseconds
trigger.value(1) # 1 means switching the tigger pin on
time.sleep_us(10) # waiting for 10 microseconds
trigger.value(0) # 0 means switching the trigger pin ff
# Measure the duration of the pulse on the echo pin
duration = time_pulse_us(echo, 1, 30000) # Timeout set to 30,000 microseconds (30ms)
# Calculate distance in centimeters, using formula d = speed * time
distance_cm = (duration / 2) * (speed_sound)
# Print the measured distance in centimeters
print("Distance:", distance_cm, "cm")
# Wait for some time before the next measurement
time.sleep(1)