from machine import Pin, ADC
import time
# Ultrasonic sensor pin definitions
trig = Pin(2, Pin.OUT)
echo = Pin(3, Pin.IN)
# Potentiometer pin definition (ADC0)
pot = ADC(Pin(26))
def get_distance():
# Send Trigger pulse
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
# Measure pulse duration
while echo.value() == 0:
pulse_start = time.ticks_us()
while echo.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
# Calculate distance in centimeters
distance = (pulse_duration * 0.0343) / 2
return distance
while True:
# Read Potentiometer to set Span (maps 0-65535 raw value to 0-400 cm range)
pot_raw = pot.read_u16()
span_threshold = (pot_raw / 65535.0) * 400
# Measure current distance
dist = get_distance()
# Log reading only if measured distance is within the Span limit
if dist < span_threshold:
print(f"[LOG] Distance: {dist:.1f} cm (Less than Span Limit: {span_threshold:.1f} cm)")
else:
print(f"Ignored: {dist:.1f} cm exceeds span ({span_threshold:.1f} cm)")
time.sleep(1)