from machine import Pin, ADC
import uasyncio as asyncio
from lcd1602 import LCD
from hcsr04 import HCSR04
led_green = 13
led_red = 12
button = 16
potentiometer = 28
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)
min_dist = 10
max_dist = 100
async def blink_ledR():
while True:
ledR.value(1)
await asyncio.sleep(0.25)
ledR.value(0)
await asyncio.sleep(0.25)
async def display_startup():
lcd.clear()
lcd.write(0, 0, " Pengesan Jarak ")
await asyncio.sleep(2)
async def setup_mode():
lcd.clear()
lcd.write(0, 0, " Tekan PB ")
lcd.write(0, 1, " untuk MULA ")
while PB.value() == 1:
await asyncio.sleep(0.1)
async def read_potentiometer(prompt):
while True:
pot_value = int(10 + (pot.read_u16() / 65535) * 90)
lcd.clear()
lcd.write(0, 0, prompt)
lcd.write(0, 1, "Dist: {} cm".format(pot_value))
await asyncio.sleep(0.1)
if PB.value() == 0:
await asyncio.sleep(0.5)
return pot_value
async def scan_mode():
global min_dist, max_dist
while True:
distance = int(sensor.distance_cm())
if min_dist <= distance <= max_dist:
lcd.clear()
lcd.write(0, 0, "Distance: {} cm".format(distance))
lcd.write(0, 1, "Status: OK")
ledG.value(0)
else:
lcd.clear()
lcd.write(0, 0, "Distance: {} cm".format(distance))
lcd.write(0, 1, "Status: OUT OF RANGE")
ledG.value(1)
await asyncio.sleep(0.1)
if PB.value() == 0:
await asyncio.sleep(0.5)
return
async def main():
await display_startup()
while True:
await setup_mode()
ledG.value(0)
global min_dist, max_dist
min_dist = await read_potentiometer("Set Min Distance")
max_dist = await read_potentiometer("Set Max Distance")
await scan_mode()
loop = asyncio.get_event_loop()
loop.create_task(blink_ledR())
loop.create_task(main())
loop.run_forever()