# SmartSecurityGuard - Enhanced Security System Project
print("SmartSecurityGuard - Enhanced Security System Project")
print("4/12/2023")
print("created by ZUNIE")


from machine import Pin, PWM, SoftI2C, ADC
from utime import sleep
# Import the correct libraries for your hardware
# Replace UltraSONIC, SERVOLLLL, and OLEDLIBRARY with the correct names
import UltraSONIC  
import SERVOLLLL
import OLEDLIBRARY

# Pin declaration
MOTION_LED = Pin(26, Pin.OUT)
sensor_motion = Pin(14, Pin.IN)
LDR_Pin = ADC(Pin(15, Pin.IN))
LUX_LED = Pin(18, Pin.OUT)
Pin_scl_sda = SoftI2C(scl=Pin(22), sda=Pin(21))
TRIG_pin = Pin(5, Pin.OUT)
ECHO_pin = Pin(4, Pin.IN)
BUZZER_pin = Pin(2, Pin.OUT)
signal_LED = Pin(27, Pin.OUT)
Servo_Pin = Pin(13, Pin.OUT)

# CREATE OBJECTS
# Use the correct library name for your ultrasonic sensor
sonic = UltraSONIC.HCSR04(trigger_pin=TRIG_pin, echo_pin=ECHO_pin)
skrin = OLEDLIBRARY.SSD1306_I2C(width=128, height=64, i2c=Pin_scl_sda)
blade = SERVOLLLL.Servo(pin=Servo_Pin)

# Function to handle security alert
def handle_alert():
    # Activate Alert
    signal_LED.on()
    tone_buzzer = PWM(BUZZER_pin, freq=1500, duty=50)
    blade.move(180)
    sleep(2)
    # Reset Alert
    signal_LED.off()
    tone_buzzer.deinit()
    blade.move(0)

# Main Loop
while True:
    # Motion Detection
    status_intruder = sensor_motion.value()
    if status_intruder == 1:
        print("Intruder detected!")
        for a in range(5):
            MOTION_LED.on()
            sleep(0.5)
            MOTION_LED.off()
            sleep(0.5)
        # Handle Alert
        handle_alert()
    else:
        print("No intruder.")
        MOTION_LED.off()

    # Light Intensity Sensing
    light_intensity_value = LDR_Pin.read()
    print("Light Intensity:", light_intensity_value)
    light_in_voltage = light_intensity_value / 4096 * 5.0
    print("Voltage Detected Based on Light Absorption:", light_in_voltage, "V")

    if light_in_voltage >= 4.17:
        LUX_LED.off()
        skrin.fill(1)  # Clear the display
        skrin.text("Secure Area", 15, 30, 1)
        skrin.show()
    elif light_in_voltage <= 0.19:
        LUX_LED.on()
        skrin.fill(1)  # Clear the display
        skrin.text("Low Light!", 15, 30, 1)
        skrin.show()

    # Ultrasonic Object Detection
    distance_in_mm = sonic.distance_mm()
    print("Distance from Ultrasonic Sensor:", distance_in_mm, "mm")

    if distance_in_mm < 200:  # Adjust the threshold as needed
        print("Object detected in proximity!")
        # Handle Alert for close proximity
        handle_alert()

    sleep(3)