from machine import Pin, SoftI2C, PWM
from utime import sleep_ms
from hcsr04 import HCSR04
from i2c_lcd import I2cLcd

# Initialize Ultrasonic Sensor
trig_pin = Pin(12, Pin.OUT)
echo_pin = Pin(14, Pin.IN)
ultrasonic = HCSR04(trig_pin, echo_pin)

# Initialize Servo Motor
servo_pin = Pin(13, Pin.OUT)
servo_pwm = PWM(servo_pin)
servo_pwm.freq(50)  # Set PWM frequency to 50Hz
servo_min_duty = 10  # Minimum duty cycle for servo (adjust as needed)
servo_max_duty = 90  # Maximum duty cycle for servo (adjust as needed)

# Initialize LCD
i2c = SoftI2C(sda=Pin(21), scl=Pin(22))
lcd = I2cLcd(i2c, 0x27, 2, 16)  # Adjust address and rows/columns if needed

def read_distance():
    try:
        distance = ultrasonic.distance_cm()
        return distance
    except OSError:
        return None

def activate_servo():
    # Move servo to a specific angle (adjust as needed)
    servo_pwm.duty(servo_min_duty)  # Move servo to minimum angle
    sleep_ms(500)  # Wait for servo to reach the position
    servo_pwm.duty(servo_max_duty)  # Move servo to maximum angle
    sleep_ms(500)  # Wait for servo to reach the position

while True:
    distance = read_distance()
    if distance is not None:
        print("Distance: %.2f cm" % distance)
        lcd.clear()
        #LCD Display
        lcd.move_to(0, 0)
        lcd.putstr('Distance: ')
        lcd.move_to(0, 1)
        lcd.putstr('%.2f cm' % distance)
        if distance < 100:
            activate_servo()
    sleep_ms(500)
$abcdeabcde151015202530fghijfghij