The following code measures distance using an ultrasonic sensor. The only thing you have to be careful about is the sensor operating voltage. Some ultrasonic sensor works at 5V and some work at 3.3V. Please make sure your ultrasonic sensors operating voltage.
Moreover, the Pi Pico input pin voltage is 3.3V. Therefore, if your ultrasonic sensor operates at 5V, you can’t connect the echo pin directly to your Pico as input. You have to lower the 5V to 3.3V or lower using a resistor bridge. Otherwise, you won’t get proper readings.
from machine import Pin
import utime
trigger = Pin(1, Pin.OUT)
echo = Pin(0, Pin.IN)
def ultra():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
signaloff = 0
signalon = 0
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
print("The distance from object is ", distance,"cm")
while True:
ultra()
utime.sleep(1)