print("Parking Gate System")
print("Date: 8/12/23")
print("Created by Luqman")

#Import libraries
import library_oled
import library_ultrasonic
import library_servo
from machine import Pin, PWM, I2C
from utime import sleep

#Pin declaration
oled_width = 128
oled_height = 64
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
TRIG_pin = Pin(33, Pin.IN)
ECHO_pin = Pin(25, Pin.OUT)
sensor_motion = Pin(17, Pin.IN)
led_green = Pin(14, Pin.OUT)
Servo_Pin = Pin(18, Pin.OUT)
Servo_Pin2 = Pin(5, Pin.OUT)
built_in_LED = Pin(14, Pin.OUT)
buzzer_pin = Pin(19, Pin. OUT)



#Create object for sensor with libraries
skrin = library_oled.SSD1306_I2C(oled_width, oled_height, i2c)
Ultrasonic = library_ultrasonic.HCSR04(trigger_pin=TRIG_pin, echo_pin=ECHO_pin)
gate = library_servo.Servo(pin = Servo_Pin)
gate2 = library_servo.Servo(pin = Servo_Pin2)

#Main program
target = 10

while True:
    status_car = sensor_motion.value()
    distance_cm = Ultrasonic.distance_cm()

    if status_car ==True:
        #OLED TO DISPLAY
        skrin.text("Welcome to",10 ,10 )
        skrin.show()
        skrin.text("Parking Company",10 ,25 )
        skrin.show()
        built_in_LED.on()
        sleep(3)
        built_in_LED.off()
        led_green.on()
        gate.move(90)
        sleep(4)
        gate.move(180)
        sleep(1)
        gate.move(90)
        led_green.off()
        sleep(4)
    else:   
        led_green.off()
        skrin.fill(0)
        skrin.show()

    if distance_cm < 150:
        value = int(input("Enter the parking code:"))
        if value > target:
            print("WRONG,", value, "too high")
            #BUZZER PART
            for B in range (3):
                tone_buzzer = PWM(buzzer_pin, freq =440, duty =50)
                sleep(0.5)
                tone_buzzer = PWM(buzzer_pin, freq =440, duty =0)
        elif int(value) < target:
            print("WRONG!,",value, "too low")
            #BUZZER PART
            for B in range (3):
                tone_buzzer = PWM(buzzer_pin, freq =400, duty =50)
                sleep(0.5)
                tone_buzzer = PWM(buzzer_pin, freq =400, duty =0)
        else:
            print("Alright, you can park here!")
            for A in range (1):
                led_green.on()
                gate2.move(90)
                sleep(4)
                gate2.move(180)
                sleep(2)
                gate2.move(90)
                led_green.off()
                sleep(0.5)      
    else:
        built_in_LED.off()
        skrin.fill(0)
        skrin.show()

        sleep(3)