from machine import Pin, ADC
import uasyncio as asyncio
from hcsr04 import HCSR04
from lcd1602 import LCD

lcd = LCD()
sensor = HCSR04(trigger_pin=2, echo_pin=3)

adc = ADC(28)
button = Pin(16, Pin.IN, Pin.PULL_UP)
ledR = Pin(12, Pin.OUT)
ledG = Pin(13, Pin.OUT)

object_detected = False  # Initialize object_detected variable

async def display_startup():
    lcd.clear()
    lcd.write(0, 0, "Distance Counter")
    await asyncio.sleep(2)

async def blink_ledG():
    while True:
        ledG.value(1)
        await asyncio.sleep(0.5)
        ledG.value(0)
        await asyncio.sleep(0.5)

async def display_standby():
    lcd.clear()
    lcd.write(0, 0, "User Input")

    global object_detected  # Declare object_detected as global

    while button.value() == 1:
        distance = int(10 + (adc.read_u16() / 65535) * 90)
        lcd.write(0, 1, "Dist: {} cm".format(distance))
        await asyncio.sleep(0.5)

        if distance >= 10 and distance <= 100:
            object_detected = True  # Set object_detected to True
        else:
            object_detected = False  # Set object_detected to False

async def display_distance():
    global object_detected  # Declare object_detected as global

    while True:
        distance = sensor.distance_cm()
        lcd.clear()
        lcd.write(0,0, "Distance: {} cm".format(int(distance)))

        if distance >= 10 and distance <= 100:
            lcd.write(0,1, "Object: {}".format("Yes" if object_detected else "No"))
            ledR.value(1)
        else:
            lcd.write(0, 1, "Object: No")
            ledR.value(0)

        await asyncio.sleep(0.1)

        if button.value() == 0:
            await asyncio.sleep(0.5)
            return



async def main():
    await display_startup()
    await asyncio.sleep(2)
    await display_standby()

    while True:
        await display_distance()
        await display_standby()

loop = asyncio.get_event_loop()
loop.create_task(blink_ledG())
loop.create_task(main())
loop.run_forever()
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT