#AFRINA RIDWANA BINTI AHMAD RIZAL
import machine
import uasyncio as asyncio
from lcd1602 import LCD
from hcsr04 import HCSR04
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():
lcd.clear()
lcd.write(0, 0, "Distance Counter")
async def led_blink():
await asyncio.sleep(2)
while True:
ledG.value(1)
await asyncio.sleep(0.05)
ledG.value(0)
await asyncio.sleep(0.05)
async def standby_mode():
last_pot_value = None
while True:
anVal = pot.read_u16() / 65535.0
pot_value = int(10 + anVal * 100)
if pot_value != last_pot_value:
lcd.clear()
lcd.write(0, 0, "User Input")
lcd.write(0, 1, "Dist: {} cm".format(pot_value))
last_pot_value = pot_value
await asyncio.sleep(0.5)
if PB.value() == 0:
await asyncio.sleep(0.2)
while PB.value() == 0:
await asyncio.sleep(0.1)
return pot_value
async def scan_mode(threshold):
last_distance = None
while True:
distance = sensor.distance_cm()
if distance != last_distance:
ledR.value(1 if distance < threshold else 0)
lcd.clear()
lcd.write(0, 0, "Distance: {} cm".format(distance))
lcd.write(0, 1, "Object: Yes" if distance < threshold else "Object: No")
last_distance = distance
await asyncio.sleep(0.1)
if PB.value() == 0:
await asyncio.sleep(0.2)
while PB.value() == 0:
await asyncio.sleep(0.1)
ledR.off()
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()