class _Display: def __init__(self): self._np = NeoPixel(Pin(5, Pin.OUT), 9) def __setitem__(self, subscript, value): self._np[_get_index(subscript)] = value def __getitem__(self, subscript): return self._np[_get_index(subscript)] def anim_pixel(self, subscript, r, g, b, steps=20): index = _get_index(subscript) np = self._np start = np[index] end = r, g, b for i in range(0, steps): j = steps - i np[index] = [ int((s * j + e * i) / steps) for s, e in zip(start, end) ] yield 1 / 60 np[index] = end def write_now(self): self._np.write()
def init(): global __led if __led != None or PIN_LED <= 0: return __led = NeoPixel(Pin(PIN_LED, Pin.OUT), 1) __led.fill((0, 0, 0)) __led.write()
class NeoPixelAdaptor(BaseDisplayAdaptor): def __init__(self): """ Ascii Adaptor class takes the display object and convert it into an ascii display. """ super().__init__() def setup(self, display_data): """Overides the base class """ strip_size = display_data.height * display_data.width self._grid = NeoPixel(Pin(23), strip_size) def show(self, delta, display_data): """ Show function will show the ascii display using the given display object. Is used every loop in Controller. :param display: Instance that will be converted :type display: Display :param delta: The amount of time that has passed since the start of the loop in the controller :type delta: Number """ pixels = display_data.pixels for y_index in range(display_data.height): for x_index in range(display_data.width): led_index = convert_to_index(x_index, y_index, display_data.height) self._grid[led_index] = pixels[x_index][y_index] self._grid.write()
def test_led(): px = NeoPixel(Pin(D5), 4) px[0] = (255, 0, 0) px[1] = (0, 255, 0) px[2] = (0, 0, 255) px[3] = (255, 255, 255) px.write()
class Flashing_lights: 'Controls two neopixels that flash continuously' def __init__(self, neopixel_pin): self.n = NeoPixel(Pin(neopixel_pin, Pin.OUT), 2) self.n[0] = (0, 0, 0) self.n[1] = (0, 0, 0) self.n.write() self.brightness_max = 1 self.brightness_min = .03 self.color = (100, 0, 0) self.progress = 0 self.epoch = time.ticks_ms() self.breath = 27 def set_color(self, color, brightness_min=0.03): self.color = color self.epoch = localtime() self.brightness_min = brightness_min def loop(self): k = ((math.cos((time.ticks_ms() - self.epoch) / 450) + 1) / 2.8) * ( self.brightness_max - self.brightness_min) + self.brightness_min self.n[1] = self.n[0] = dim(self.color, k) self.n.write()
class NeoPixelWriter: def __init__(self, num_pixels=10, bytes_per_pixel=4, pinno=15): pin = Pin(pinno, Pin.OUT) self.np = NeoPixel(pin, num_pixels, bpp=bytes_per_pixel) self.bytes_per_pixel = bytes_per_pixel self.tuple_len = bytes_per_pixel+1 def on_next(self, x): """The event should be a tuple/list where the first element is the pixel number and the rest are the settings for that pixel OR it can be a standard (sensor_id, ts, event) tuple, where the control message is in the third element. """ if len(x)==3 and (isinstance(x[2], tuple) or isinstance(x[2], list)) and \ len(x[2])==self.tuple_len: x = x[2] # the control message is embedded in a standard triple elif len(x)!=self.tuple_len: raise Exception("expecting a tuple of length %d" % self.tuple_len) pixel = x[0] self.np[pixel] = x[1:] self.np.write() def on_error(self, e): pass def on_completed(self): pass
class ColorWheel: NEO_PIXEL_PIN = 26 # on my board the neopixel is connected to GPIO 26 NO_OF_LEDS = 7 def __init__(self): self.red = 0 self.green = 0 self.blue = 0 if sys.platform == "esp32": from machine import Pin from neopixel import NeoPixel # init data pin to control LEDs self.brightness=0.1 #brightness: 0-1.0 pin = Pin(self.NEO_PIXEL_PIN, Pin.OUT) self.np = NeoPixel(pin, self.NO_OF_LEDS) def colors(self,pos): if pos<60: self.red=255 self.green=int(255*pos/60) self.blue=0 elif pos >=60 and pos < 120: self.red=255-int(255*(pos-60)/60) self.green = 255 self.blue = 0 elif pos >=120 and pos < 180: self.red = 0 self.blue = int(255*(pos-120)/60) self.green = 255 elif pos >= 180 and pos < 240: self.red = 0 self.green = 255-int(255*(pos-180)/60) self.blue = 255 elif pos >= 240 and pos < 300: self.red = int(255*(pos-240)/60) self.green = 0 self.blue = 255 else: self.red = 255 self.green = 0 self.blue = 255 - int(255*(pos-300)/60) print("red: {:03d}, green: {:03d}, blue: {:03d}".format(self.red, self.green, self.blue)) return (self.red,self.green,self.blue) def show(self): if sys.platform == "esp32": for i in range(0,self.NO_OF_LEDS): self.np[i] = (int(self.red*self.brightness), int(self.green*self.brightness), int(self.blue*self.brightness)) self.np.write() sleep_ms(200)
def on(self): blue_modulo = 3 for i in range(self.n): NeoPixel.__setitem__(self, i, (255, 0, 0)) if i % blue_modulo == 0: NeoPixel.__setitem__(self, i, (61, 0, 255)) NeoPixel.write(self) self._on = True
def neo_write(t_color, sleep, nb=NB_LEDS): # write a table of colors to neopixel import machine from neopixel import NeoPixel leds = NeoPixel(machine.Pin(2), nb) for i, color in enumerate(t_color): leds[i] = color sleep(100) leds.write()
def set_random(): pin = Pin(4, Pin.OUT) # set GPIO0 to output to drive NeoPixels np = NeoPixel(pin, 30) # create NeoPixel driver on GPIO0 for 8 pixels for x in range(30): r = random.randint(0, 100) g = random.randint(0, 100) b = random.randint(0, 100) np[x] = (r, g, b) np.write() # write data to all pixels
class NeoPixelPlayer: def __init__(self, pin, nlength): self.nlength = nlength self.np = NeoPixel(Pin(pin), nlength) #input length self.ilength = nlength def out(self, output): self.np.buf = output self.np.write()
def led_game(): np = NeoPixel(pin, LED) for column, row in game.get_block_coord(): number_of_led = row + 2 + (11 - column) * 25 np[number_of_led] = led_color(game.block_color, 15) for (led_column, led_row), color in game.waste_dict.items(): if led_row >= 0 and led_row < 12 and led_column >= 0 and led_column < 12: number_of_led = led_row + 2 + (11 - led_column) * 25 np[number_of_led] = led_color(color, 20) np.write()
class LedStrip: def __init__(self, pin, number): self._pin = pin self._colors = [] self._number = number self._strip = NeoPixel(pin, number) self.clear() def clear(self): self.all((0, 0, 0)) def add(self, color): self.flash(3, colors['GREEN']) self._colors.append(color) self.clear() i = 0 leds_per_color = math.ceil(self._number / len(self._colors)) for color in self._colors: for num in range(0, leds_per_color): if (i < self._number): self.set_color(i, color) i = i + 1 self.update() def all(self, color): for i in range(self._number): self.set_color(i, color) self.update() def blink(self, n, color): on = False for i in range(n * 2): on = not (on) if on: self.all(color) else: self.clear() utime.sleep(0.25) def flash(self, n, color): for i in range(0, n): self.clear() for led in range(0, self._number): self.set_color(led, color, 0.5) def set_color(self, i, rgb, brightness=0.1): self._strip[i] = tuple([int(brightness * clr) for clr in rgb]) self.update() def update(self): self._strip.write()
class RGB: def __init__(self,port , num): p = getPin(port) if p[0] == None : return self.rgb = NeoPixel(Pin(p[0]) , num , timing = True) self.tar = list(self.rgb) def setColor(self , list , color): for i in range(0,len(list)): self.rgb[list[i]-1] = color self.rgb.write()
def blink(self, color=[255, 255, 255], times=3, interval=0.5): try: self.off() for i in range(times): NeoPixel.fill(self, color) NeoPixel.write(self) time.sleep(interval) NeoPixel.fill(self, [0, 0, 0]) NeoPixel.write(self) time.sleep(interval) finally: self.off()
def field(snake_color=(0, 10, 0)): np = NeoPixel(pin, NUMBER_LED) for x, y in snake: led_number = x + ROW + y*COLUMN np[led_number] = snake_color for x, y in food: led_number = x + ROW + y*COLUMN np[led_number] = (0, 10, 10) if snake[-1] == food[-1]: led_number = x + ROW + y*COLUMN np[led_number] = (10, 0, 0) np.write()
class NeoDevice: def __init__(self, pin, width, height, snake=True): self.pin_number = pin self.width = width self.height = height self.snake = snake self._pin = Pin(self.pin_number, Pin.OUT) self._device = NeoPixel(self._pin, self.total_pixels) @property def total_pixels(self): return self.width * self.height def translate(self, pixel_position): """ Pixel top left to bottom right to snake position from bottom right to left :param pixel_position: :return: """ # Work out the X/Y from the top left x = pixel_position % self.width y = pixel_position // self.width # X is our column column_offset = (self.width - 1 - x) * self.height if x % 2 == 0: # Even column, runs downwards return column_offset + y else: return column_offset + (self.height - 1) - y def translate_xy(self, x, y): return self.translate(y * self.width + x) def write_pixel(self, pixel_number, colour): location = self.translate(pixel_number) print("Location: {}".format(location)) print("Pixel number: {}".format(pixel_number)) print("Colour: {}".format(colour)) print("Device item: {}".format( self._device[self.translate(pixel_number)])) self._device[self.translate(pixel_number)] = colour def write_absolute_pixel(self, pixel_number, colour): self._device[pixel_number] = colour def write_xy_pixel(self, x, y, colour): self._device[self.translate_xy(x, y)] = colour def refresh(self): self._device.write()
def choice_game(): np = NeoPixel(pin, NUMBER_LED) if pin_up.value() == 0: for i in range(NUMBER_LED): np[i] = (0, 10, 30) np.write() if pin_up.value() != 0: import tetris_led.py elif pin_down.value() == 0: for i in range(NUMBER_LED): np[i] = (40, 10, 10) np.write() if pin_down.value() != 0: import snake_led.py
def fade(): pin = Pin( 0, Pin.OUT) # set GPIO0 or D3 in NodeMCU to output to drive NeoPixels np = NeoPixel(pin, 144) # create NeoPixel driver on GPIO0 for 300 pixels l = [4, 8, 10, 12, 14, 16, 20, 30, 40, 60, 80, 100, 140, 180, 220, 255] for j in l: for i in range(144): np[i] = (j, j, 0) np.write() l.reverse() for j in l: for i in range(144): np[i] = (j, j, 0) np.write()
def main(): light = machine.ADC(0) # Reading either light sensor/moisture sensor/soil quality sensor # bus = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=100000) # bmp = BMP280(bus) indicator = NeoPixel(machine.Pin(4, machine.Pin.OUT), 1) # Set up 1 WS2812 as a neopixel indicator[0] = (255, 0, 0) # set the first pixel to white indicator.write() # Setting up HTTP server connectWifi() addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('listening on ', addr) indicator[0] = (0, 255, 0) # set the first pixel to white indicator.write() while True: conn, address = s.accept() time.sleep_ms(100) conn.recv(1024) header = 'HTTP/1.1 200 OK\r\n' header += 'Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept\r\n' header += 'Access-Control-Allow-Origin: *\r\n' header += 'Cache-Control: no-cache\r\n' header += 'Connection: keep-alive\r\n' header += 'Content-Type: text/event-stream\r\n\r\n' final_response = header.encode('utf-8') conn.send(final_response) print(final_response) while True: final_response = "data: " + sensorRead(light) + "\n\n" # No moisture or soil detection try: conn.send(final_response) except OSError as e: conn.close() break print(final_response) time.sleep(1)
class Indicator: def __init__(self): self.animation = '' self.color = (0, 0, 0) # color that user set self.fcolor = [0, 0, 0] # color that the handler use self.rgb = NeoPixel(Pin(5), 1, timing=True) def animate(self, type='None', color=(0, 100, 100), speed=10): self.rgb[0] = color self.rgb.write() sleep_ms(1) self.rgb[0] = (0, 0, 0) self.rgb.write() # Timer has been penalty because of its unstable behaviour # DEPRECATED """
def show(self, delta, display_data): """ Show function will show the ascii display using the given display object. Is used every loop in Controller. :param display: Instance that will be converted :type display: Display :param delta: The amount of time that has passed since the start of the loop in the controller :type delta: Number """ grid = NeoPixel(Pin(23), display_data.width * display_data.height) pixels = display_data.pixels for y in pixels: for x in y: index = x_y_to_series_conversion(display_data.width, y.index(x), \ pixels.index(y)) grid[index] = x grid.write()
class View(): def __init__(self, pin, number_of_pixels): self.number_of_pixels = number_of_pixels self.np = NeoPixel(pin, self.number_of_pixels) def render(self, color_buffer): for i in range(len(color_buffer)): self.np[i] = color_buffer[i].as_instruction() self.np.write() def render_color(self, color): for i in range(self.number_of_pixels): self.np[i] = color.as_instruction() self.np.write() def off(self): self.render_color(Color(0, 0, 0))
def demo(self, program="cycle"): self.off() try: n = self.n if program == "cycle": for i in range(4 * n): for j in range(n): NeoPixel.__setitem__(self, j, [0, 0, 0]) NeoPixel.__setitem__(self, i % n, [255, 255, 255]) NeoPixel.write(self) time.sleep_ms(25) elif program == "bounce": for i in range(4 * n): for j in range(n): NeoPixel.__setitem__(self, j, [0, 0, 128]) if (i // n) % 2 == 0: NeoPixel.__setitem__(self, i % n, [0, 0, 0]) else: NeoPixel.__setitem__(self, n - 1 - (i % n), [0, 0, 0]) NeoPixel.write(self) time.sleep_ms(60) elif program == "fade": for i in range(0, 4 * 256, 8): for j in range(n): if (i // 256) % 2 == 0: val = i & 0xff else: val = 255 - (i & 0xff) NeoPixel.__setitem__(self, j, [val, 0, 128]) NeoPixel.write(self) finally: self.off()
class Feedback(): "simple feedback via 3 neopixel leds" # fb = Feedback() # fb.update(0,fb.GREEN) L_MQTT = 0 L_NET = 1 L_P1 = 2 BLACK = (0, 0, 0) WHITE = (20, 20, 20) RED = (64, 0, 0) GREEN = (2, 16, 2) # dim green BLUE = (0, 0, 64) YELLOW = (64, 64, 0) PURPLE = (64, 0, 64) np = None def __init__(self): _pin_np = Pin(cfg.NEOPIXEL_PIN, Pin.OUT) # set to output to drive NeoPixels self.np = NeoPixel(_pin_np, 3) # create NeoPixel driver for 3 pixels self.np.write() def update(self, n: int = 2, color: tuple = (64, 64, 64)): if self.np: self.np[n] = color #pylint: disable= unsupported-assignment-operation self.np.write() def clear(self, color: tuple = (0, 0, 0)): for n in range(3): self.np[n] = color #pylint: disable= unsupported-assignment-operation self.np.write()
class uPyHAL: def __init__(self, config): self.num_pixels = 64 self.np = NeoPixel(Pin(13), self.num_pixels) self.enable_auto_time = False # https://github.com/micropython/micropython/issues/2130 #utime.timezone(config['tzOffsetSeconds']) def init_display(self, num_pixels=64): self.clear_display() def clear_display(self): for i in range(self.num_pixels): self.np[i] = (0, 0, 0) self.np.write() def update_display(self, num_modified_pixels): if not num_modified_pixels: return self.np.write() def put_pixel(self, addr, r, g, b): self.np[addr % self.num_pixels] = (r, g, b) def reset(self): self.clear_display() def process_input(self): #TODO: implement return 0 def set_rtc(self, t): settime() def set_auto_time(self, enable=True): self.enable_auto_time = enable def suspend_host(self, restart_timeout_seconds): if restart_timeout_seconds < 15: return
class Neo: """Wrapper for the NeoPixel class, creating a nicer interface for users working with NeoPixels""" def __init__(self,pin_nr): """The constructor accepts a pin number to a pin that is connected to a NeoPixel""" self.neo = NeoPixel(Pin(13),1) self._siren_timer=Timer(0) self._siren_state=True def set_color(self,r,g,b): """Set the NeoPixels color to the given RGB value""" self.neo[0] = (r,g,b) self.neo.write() def purple(self): self.set_color(128,0,128) def red(self): self.set_color(255,0,0) def green(self): self.set_color(0,255,0) def blue(self): self.set_color(0,0,255) def siren(self, sleep_time=450): def tick(input): self._siren_state=not self._siren_state if self._siren_state: self.blue() else: self.red() if sleep_time > 0: self._siren_timer.init(period=sleep_time, mode=Timer.PERIODIC, callback=tick) else: self._siren_timer.init() def pulse(self,delay=100): """Makes the NeoPixel pulse in different colors""" for index in range(0,2): i = 0 while i<255: curr = list(self.neo[0]) curr[index] = i self.neo[0] = curr time.sleep_ms(delay) self.neo.write() i+=1 while i>255: curr = list(self.neo[0]) curr[index] = i self.neo[0] = curr time.sleep_ms(delay) self.neo.write() i-=1
class PixelWriter1D(object): NULL_FUNCTION = "0" def __init__(self, pinNumber, ledCount): self.np = NeoPixel(Pin(pinNumber), ledCount) self.ledCount = ledCount self.rFunc = self.NULL_FUNCTION self.gFunc = self.NULL_FUNCTION self.bFunc = self.NULL_FUNCTION def setRedFunction(self, redFunctionString): self.rFunc = redFunctionString def setGreenFunction(self, greenFunctionString): self.gFunc = greenFunctionString def setBlueFunction(self, blueFunctionString): self.bFunc = blueFunctionString def writeAllPixels(self, t): for x in range(self.ledCount): self.np[x] = (eval(self.rFunc), eval(self.gFunc), eval(self.bFunc)) self.np.write()
def testNeoPixels(): n = 10 np = NeoPixel(Pin(Neo), n) # cycle for i in range(4 * n): for j in range(n): np[j] = (0, 0, 0) np[i % n] = (255, 255, 255) np.write() #time.sleep_ms(25) # bounce for i in range(4 * n): for j in range(n): np[j] = (0, 0, 128) if (i // n) % 2 == 0: np[i % n] = (0, 0, 0) else: np[n - 1 - (i % n)] = (0, 0, 0) np.write() #time.sleep_ms(60) # fade in/out for i in range(0, 4 * 256, 8): for j in range(n): if (i // 256) % 2 == 0: val = i & 0xff else: val = 255 - (i & 0xff) np[j] = (val, 0, 0) np.write() # clear for i in range(n): np[i] = (0, 0, 0) np.write()
class Rgb(NeoPixel): def __init__(self, pin, num=1): self.pin = pin self.num = num self.np = NeoPixel(Pin(self.pin, Pin.OUT), self.num) # self.np = super().__init__(Pin(self.pin, Pin.OUT), self.num) def simpleTest(self, wait_ms=500): self.np[0] = RED self.np.write() sleep_ms(wait_ms) self.np[0] = GREEN self.np.write() sleep_ms(wait_ms) self.np[0] = BLUE self.np.write() sleep_ms(wait_ms) self.np[0] = (0, 0, 0) self.np.write() def color(self, color=RED, i=0): self.np[i] = color self.np.write() def color_chase(self, np, num_pixels, color, wait): for i in range(self.num): self.np[i] = color self.np.write() sleep(wait) def rainbow_cycle(self, wait=3, intensity=2): for j in range(255): for i in range(self.num): rc_index = (i * 256 // self.num) + j self.np[i] = wheel(rc_index & 255, dev=intensity) self.np.write() sleep_ms(wait) def test(self): #https://github.com/maxking/micropython/blob/master/rainbow.py self.simpleTest() self.color_chase( self.np, self.num, RED, 0.1) # Increase the number to slow down the color chase self.color_chase(self.np, self.num, YELLOW, 0.1) self.color_chase(self.np, self.num, GREEN, 0.1) self.color_chase(self.np, self.num, CYAN, 0.1) self.color_chase(self.np, self.num, BLUE, 0.1) self.color_chase(self.np, self.num, PURPLE, 0.1) self.rainbow_cycle() # Increase the number to slow down the rainbow sleep(1) self.np.fill(BLACK) self.np.write()
class DHT11(DHTBase): def humidity(self): return self.buf[0] def temperature(self): return self.buf[2] class DHT22(DHTBase): def humidity(self): return(self.buf[0]<<8|self.buf[1])*0.1 def temperature(self): t=((self.buf[2]&0x7f)<<8|self.buf[3])*0.1 if self.buf[2]&0x80: t=-t return t buzz=Buzz() oled=OLED() display=oled accelerometer=Accelerometer() rgb=NeoPixel(Pin(17,Pin.OUT),3,3,1) rgb.write() light=ADC(Pin(39)) sound=ADC(Pin(36)) ext=ADC(Pin(34)) button_a=Pin(0,Pin.IN,Pin.PULL_UP) button_b=Pin(2,Pin.IN,Pin.PULL_UP) touchPad_P=TouchPad(Pin(27)) touchPad_Y=TouchPad(Pin(14)) touchPad_T=TouchPad(Pin(12)) touchPad_H=TouchPad(Pin(13)) touchPad_O=TouchPad(Pin(15)) touchPad_N=TouchPad(Pin(4))