import neopixel
import _thread
from machine import Pin, ADC
from time import sleep, sleep_us, time_ns
SOUND_SPEED = 0.034
CM_TO_INCH = 0.393701
p5_trigger = Pin(5, Pin.OUT)
p18_echo = Pin(18, Pin.IN)
ledstrip = neopixel.NeoPixel(Pin(4), 1)
global ledcolor
ledcolor = 0
def measure(trig_pin : Pin, echo_pin : Pin):
trig_pin.off()
sleep_us(2)
trig_pin.on()
sleep_us(10)
trig_pin.off()
start_pulse = time_ns()
while not echo_pin.value():
pass
end_pulse = time_ns()
while echo_pin.value():
end_pulse = time_ns()
duration = end_pulse - start_pulse
distanceCm = (duration / 2000) * SOUND_SPEED
return distanceCm
def set_distance_to_color(trig_pin : Pin, echo_pin : Pin) -> tuple:
distance = measure(trig_pin, echo_pin)
# normalization
if distance < 0:
distance = 0
elif distance > 255:
distance = 255
color_bright = 255 - distance # the closer the brighter
return int(color_bright)
def run_ultrasonic_color_manipulation(trig_pin : Pin, echo_pin : Pin):
'''
This function should update the global variable "ledcolor" according to
the supersonic sensor read.
@param trig_pin: trigger pin of a sound sensor
@param echo_pin: echo pin of the same sound sensor
'''
while True:
global ledcolor
ledcolor = set_distance_to_color(trig_pin, echo_pin)
def main():
global ledcolor
_thread.start_new_thread(run_ultrasonic_color_manipulation, (p5_trigger, p18_echo))
while True:
sleep(0.1)
ledstrip[0] = (ledcolor, 0, 255)
print(ledstrip[0])
ledstrip.write()
main()