# ESP32 Pin assignment 

 #import all libraries/modules
from machine import Pin, I2C, PWM
import ultrasonic 
from machine import Pin, PWM
from utime import sleep

#Pin declaration
servo_pin = 13
TRIG = Pin(33, Pin.IN)
ECHO = Pin(32, Pin.OUT)
led_green = Pin(18, Pin.OUT)
led_red = Pin(19, Pin.OUT)

servo = PWM(Pin(servo_pin), freq=50, duty=77)

sensor_jarak = ultrasonic.HCSR04(trigger_pin=TRIG, echo_pin=ECHO)


def move_servo(angle):
    duty_cycle = int(((angle / -180) * 77) + 77)
    servo.duty(duty_cycle)
    sleep(0.5)  # Give time for the servo to move

while True:
    #ULTRASONIC PART 
    print("\n============DISTANCE OF INCOMING OBJECT===========")
    distance_in_cm = sensor_jarak.distance_cm()
    print('An object is detected')

    if distance_in_cm<50: 
        move_servo(120);
        led_green.on()
        sleep(5);
        move_servo(0);
    elif distance_in_cm>50:
        move_servo(0);
        led_red.off()
        sleep(2);
        move_servo(0);

    sleep(5)