from machine import Pin, time_pulse_us
import time
# Define pins for Trig and Echo
trig_pin = Pin(27, Pin.OUT)
echo_pin = Pin(26, Pin.IN)
# Define LED output
led_red = Pin(25, Pin.OUT)
def measure_distance(): # function definition
# Send a 10us pulse to trigger the sensor
trig_pin.off() # Sets the trigger pin low.
time.sleep_us(2) # Very short pause to stabilize the low signal
trig_pin.on()# Sets the trigger pin high.
time.sleep_us(10) # Keeps the trigger pin high for 10 microseconds
trig_pin.off() #Sets the trigger pin low again.
# Measure the pulse duration on the Echo pin
pulse_duration = time_pulse_us(echo_pin, 1, 30000) # Timeout after 30ms
# 30000: This is a timeout value specified in microseconds.
# It means that time_pulse_us() will wait for a maximum of 30,000 microseconds (30 milliseconds) for the rising edge on the echo_pin. If
#no pulse is detected within this time, the function will return -1.
# Calculate distance in centimeters
distance_cm = (pulse_duration / 2) / 29.1 # Speed of sound is 343 m/s or 29.1 cm/us
return distance_cm
while True:
distance = measure_distance()
print("Distance:", distance, "cm")
#coding for simple ultrasonic sensor
#if distance < 200, red LED is ON
#if distance > 201, red LED is OFF
if (distance < 200):
led_red.value(1)
time.sleep(1) # Wait for 1 second before the next measurement
if (distance > 201):
led_red.value(0)
time.sleep(1) # Wait for 1 second before the next measurement