from machine import Pin, ADC
from lcd1602 import LCD
from hcsr04 import HCSR04
import uasyncio as asyncio
lcd = LCD()
led_red = Pin(12, Pin.OUT)
led_green = Pin(13, Pin.OUT)
pushbutton = Pin(16, Pin.IN, Pin.PULL_UP)
pot = ADC(Pin(4))
sensor = HCSR04(trigger_pin=Pin(3), echo_pin=Pin(2))
threshold = 50 # Initialize threshold
async def display():
lcd.clear()
lcd.write(0, 0, "Distance Counter")
await asyncio.sleep(2)
async def blink_green_led():
while True:
led_green.value(1)
await asyncio.sleep(0.1)
led_green.value(0)
await asyncio.sleep(0.1)
async def standby_mode():
while True:
anVal = pot.read_u16() / 65535
pot_value = int(10 + anVal * 90)
lcd.clear()
lcd.write(0, 0, "User Input")
lcd.write(0, 1, "Dist: {} cm".format(pot_value))
await asyncio.sleep(0.5)
if pushbutton.value() == 0:
return pot_value
async def scan_mode(threshold):
while True:
distance = sensor.distance_cm()
if distance < threshold:
led_red.on()
lcd.clear()
lcd.write(0, 0, "Distance: {} cm".format(distance))
lcd.write(0, 1, "Object: Yes")
else:
led_red.off()
lcd.clear()
lcd.write(0, 0, "Distance: {} cm".format(distance))
lcd.write(0, 1, "Object: No")
await asyncio.sleep(0.1)
if pushbutton.value() == 0:
led_red.off()
return
async def main():
await display()
while True:
threshold = await standby_mode()
await scan_mode(threshold)
loop = asyncio.get_event_loop()
loop.create_task(blink_green_led())
loop.create_task(main())
loop.run_forever()