from	machine	import	Pin, ADC
import	time
from	collections	import	deque

pin = Pin(33, Pin.IN, Pin.PULL_UP)
adc = ADC(pin, atten=ADC.ATTN_0DB)				# 0..950 mV
buzzer = Pin(32, Pin.OUT, value=0)


# see decay on pin SOUND, buzzer period=210 uSec / 5 kHz, ampl=1 Volt)
def test1():
    buzzer(1)
    time.sleep_ms(50)
    buzzer(0)
    
    
# measure adc time
def test2():
    t1 = time.ticks_us()
    a = adc.read_uv()							# 320 uSec / 3 kHz
    t2 = time.ticks_us()
    print(t2-t1)


# measure amplitudes
# silent=75_000, buzzer=700_000 (including 75_000 i.e. sinus)
def test3():
    for _ in range(10):
        print(adc.read_uv())
    buzzer(1)
    print()
    for _ in range(100):
        print(adc.read_uv())
    buzzer(0)
    print()
    for _ in range(100):
        print(adc.read_uv())


# Highest Morse speed = 30 words per minute
# --> tick = 60000 / (30 * 50) = 40 mSec
# sample rate := 40 mSec / 10 = 4 mSec, treshold 500_000
def test4():

    def sample():
        que = deque((), 14)
        for _ in range(14):				# 4 mSec  / 320 uSec
            que.append(adc.read_uv())
        return max(list(que)) >  500_000
    

    for _ in range(5): print(sample())
    buzzer(1)
    print()
    for _ in range(20): print(sample())
    buzzer(0)
    print()
    for _ in range(20): print(sample())


test4()

    
    