light: debounce mode switch, some other improvements

This commit is contained in:
Konstantin Koslowski 2021-04-18 12:03:47 +02:00
parent c4826219bf
commit bfbd8316fc

View file

@ -5,14 +5,13 @@ import time
# Pins
PIN_NP = 5
PIN_Y= 0
PIN_G= 4
PIN_B= 2
PIN_MODE= 0
PIN_COLOR = 4
# NeoPixel
NUM_LED = 16
# y - Mode
MODE_MAX = 5
MODES = [ "off", "on", "color_chase", "rainbow", "strobe" ]
MODE_MAX = 4
MODES = [ "on", "color_chase", "rainbow", "strobe" ]
MODE_STEP = 1
# g - Color
COLOR_MAX = 255
@ -22,39 +21,32 @@ BRIGHTNESS_MAX = 250
BRIGHTNESS_STEP = 50
# Delay
DELAY = 0.1
DELAY_IRQ = 0.5
DELAY_CHASE = 0.05
DELAY_STROBE = 0.2
DELAY_MODE = 0.5
light = None
state = None
ts_mode = 0
def handle_y(pin):
global light, state
if state is None:
state = machine.disable_irq()
def handle_mode(pin):
global light, ts_mode
if time.time() > (ts_mode + DELAY_MODE):
ts_mode = time.time()
light.set_fn("mode")
def handle_g(pin):
global light, state
def handle_color(pin):
global light
light.set_fn("color")
def handle_b(pin):
global light, state
light.set_fn("brightness")
class Light:
def __init__(self):
self.mode = 0
self.color = 0
self.brightness = 0
self.np = neopixel.NeoPixel(machine.Pin(PIN_NP), NUM_LED)
self.sw_y = machine.Pin(PIN_Y, machine.Pin.IN, machine.Pin.PULL_UP)
self.sw_g = machine.Pin(PIN_G, machine.Pin.IN, machine.Pin.PULL_UP)
self.sw_b = machine.Pin(PIN_B, machine.Pin.IN, machine.Pin.PULL_UP)
self.sw_y.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_y)
self.sw_g.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_g)
self.sw_b.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_b)
self.sw_mode = machine.Pin(PIN_MODE, machine.Pin.IN, machine.Pin.PULL_UP)
self.sw_color = machine.Pin(PIN_COLOR, machine.Pin.IN, machine.Pin.PULL_UP)
self.sw_mode.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_mode)
self.sw_color.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_color)
def set_fn(self, fn):
if fn == "mode":
@ -87,25 +79,22 @@ class Light:
def start(self):
global state
old_mode = self.mode
old_mode = None
old_color = self.color
old_brightness = self.brightness
i = 0
j = 0
while True:
if state:
time.sleep(DELAY_IRQ)
machine.enable_irq(state)
state = None
if not self.mode == old_mode:
print("mode: {}, old_mode: {}".format(MODES[self.mode], MODES[old_mode]))
if MODES[self.mode] == "off":
if not self.mode == old_mode:
old_mode = self.mode
self.set_color(-1)
time.sleep(DELAY)
# Off
elif MODES[self.mode] == "on":
print("mode: {} ({}), old_mode: {}".format(self.mode, MODES[self.mode], old_mode))
# # Off
# if MODES[self.mode] == "off":
# if not self.mode == old_mode:
# old_mode = self.mode
# self.set_color(-1)
# time.sleep(DELAY)
# On
if MODES[self.mode] == "on":
if not self.mode == old_mode:
old_mode = self.mode
self.set_color(self.color)
@ -113,7 +102,7 @@ class Light:
old_color = self.color
self.set_color(self.color)
time.sleep(DELAY)
# On
# Color Chase
elif MODES[self.mode] == "color_chase":
if not self.mode == old_mode:
old_mode = self.mode