# mPy - Demonstrating ultrasonic distance measuring on kit FKS0001
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-07-03  initoal release

from	machine		import	Pin
import	time
from	driver_lcd	import	Lcd

# ===================== Ultra-sonic disdtance =============================

class UsDistance:
    
    def __init__(self, pin_trig=32, pin_echo=35):
        self.trig = Pin(pin_trig, Pin.OUT, value=0)
        self.echo = Pin(pin_echo, Pin.IN, Pin.PULL_UP)
        

    # return the measured gap in cm
    def get(self):
        self.trig(1)								# send impulse
        time.sleep_us(10)
        self.trig(0)
        while not self.echo(): pass					# wait until echo high
        t1 = time.ticks_us()
        while self.echo(): pass						# wait until echo low
        dt = time.ticks_diff(time.ticks_us(), t1)	# pulse width in uSec
        return round(dt / 59, 1)					# gap in cm @ 340 m/sec
    
# ============================= main ====================================

# Print distance to shell and LCD at 0.5 Sec
def main():
    lcd  = Lcd()
    dist = UsDistance()
    while True:
        gap = dist.get()
        print(gap)
        lcd.print('gap:', gap, 'cm') 
        time.sleep(0.5)
        
        
main()

# ============================== end ====================================
