from machine import Pin,PWM
import utime

button = Pin(18,Pin.IN)
buzzer = PWM(Pin(33))
buzzer.duty_u16(0)
trig = 27
Tone = [392, 440, 494, 523, 587, 659, 698, 784]

def getDistance(trig):
    trig = Pin(27,Pin.OUT)
    trig.value(0)
    utime.sleep_us(2)
    trig.value(1)
    utime.sleep_us(10)
    trig.value(0)
    trig = Pin(27,Pin.IN)
    while trig.value() == 0:
        start = utime.ticks_us()
    while trig.value() == 1:
        end = utime.ticks_us()
    d = (end - start) * 0.0343 / 2 
    return d

  
def loop():
    while button.value() == 1:
        pass
    else:
        while True:
            distance = getDistance(trig)
            num = int(distance / 5)
            if num >= 0 and num <= 6:
                buzzer.duty_u16(2000)
                buzzer.freq(Tone[num])
                utime.sleep(0.1)
            else:
                buzzer.duty_u16(0)
if __name__ == "__main__":
    loop()
    