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

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

pbPin = Pin(16,Pin.IN,Pin.PULL_UP)
ledG = Pin(13,Pin.OUT)
ledR = Pin(12,Pin.OUT)
anPin = ADC(Pin(28))
anVal=0

lcd.clear()
lcd.write(0,0,"Distance Counter")
sleep(2)
lcd.clear()

treshold = 0
def settingTreshold():
    lcd.clear()
    global anVal
    while True:
        anVal = -(90*anPin.read_u16() + 655350) / -65535
        if anVal<100:
            lcd.write(10,1," ")
        lcd.write(0,0,"User Input")
        lcd.write(0,1,"Dist:" + " {:.0f}".format(anVal) + "cm")
        if pbPin.value()==0:
            treshold = anVal
            sleep(0.3)
            lcd.clear()
            break

toggleLedG = True
status = " "

async def ledGreenBlink():
    global toggleLedG
    global anVal
    global status
    while True:
        distance = sensor.distance_cm()
        toggleLedG = not toggleLedG
        
        if distance < anVal:
            status = "Yes"
            ledR.off()
            if toggleLedG==1:
                ledG.on()
            else:
                ledG.off()
        if distance >= anVal:
            status = "No "
            ledG.off()
            ledR.on()

        lcd.write(0,0,"Distance:" + " {:.0f}".format(distance) + "cm")
        lcd.write(0,1,"Object: " + status)
        if anVal<100:
            lcd.write(13,1,str(" {:.0f}".format(anVal)))
        if anVal==100:
            lcd.write(12,1,str(" {:.0f}".format(anVal)))
        
        if distance>=10 and distance<100:
            lcd.write(14,0," ")
        if distance<10:
            lcd.write(13,0," ")

        await asyncio.sleep(0.5)

async def checkPBrun():
    while True:
        if pbPin.value()==0:
            sleep(0.3)
            settingTreshold()
            ledG.off()
        await asyncio.sleep(0.1)

settingTreshold()

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