shiney_light_things/main.py

123 lines
3.0 KiB
Python

import os, machine, time, neopixel, micropython
micropython.alloc_emergency_exception_buf(100)
# how many LEDs are there in a row?
Nled = 16
# define pin for led control
# see reference for GPIO numbers: https://microcontrollerslab.com/wp-content/uploads/2019/05/ESP8266-12E-Wemos-D1-Mini-pinout.jpg
# not all GPIO pins can be used ...
pin_number = 5
neopin = machine.Pin(pin_number, machine.Pin.OUT)
# initialize neopixel object to write to
np = neopixel.NeoPixel(neopin, Nled)
# define pin for button
button = machine.Pin(13, machine.Pin.IN)
# variable and function for button handling
button_pressed = False
def handle_button(pin):
global button_pressed
button_pressed = True
time.sleep_ms(200)
# register button function for interrupt
button.irq(trigger=machine.Pin.IRQ_RISING, handler=handle_button)
# define ranges of LEDs
full = range(0, Nled)
# define colors for LEDs
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
orange = (220, 35, 0)
purple = (255, 0, 255)
white = (255, 255, 255)
off = (0, 0, 0)
# color the leds
def paint(color = white, section = full, single = False):
if single:
section = [section]
for i in section:
if i not in full:
i %= Nled
np[i] = color
np.write()
# get rainbow colors
# Input a value 0 to 255 to get a color value.
# The colours are a transition r - g - b - back to r.
def wheel(pos):
if pos < 0 or pos > 255:
return (0, 0, 0)
if pos < 85:
return (255 - pos * 3, pos * 3, 0)
if pos < 170:
pos -= 85
return (0, 255 - pos * 3, pos * 3)
pos -= 170
return (pos * 3, 0, 255 - pos * 3)
# cycle rainbow colors
def rainbow_cycle(wait):
global button_pressed
n = Nled
while not button_pressed:
for j in range(255):
for i in range(n):
rc_index = (i * 256 // n) + j
np[i] = wheel(rc_index & 255)
np.write()
if button_pressed:
break
time.sleep_ms(wait)
button_pressed = False
# pulsating rainbow
def solid_rainbow(wait):
global button_pressed
while not button_pressed:
for j in range(255):
paint(wheel(j))
if button_pressed:
break
time.sleep_ms(wait)
button_pressed = False
# just a single color
def solid_color(color):
global button_pressed
paint(color)
while not button_pressed:
time.sleep_ms(100)
button_pressed = False
# single led rotating
def chase_single(color, wait):
global button_pressed
while not button_pressed:
for i in full:
paint(color, i, True)
paint(off, i - 1, True)
if button_pressed:
break
time.sleep_ms(wait)
button_pressed = False
while True:
rainbow_cycle(5)
solid_rainbow(200)
chase_single(orange, 50)
chase_single(white, 50)
chase_single(purple, 50)
solid_color(red)
solid_color(green)
solid_color(blue)