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

# Pin definitions
led_green = 13
led_red = 12
button = 16
potentiometer = 28

# Device initialization
lcd = LCD()
pot = ADC(potentiometer)
ledR = Pin(led_red, Pin.OUT)
ledG = Pin(led_green, Pin.OUT)
PB = Pin(button, Pin.IN, Pin.PULL_UP)
sensor = HCSR04(trigger_pin=2, echo_pin=3)

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

async def led_blink():
    while True:
        ledG.value(not ledG.value())  # Toggle LED state
        await asyncio.sleep_ms(100)   # 10 Hz blink

async def standby_mode():
    while True:
        anVal = pot.read_u16() / 65535  # Normalize potentiometer value
        pot_value = int(10 + anVal * 90)  # Convert pot value to distance (10 to 100 cm range)
        lcd.clear()
        lcd.write(0, 0, "Input Pengguna")
        lcd.write(0, 1, "Dist: {} cm".format(pot_value))
        await asyncio.sleep(0.5)
        if PB.value() == 0:  # Button press detected
            return pot_value

async def scan_mode(threshold):
    while True:
        distance = sensor.distance_cm()
        anVal = pot.read_u16() / 65535  # Normalize potentiometer value
        pot_value = int(10 + anVal * 90)  # Convert pot value to distance (10 to 100 cm range)
        lcd.clear()
        lcd.write(0, 0, "Jarak: {} cm".format(distance))
        
        if distance < threshold and pot_value < 100:
            lcd.write(0, 1, "Objek: Ya")
            ledR.on()
            ledG.off()
        else:
            lcd.write(0, 1, "Objek: Tidak")
            ledR.off()
            ledG.on()
        
        await asyncio.sleep(0.1)
        if PB.value() == 0:  # Button press detected
            ledR.off()
            ledG.on()
            return

async def main():
    await display_startup()
    
    while True:
        threshold = await standby_mode()
        await scan_mode(threshold)

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