from machine import Pin, I2C
import utime
import ssd1306

# Set up the I2C interface for the OLED display
i2c = I2C(0, scl=Pin(17), sda=Pin(16))

# Initialize the OLED display
oled = ssd1306.SSD1306_I2C(128, 64, i2c)

# Set up the pins for the ultrasonic sensor
trigger = Pin(7, Pin.OUT)
echo = Pin(6, Pin.IN)

distance = 0

def ultrasound():
    global distance
    trigger.low()
    utime.sleep_us(2)
    trigger.high()
    utime.sleep_us(5)
    trigger.low()
    while echo.value() == 0:
        signaloff = utime.ticks_us()
    while echo.value() == 1:
        signalon = utime.ticks_us()
    timepassed = signalon - signaloff
    distance = (timepassed * 0.0343) / 2

while True:
    ultrasound()
    print("The distance from object is ", distance, "cm")

    # Clear the display
    oled.fill(0)
    # Display the distance on the OLED
    oled.text("Distance:", 0, 0)
    oled.text(str(distance) + " cm", 0, 10)
    # Update the display
    oled.show()

    utime.sleep(1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT