print("This program will integrate ESP32 with ultrasonic sensor")

#Import necessary modules/libraries
import hcsr04 #ultrasonic lib
import ssd1306 #oled lib
from hcsr04 import HCSR04
from utime import sleep
from machine import SoftI2C, Pin, PWM #PWM = Pulse Width Modulation

#Create an object called ultrasonic_sensor using OOP (Object Oriented Programming)
#OOP format is --> library name.class name(......)
ultrasonic_sensor = hcsr04.HCSR04(trigger_pin=13, echo_pin=27, echo_timeout_us=500*2*30)

#Pin declaration on OLED
i2c_oleddisplay = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128 #based on spec
oled_height = 64 #based on spec

#Use OOP (Object Oriented Programming) to create the object
#Remarks: Object format --> library name.class name
#(width, height, i2c)
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oleddisplay)

#Declare buzzer connection
buzzer = PWM(Pin(23), Pin.OUT)

while True:

    #Let's test our ultrasonic sensor
    jarak_in_cm = ultrasonic_sensor.distance_cm() #use when u need decimal point number
    jarak_in_mm = ultrasonic_sensor.distance_mm() #use when u want whole number

    #Display the distance values on Serial Monitor
    print('An object is detected in : ', jarak_in_cm, 'cm')
    print('An object is detected in : ', jarak_in_mm, 'mm')
    print('------------------------------------------------')
    print('\n')

    #Display distance value on OLED screen
    oled.fill(1)
    oled.text('Object Detected:', 3, 0, 0)  #1st 0 is X-axis, 2nd 0 is Y axis, 1 for white
    oled.text(str(jarak_in_cm), 5, 20, 0)
    oled.text('cm', 75, 20, 0)
    oled.text(str(jarak_in_mm), 5, 40, 0)
    oled.text('mm', 75, 40, 0)

    oled.show()

    if jarak_in_cm < 50:
        for i in range (10):
            buzzer.init(freq=1703, duty=400)
            sleep(0.5)
            buzzer.init(freq=1, duty=0)
            sleep(0.5)
    elif 50 <= jarak_in_cm < 150:
        for i in range (10):
            buzzer.init(freq=1703, duty=400)
            sleep(1)
            buzzer.init(freq=1, duty=0)
            sleep(1)
    else:
        buzzer.init(freq=1, duty=0)

    sleep(5)
$abcdeabcde151015202530fghijfghij