print(" Hello, ULTRASONIC ")
print("Date: 28/11/2023")
print("Created By Mark")

import oled_library
import library_ultrasonic
from machine import Pin, PWM, SoftI2C
from utime import sleep


#Pin Declaration
TRIG_pin = Pin(13)
ECHO_pin = Pin(12)
RED_pin = Pin(33, Pin.OUT)
BUZZER_pin = Pin(14, Pin.OUT)
Pin_scl_sda = SoftI2C(scl=Pin(22), sda=Pin(21))

#Create an object name for sensoors with libraries. Object_name = LIBRARY.NAME.CLASS.NAME
sonic = library_ultrasonic.HCSR04(trigger_pin=TRIG_pin , echo_pin=ECHO_pin)

#create an object name using OOP ( Object Oriented Programming )
#library name.class name

screen = oled_library.SSD1306_I2C(width=128, height=64, i2c=Pin_scl_sda)

#Main Program
while True:

    #ULTRASONIC PART
    print("\n===== LET'S MEASURE AN INCOMING OBJECT=====n")
    distance_in_mm = sonic.distance_mm()
    print('An incoming object is within -->', distance_in_mm, "mm")
    distance_in_cm = sonic.distance_cm()
    print('An incoming object is within -->', distance_in_cm, "cm")

    #LED PART
    if distance_in_cm < 200:
        print('Too Close')
        RED_pin.on()
        sleep(0.5)
        RED_pin.off()
        sleep(0.3)
    else:
        RED_pin.off()
        print('Normal')
        sleep(2)


    #BUZZER PART
    for b in range (5) :
      sound_buzzer = PWM(BUZZER_pin, freq = 800, duty =50)
      sleep(0.5)
      sound_buzzer = PWM(BUZZER_pin, freq = 800, duty =0)
      sleep(1)


    #Lets start using OLED
    screen.fill(1) # 0 for BLACK , 1 for WHITE
    screen.text(str(distance_in_mm),5, 10, 0)
    screen.text(str(distance_in_cm),30, 30, 0)
    screen.show() # A must!! ( IF not the OLED will not display )


    





    sleep(2)