import machine
import uasyncio as asyncio
from lcd1602 import LCD
from hcsr04 import HCSR04
# Initialize components
i2c = machine.I2C(1, scl=machine.Pin(7), sda=machine.Pin(6))
lcd = LCD(addr=0x27)
pot = machine.ADC(28)
ledR = machine.Pin(12, machine.Pin.OUT)
ledG = machine.Pin(13, machine.Pin.OUT)
PB = machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_UP)
sensor = HCSR04(trigger_pin=2, echo_pin=3)
async def display_startup():
# 4.1 Red LED blinking at 2Hz
for _ in range(4): # Blink LED for 2 seconds
ledR.value(1)
await asyncio.sleep_ms(250)
ledR.value(0)
await asyncio.sleep_ms(250)
# 4.2 Display "Pengesan Jarak" for 2 seconds
lcd.clear()
lcd.write(0, 0, "Pengesan Jarak")
await asyncio.sleep(2)
# 4.3 Display "Tekan PB" and "untuk MULA"
lcd.clear()
lcd.write(0, 0, "Tekan PB")
lcd.write(0, 1, "untuk MULA")
async def wait_for_button_press():
while PB.value():
await asyncio.sleep(0.1)
while not PB.value():
await asyncio.sleep(0.1)
async def setup_min_distance():
while True:
pot_val = int(10 + pot.read_u16() / 65535.0 * 90)
lcd.clear()
lcd.write(0, 0, "Min Dist: {}".format(pot_val))
lcd.write(0, 1, "Push PB to confirm")
await asyncio.sleep(0.5)
if not PB.value():
await wait_for_button_press()
return pot_val
async def setup_max_distance():
while True:
pot_val = int(10 + pot.read_u16() / 65535.0 * 90)
lcd.clear()
lcd.write(0, 0, "Max Dist: {}".format(pot_val))
lcd.write(0, 1, "Push PB to start")
await asyncio.sleep(0.5)
if not PB.value():
await wait_for_button_press()
return pot_val
async def monitor_distance(min_dist, max_dist):
while True:
dist = sensor.distance_cm()
lcd.clear()
lcd.write(0, 0, "Distance: {} cm".format(dist))
if min_dist <= dist <= max_dist:
lcd.write(0, 1, "Status: OK")
ledG.off()
else:
lcd.write(0, 1, "OUT OF RANGE")
ledG.on()
await asyncio.sleep(0.5)
if not PB.value():
await wait_for_button_press()
ledG.off()
return
async def main():
while True:
await display_startup()
await wait_for_button_press()
min_dist = await setup_min_distance()
max_dist = await setup_max_distance()
await monitor_distance(min_dist, max_dist)
# Start the asyncio event loop
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()