from machine import Pin,PWM
import neopixel
import utime
import random
button = Pin(18, Pin.IN)
RGB_pin = Pin(26, Pin.OUT)
buzzer = PWM(Pin(33))
buzzer.duty_u16(0)
trig = 27
np = neopixel.NeoPixel(RGB_pin, n=6, bpp=3, timing=1)

def setup():  
    for i in range(0,6):
        np[i] = (0,0,0)
    np.write()
    
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)   
            print("The current distance is：{:.2f} cm".format(distance))
            if distance > 2 and distance < 20:                
                for n in range(0,6):
                    np[n] = (255,0,0)
                np.write()
                buzzer.duty_u16(2000)
                buzzer.freq(294)
                utime.sleep(0.1)
            else:
                for n in range(0,6):
                    np[n] = (0,255,0)
                np.write()
                buzzer.duty_u16(0)
            
if __name__ == "__main__":
    setup()
    loop()

