from machine import Pin,PWM
import utime
import neopixel
import random

trig = 27
button = Pin(18, Pin.IN)
RGB_pin = Pin(26, Pin.OUT)
np = neopixel.NeoPixel(RGB_pin, n=6, bpp=3, timing=1)
buzzer = PWM(Pin(33))
buzzer.duty_u16(0)
def motor(L12,L13,R14,R15):
    PWM(Pin(12)).duty(L12) 
    PWM(Pin(13)).duty(L13) 
    PWM(Pin(14)).duty(R14) 
    PWM(Pin(15)).duty(R15)
def setup():  # Turn off all RGB lights
    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 Map(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

def loop():
    while button.value() == 1:
        pass
    else:
        while True:
            distance = getDistance(trig)   
            print("The current distance is：{:.2f} cm".format(distance))
            if distance <= 100 and distance >= 5:
                Speed = int(Map(distance,5,100,0,1023))
                motor(Speed,0,Speed,0)
                for n in range(0,6):
                    np[n] = (255,0,0)
                np.write()
                buzzer.duty_u16(2000)
                buzzer.freq(587)
                utime.sleep(Speed / 1023)
                for n in range(0,6):
                    np[n] = (0,0,0)
                np.write()
                buzzer.duty_u16(0)
                utime.sleep(Speed / 1023)
            
if __name__ == "__main__":
    setup()
    loop()
