from machine import Pin, I2C, PWM
import time
import math
from ssd1306 import SSD1306_I2C

# Initialize the I2C bus
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=400000)

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

# Initialize the ultrasonic sensor pins
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)

# Initialize the servo motor pin
servo_pin = Pin(4, Pin.OUT)
servo = PWM(servo_pin)
servo.freq(50)

# Function to measure distance using the ultrasonic sensor
def measure_distance():
    trigger.low()
    time.sleep_us(2)
    trigger.high()
    time.sleep_us(10)
    trigger.low()
    while echo.value() == 0:
        signaloff = time.ticks_us()
    while echo.value() == 1:
        signalon = time.ticks_us()
    timepassed = signalon - signaloff
    distance = (timepassed * 0.0343) / 2
    return distance

# Main loop to continuously display the distance on the OLED display and control the servo motor
while True:
    distance = measure_distance()
    oled.fill(0)
    oled.text("Distance:", 0, 0)
    oled.text(str(round(distance, 1)) + " cm", 0, 20)
    oled.show()
    if distance < 10:
        # Move the servo motor to the closed position
        servo.duty_u16(65535 // 2)
    else:
        # Move the servo motor to the open position
        servo.duty_u16(65535 // 4)
    time.sleep(1)

BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT