Candle effect
Sat Oct 08 2022 22:58:27 GMT+0000 (UTC)
Saved by @aguest #python #micropython
# LED Candle animation for microypthon on esp8266 import time import uos import math import machine import neopixel # number of leds in the strip LED_COUNT = 20 # base color r = 99 g = 31 b = 6 np = neopixel.NeoPixel(machine.Pin(4), LED_COUNT) def show(): np.write() def Color(r, g, b): return (int(r), int(g), int(b)) def setPixelColor(i, color): np[i] = color def wait(ms): time.sleep(ms/1000.0) def randint(min, max): return min + int(int.from_bytes(uos.urandom(2), 10) / 65536.0 * (max - min + 1)) def c_brightness(c, brightness): return max(0, min(c * brightness / 100, 255)) class LED_light(object): def __init__(self, pos): self.time = 0 self.pos = pos def update(self, delta): self.time = self.time - delta if self.time <= 0: self.random_mode() self.random_duration() def set_brightness(self, brightness): setPixelColor(self.pos, Color(c_brightness(r, brightness), c_brightness(g, brightness), c_brightness(b, brightness))) def random_mode(self): # Probability Random LED Brightness # 50% 77% – 80% (its barely noticeable) # 30% 80% – 100% (very noticeable, sim. air flicker) # 5% 50% – 80% (very noticeable, blown out flame) # 5% 40% – 50% (very noticeable, blown out flame) # 10% 30% – 40% (very noticeable, blown out flame) brightness = 0 r = randint(0, 100) if r < 50: brightness = randint(77, 80) elif r < 80: brightness = randint(80, 100) elif r < 85: brightness = randint(50, 80) elif r < 90: brightness = randint(40, 50) else: brightness = randint(30, 40) self.set_brightness(brightness) def random_duration(self): # Probability Random Time # 90% 20 ms # 3% 20 – 30 ms # 3% 10 – 20 ms # 4% 0 – 10 ms r = randint(0, 100) if r < 90: self.time = 20 elif r < 93: self.time = randint(20, 30) elif r < 96: self.time = randint(10, 20) else: self.time = randint(0, 10) def main(): candles = [LED_light(i) for i in range(LED_COUNT)] while True: now = time.ticks_ms() [l.update(now) for l in candles] show() wait(2) main()
Comments