from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import utime

# Ultrasonic sensor setup
trigger = Pin(7, Pin.OUT)
echo = Pin(6, Pin.IN)

def ultrasound():
    trigger.low()
    utime.sleep_us(2)
    trigger.high()
    utime.sleep_us(10)
    trigger.low()
    while echo.value() == 0:
        signaloff = utime.ticks_us()
    while echo.value() == 1:
        signalon = utime.ticks_us()
    timepassed = signalon - signaloff
    return timepassed

# OLED display dimensions
WIDTH = 128
HEIGHT = 64

# Initialize I2C for OLED
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=200000)
print("I2C Address      : " + hex(i2c.scan()[0]).upper())
print("I2C Configuration: " + str(i2c))

# Initialize OLED display
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)

while True:
    # Measure distance
    measured_time = ultrasound()
    distance_cm = (measured_time * 0.0343) / 2
    distance_cm = round(distance_cm, 2)
    
    # Display on OLED
    oled.fill(0)
    oled.text("Distance:", 20, 15)
    oled.text(str(distance_cm) + " cm", 20, 35)
    oled.show()
    
    # Print to serial monitor
    print("The distance from object is", distance_cm, "cm")
    
    utime.sleep(1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT