# Exercise 13(a)
from machine import Pin, time_pulse_us
from time import sleep_ms,sleep_us
# Define the GPIO lines needed
echo_pin = Pin(18, Pin.IN)
trig_pin = Pin(19, Pin.OUT)
# Ensure the trigger line is zero to begin with
trig_pin.value(0)
sleep_us(10)
while True:
trig_pin.value(1) # signal to output pulses
sleep_us(10) # only need a short burst of pulses
trig_pin.value(0) # signal to stop pulses
# determine how long before an echo signal is received
pulse_duration = time_pulse_us(echo_pin, 1, 1000000) # Wait for a LOW pulse, 1s timeout
if pulse_duration > -1:
echo_duration = pulse_duration/2
# calculate the distance in cms
object_distance = 341 * (echo_duration/1000000)*100
print(f' The object is {object_distance:.1f} cms away')
sleep_ms(500) # no need to update the readings too frequently