import time
import board
import digitalio
import pulseio
import analogio

# Set up pins for ultrasonic sensor
TRIG = digitalio.DigitalInOut(board.GP4)
TRIG.direction = digitalio.Direction.OUTPUT
ECHO = board.GP5

# Set up LED
LED = digitalio.DigitalInOut(board.GP13)
LED.direction = digitalio.Direction.OUTPUT

# Set up KY-033 Line Tracking Sensor (Analog)
LIGHT_SENSOR = analogio.AnalogIn(board.GP26)

# Initialize PulseIn for ultrasonic sensor
pulse = pulseio.PulseIn(ECHO, maxlen=1, idle_state=False)

# Function to control LED based on distance and light level
def led_alert(distance, light_level):
    # Define thresholds
    DISTANCE_THRESHOLD = 1000  # cm
    LIGHT_THRESHOLD = 20000   # Adjust this value based on your environment for "darkness"
    
    if distance <= DISTANCE_THRESHOLD and light_level <= LIGHT_THRESHOLD:
        LED.value = True  # Turn LED on if both conditions are met
        print("LED ON: Object detected and it's dark.")
    else:
        LED.value = False  # Turn LED off otherwise
        print("LED OFF: Conditions not met.")

# Function to send pulse and measure response
def send_pulse():
    TRIG.value = False
    time.sleep(0.000002)
    TRIG.value = True
    time.sleep(0.00001)
    TRIG.value = False

    # Measure pulse duration
    pulse.clear()
    while len(pulse) == 0:
        pass
    pulse_width = pulse[0] if len(pulse) > 0 else None
    return pulse_width

# Function to read light level from KY-033
def read_light_level():
    return LIGHT_SENSOR.value

while True:
    # Ultrasonic sensor measurement
    pulse_width = send_pulse()
    if pulse_width is not None:
        distance = pulse_width * 0.034 / 2  # Calculate distance in cm
        print("Distance:", distance, "cm")
    else:
        distance = None
        print("No pulse detected")

    # Light level measurement
    light_level = read_light_level()
    print("Light Level:", light_level)
    
    # Control LED based on distance and light conditions
    if distance is not None:
        led_alert(distance, light_level)
    
    time.sleep(5)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT