Jul 15, 2024
RPi.GPIO
, time
trig_pin
= 23echo_pin
= 24GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
try:
while True:
# Ping Send: Set trigger pin to low, wait, set high, wait, set low
GPIO.output(trig_pin, 0)
time.sleep(2e-6)
GPIO.output(trig_pin, 1)
time.sleep(10e-6)
GPIO.output(trig_pin, 0)
# Echo Wait: Wait for echo pin to go high, then start timer
while GPIO.input(echo_pin) == 0:
pass
start_time = time.time()
# Timer Stop: Wait for echo pin to go low, then stop timer
while GPIO.input(echo_pin) == 1:
pass
stop_time = time.time()
# Calculate Ping Travel Time
ping_travel_time = stop_time - start_time
ping_travel_time_microseconds = int(ping_travel_time * 1e6)
# Print Result
print(ping_travel_time_microseconds)
# Sleep to avoid ping overlap
time.sleep(0.2)
except KeyboardInterrupt:
GPIO.cleanup()
print("GPIO Good to Go")