from machine import Pin, I2C
import time
import ssd1306
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
def get_distance():
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
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)
distance = (pulse_duration * 0.034) / 2
return distance
while True:
dist = get_distance()
oled.fill(0)
oled.text("Ultrasonic", 0, 0)
oled.text("Distance:", 0, 20)
oled.text(str(int(dist)) + " cm", 0, 40)
oled.show()
print("Distance:", dist, "cm")
time.sleep(1)