import time
import utime
from neopixel import Neopixel
import machine
pixels = Neopixel(17, 0, 6, "GRB")
trigger1 = machine.Pin(27, machine.Pin.OUT)
echo1 = machine.Pin(26, machine.Pin.IN)
# Define the color range for the animation
start_color = (0xb6, 0xe4, 0x30) # Bright Green
end_color = (0x80, 0x00, 0x00) # Dark Red
# Initialize variables for pixel index
pixel_index = 0
def ultra1(): # Sensor LINKS
trigger1.low()
utime.sleep_us(2)
trigger1.high()
utime.sleep_us(5)
trigger1.low()
while echo1.value() == 0:
signaloff = utime.ticks_us()
while echo1.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance1 = (timepassed * 0.0343) / 2
print("De sensor ziet het obstakel op ", distance1, "cm")
return distance1
def interpolate_color(start_color, end_color, distance, max_distance):
"""
Interpolate color between start_color and end_color based on distance.
The closer the distance is to max_distance, the closer the color will be to end_color.
"""
ratio = distance / max_distance
new_color = tuple(int(start + ratio * (end - start)) for start, end in zip(start_color, end_color))
return new_color
while True:
distance = ultra1()
num_leds = min(int(distance / 25), 16) # Calculate the number of illuminated LEDs
print("Aantal LEDs:", num_leds)
for i in range(num_leds):
# Interpolate color based on distance
new_color = interpolate_color(start_color, end_color, distance, 400)
pixels.set_pixel(i, new_color)
for i in range(num_leds, 16): # Turn off the remaining LEDs
pixels.set_pixel(i, (0, 0, 0))
pixels.show()
time.sleep(0.1)