
from machine import Pin, PWM, Timer
from time import sleep, ticks_us

TRIG_PIN	= 7							# Pi Pico W powered by 3.7V LiPo thru 1N5819
ECHO_PIN	= 6							# SR04 powered by same source

trig_pin   	= Pin(TRIG_PIN, Pin.OUT)	# SR04
echo_pin    = Pin(ECHO_PIN, Pin.IN)		# SR04
led_pin     = machine.Pin("LED", machine.Pin.OUT)	# LED pin, obscure location not 25

data_rdy_flag = False					# distance data ready
echo_start    = 0						# time of echo signal rising
echo_dist     = 0						# result of echo pulse in cm
    
def echo_isr(pin):
    global data_rdy_flag				# flag set if data ready
    global echo_start					# save time start for next call
    global echo_dist					# result
    if(echo_pin.value()):					# echo has risen
        echo_start = ticks_us()			# echo rises ~500uS after trigger
    else:								# echo has fallen
        echo_dist = int((ticks_us()-echo_start)*0.0171)
        data_rdy_flag = True			# data ready

def sr04trigger(timer):
    trig_pin.value(0)					# echo rises ~500 uS after trig falls
    trig_pin.value(1)					# trig high for ~12 uS
    trig_pin.value(1)					# echo will fall after ~150mS if no target
    trig_pin.value(0)					# reset trig pin
        
echo_pin.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=echo_isr) # int on change
trig_rate = Timer(mode=Timer.PERIODIC, period=200, callback=sr04trigger) # software timer

while True:
    while data_rdy_flag == False:		# wait for next valid data
        sleep(.1)
    print(echo_dist, "cm")
    data_rdy_flag = False
    led_pin.value(not led_pin.value())	# Toggle the LED state (ON/OFF)


