from machine import Pin, ADC
import uasyncio as asyncio
from hcsr04 import HCSR04
from lcd1602 import LCD
lcd = LCD()
sensor = HCSR04(trigger_pin=2, echo_pin=3)
adc = ADC(28)
button = Pin(16, Pin.IN, Pin.PULL_UP)
ledR = Pin(12, Pin.OUT)
ledG = Pin(13, Pin.OUT)
object_detected = False # Initialize object_detected variable
async def blink_ledG():
while True:
ledG.value(1)
await asyncio.sleep(0.5)
ledG.value(0)
await asyncio.sleep(0.5)
async def display_splash_screen():
while True:
lcd.clear()
lcd.write(0, 0, "Distance Counter ")
await asyncio.sleep(2)
async def display_standby():
lcd.clear()
lcd.write(0, 0, "User Input")
global object_detected # Declare object_detected as global
while button.value() == 1:
distance = int(10 + (adc.read_u16() / 65535) * 90)
lcd.write(0, 1, "Dist: {} cm".format(distance))
await asyncio.sleep(0.5)
if distance >= 10 and distance <= 100:
object_detected = True # Set object_detected to True
else:
object_detected = False # Set object_detected to False
async def display_distance():
global object_detected # Declare object_detected as global
while True:
distance = sensor.distance_cm()
lcd.clear()
lcd.write("Distance: {} cm".format(int(distance)), 0, 0)
if distance >= 10 and distance <= 100:
lcd.write("Object: {}".format("Yes" if object_detected else "No"), 0, 16)
ledR.value(1)
else:
lcd.write(0, 1, "Object: No")
ledR.value(0)
await asyncio.sleep(0.1)
if button.value() == 0:
await asyncio.sleep(0.5)
return
async def display_startup():
lcd.clear()
lcd.write(0, 0, "Starting Up...")
await asyncio.sleep(2)
async def main():
await display_startup()
asyncio.create_task(display_splash_screen())
await asyncio.sleep(2)
await display_standby()
while True:
await display_distance()
await display_standby()
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()