from machine import Pin, ADC
from utime import sleep
import uasyncio as asyncio
from lcd1602 import LCD
from hcsr04 import HCSR04
lcd = LCD()
pot_pin = ADC(Pin(28))
button_pin = Pin(16, Pin.IN, Pin.PULL_UP)
green_led = Pin(13, Pin.OUT)
red_led = Pin(12, Pin.OUT)
ultrasonic_sensor = HCSR04(trigger_pin=2, echo_pin=3)
DIST_MIN = 10
DIST_MAX = 100
LCD_MESSAGE_DELAY = 2
threshold_distance = 50
def get_pot_value():
return int((pot_pin.read_u16() / 65535) * (DIST_MAX - DIST_MIN) + DIST_MIN)
async def get_distance():
try:
distance = ultrasonic_sensor.distance_cm()
return distance
except OSError:
return None
async def display_startup_message():
lcd.clear()
lcd.write(0, 0, "Distance Counter")
await asyncio.sleep(LCD_MESSAGE_DELAY)
async def blink_green_led():
await asyncio.sleep(LCD_MESSAGE_DELAY)
while True:
green_led.value(1)
await asyncio.sleep(0.1)
green_led.value(0)
await asyncio.sleep(0.1)
async def standby_mode():
global threshold_distance
while True:
pot_value = get_pot_value()
lcd.clear()
lcd.write(0, 0, "User Input")
lcd.write(0, 1, f"Dist: {pot_value} cm")
await asyncio.sleep(0.5)
if not button_pin.value():
await asyncio.sleep(0.2)
if not button_pin.value():
return pot_value
async def scan_mode(threshold):
while True:
distance = await get_distance()
if distance is not None:
lcd.clear()
lcd.write(0, 0, f"Distance: {int(distance)} cm")
object_present = "Yes" if distance < threshold else "No"
lcd.write(0, 1, f"Object: {object_present}")
if distance < threshold:
red_led.value(1)
else:
red_led.value(0)
else:
lcd.clear()
lcd.write(0, 0, "Error")
lcd.write(0, 1, "Out of range")
await asyncio.sleep(0.5)
if not button_pin.value():
await asyncio.sleep(0.2)
if not button_pin.value():
red_led.value(0)
return
async def main():
await display_startup_message()
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()