This is some code you can use for the HC-SR04 sensor with MicroPython, adapted from this GitHub repository:
from utime import sleep_us
from machine import Pin, time_pulse_us
class Ultrasonic:
def __init__(self, tPin, ePin):
# Init trigger pin (out)
self.trigger = Pin(tPin, Pin.OUT)
self.trigger.low()
# Init echo pin (in)
self.echo = Pin(ePin, Pin.IN)
def distance_in_cm(self):
# Send a 10us pulse.
self.trigger.high()
sleep_us(10)
self.trigger.low()
try:
time = time_pulse_us(self.echo, 1, 29000)
except OSError:
return None
# Calc the duration of the recieved pulse, divide the result by
# 2 (round-trip) and divide it by 29 (the speed of sound is
# 340 m/s and that is 29 us/cm).
dist_in_cm = (time / 2.0) / 29
return dist_in_cm