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

led_green = Pin(13, Pin.OUT)
led_red = Pin(12, Pin.OUT)
button = Pin(16, Pin.IN, Pin.PULL_UP)
potentiometer = ADC(28)

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

async def blink_red_led():
    while True:
        led_red.value(1)
        await asyncio.sleep(0.25)  # 0.25 seconds on
        led_red.value(0)
        await asyncio.sleep(0.25)  # 0.25 seconds off

async def display_startup():
    lcd.clear()
    lcd.write(0, 0, "Pengesan Jarak")
    await asyncio.sleep(2)
    lcd.clear()
    lcd.write(0, 0, "Tekan PB")
    lcd.write(0, 1, "untuk MULA")
    while button.value() == 1:
        await asyncio.sleep(0.1)

async def read_potentiometer(prompt):
    while True:
        pot_value = int(10 + (potentiometer.read_u16() / 65535) * 90)
        lcd.clear()
        lcd.write(0, 0, prompt)
        lcd.write(0, 1, "Dist: {} cm".format(pot_value))
        await asyncio.sleep(0.5)
        if button.value() == 0:
            await asyncio.sleep(0.5)
            return pot_value

async def scan_mode(min_distance, max_distance):
    while True:
        distance = sensor.distance_cm()
        lcd.clear()
        lcd.write(0, 0, "Distance: {} cm".format(distance))
        if distance < min_distance or distance > max_distance:
            lcd.write(0, 1, "OUT OF RANGE")
            led_green.value(1)
            led_red.value(0)
        else:
            lcd.write(0, 1, "Status: OK")
            led_green.value(0)
            led_red.value(1)
        await asyncio.sleep(0.1)
        if button.value() == 0:
            await asyncio.sleep(0.5)
            return

async def main():
    blink_task = asyncio.create_task(blink_red_led())  # Start blinking immediately
    while True:
        await display_startup()
        blink_task.cancel()  # Stop blinking after the startup phase
        led_red.value(0)  # Ensure the red LED is off

        # Read the minimum distance value
        min_distance = await read_potentiometer("Set Min Dist")
        lcd.clear()
        lcd.write(0, 0, "Min Dist Set")
        await asyncio.sleep(2)

        # Read the maximum distance value
        max_distance = await read_potentiometer("Set Max Dist")
        lcd.clear()
        lcd.write(0, 0, "Max Dist Set")
        await asyncio.sleep(2)

        blink_task = asyncio.create_task(blink_red_led())  # Resume blinking during scan mode
        await scan_mode(min_distance, max_distance)
        blink_task.cancel()  # Stop blinking after the scan mode
        led_red.value(0)  # Ensure the red LED is off again

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