class neo16x16_img: def __init__(self,pin): self.np=NeoPixel(pin,256) def clear(self): self.np.clear() def show(self,dat,pos=0): for x in range(16): for y in range(8): if ((x+pos)*8)>=len(dat): self.np[x*16+y*2]=(0,0,0) self.np[x*16+y*2+1]=(0,0,0) else: t=dat[(x+pos)*8+y] r=t%16 g=(t>>4)%16 b=(t>>8)%16 if pos%2: self.np[x*16+y*2]=(r,g,b) else: self.np[x*16+15-y*2]=(r,g,b) r=(t>>12)%16 g=(t>>16)%16 b=(t>>20)%16 if pos%2: self.np[x*16+y*2+1]=(r,g,b) else: self.np[x*16+14-y*2]=(r,g,b) self.np.show()
class neo16x16: def __init__(self, pin): self.np = NeoPixel(pin, 256) self.color = (0,0,8) def clear(self): self.np.clear() def set(self, n, dat): self.np[n] = dat self.np.show() def setcolor(self, color): self.color = color def show(self, dat, pos=0, clear = True, color=''): if color != '': self.color = color if clear: for i in range(256): self.np[i]=(0,0,0) for x in range(16): for y in range(16): if (x+pos)>=len(dat): self.np[x*16+y]=(0,0,0) else: if (1<<y)&dat[x+pos]: if pos%2==0: self.np[x*16 + y] = self.color else: self.np[x*16 +15 - y] = self.color self.np.show()
def ledrgb(n, r, g, b): n = min(max(n, 0), 3) r = min(max(r, 0), 255) g = min(max(g, 0), 255) b = min(max(b, 0), 255) np = NeoPixel(pin15, 4) np[floor(n)] = (floor(r), floor(g), floor(b)) np.show()
class MoveMini: def __init__(self): self.np = NeoPixel(pin0, 5) self.pos = 0 self.motor_right = pin1 self.motor_left = pin2 self.stop() def forward(self): display.show(Image.ARROW_N) self.np[1] = self.np[3] = (0, LIGHT_LEVEL, LIGHT_LEVEL) self.np[2] = (LIGHT_LEVEL, LIGHT_LEVEL, LIGHT_LEVEL) self.np[0] = self.np[4] = (0, 0, 0) self.np.show() self.motor_right.set_analog_period(20) self.motor_left.set_analog_period(20) self.motor_right.write_analog(50) self.motor_left.write_analog(100) def backward(self): display.show(Image.ARROW_S) self.np[1] = self.np[2] = self.np[3] = (LIGHT_LEVEL, 0, 0) self.np[0] = self.np[4] = (0, 0, 0) self.np.show() self.motor_right.set_analog_period(20) self.motor_left.set_analog_period(20) self.motor_right.write_analog(100) self.motor_left.write_analog(50) def left(self): display.show(Image.ARROW_W) self.np[1] = self.np[2] = (0, LIGHT_LEVEL, 0) self.np[0] = (LIGHT_LEVEL, LIGHT_LEVEL, 0) self.np[3] = self.np[4] = (0, 0, 0) self.np.show() self.motor_right.set_analog_period(20) self.motor_left.set_analog_period(20) self.motor_right.write_analog(100) self.motor_left.write_analog(100) def right(self): display.show(Image.ARROW_E) self.np[2] = self.np[3] = (0, LIGHT_LEVEL, 0) self.np[4] = (LIGHT_LEVEL, LIGHT_LEVEL, 0) self.np[0] = self.np[1] = (0, 0, 0) self.np.show() self.motor_right.set_analog_period(20) self.motor_left.set_analog_period(20) self.motor_right.write_analog(50) self.motor_left.write_analog(50) def stop(self): display.show(Image.HAPPY) for i in range(5): self.np[i] = (0, 0, 0) self.np.show() self.motor_right.read_digital() self.motor_left.read_digital()
def init_pixels(led_count: int) -> NeoPixel: ADDRESSABLE_LEDS = led_count # (30/m * 5m) / 3 [Addr is Groups of 3] print('Setting up neopixel + clearing lights') pixels = NeoPixel(board.D18, ADDRESSABLE_LEDS, brightness=1, auto_write=False, pixel_order="BRG") pixels.fill(COL_BLACK) pixels.show() return pixels
class Controller(): def __init__(self, ledsCount, color, brightness): self.pixels = NeoPixel(board.D18, ledsCount, auto_write=False, brightness=brightness) self.color = color self.brightness = brightness self.pixels.fill(self.color) self.show_pixels() def change_color(self, color): self.color = color self.pixels.fill(self.color) self.show_pixels() def change_brightness(self, brightness): self.brightness = abs(brightness / 100) self.pixels.brightness = self.brightness self.show_pixels() def set_pixels(self, leds, colors=[]): self.clear_pixels() if len(colors) <= 0: for led in leds: self.set_pixel(led, self.color) else: for i, led in enumerate(leds): self.set_pixel(led, colors[i]) self.pixels.show() def set_pixel(self, led, color): self.pixels[led] = color def show_pixels(self): self.pixels.show() def clear_pixels(self): self.pixels.fill((0, 0, 0)) def turn_off(self): self.clear_pixels() self.show_pixels() def turn_on(self): self.pixels.fill(self.color) self.show_pixels()
class Strip: PIN = board.D18 # port on the RPI LED_COUNT = 5 # number of LEDs BRIGHTNESS = 0.05 # the LEDs are insanely bright, 5% should be fine def __init__(self): self.strip = NP( self.PIN, self.LED_COUNT, brightness=self.BRIGHTNESS, auto_write=False, # don't automatically write to LEDs ) def animate(self, animation: Animation): """Set the color of the strip, given an animation.""" for i, color in enumerate(animation()): self.strip[i] = color.to_tuple() self.strip.show()
class _TrellisNeoPixel: """Neopixel driver """ # Lots of stuff come from Adafruit_CircuitPython_seesaw/neopixel.py def __init__(self, auto_write=True, brightness=1.0, part=_TRELLISM4_LEFT_PART, left_part=None): if part == _TRELLISM4_LEFT_PART: self.pix = NeoPixel(board.NEOPIXEL, 32, auto_write=False, brightness=brightness) elif part == _TRELLISM4_RIGHT_PART: self.pix = left_part.pix self.auto_write = auto_write self._offset = part def __setitem__(self, key, color): self.pix[_key(key) + self._offset] = color if self.auto_write: self.show() def __getitem__(self, key): return self.pix[_key(key) + self._offset] def fill(self, color): """Fill method wrapper """ # Suppress auto_write while filling. current_auto_write = self.auto_write self.auto_write = False for i in range(16): self[i] = color if current_auto_write: self.show() self.auto_write = current_auto_write def show(self): """Fill method wrapper """ self.pix.show()
class NeoHandler(Thread): def __init__(self, number_of_leds=300): self.stop = False self.leds = number_of_leds self.pixels = NeoPixel( board.D18, 300, auto_write=False ) # Hard coded 300 for timing issues TODO (should re-look at this) # Define Neo States self.neo_state_off = 0 self.neo_state_solid = 1 self.neo_state_flashing = 2 self.neo_state_alternate = 3 self.neo_state_pulse = 4 self.neo_state_chase = 5 self.neo_state_bounce = 6 self.neo_state_no = 7 # Initial Colour self.colour = (29, 60, 125) self.period_delay = 0.5 self.brightness = 0.5 # Current State self.neo_state = self.neo_state_off # Chaser Variables self.chaser_leds_on = 3 self.chaser_leds_off = 7 self.chaser_reverse = False Thread.__init__(self) # Function to fill only selected LEDS (needed because of hard coded led number) def fill(self, col): for i in range(self.leds): self.pixels[i] = col # Function to stop thread def stop_thread(self): self.stop = True # Update colour with any function (obsolete) def _update_colour(self, col): self.colour = col # For writing preset functions, i.e. red pulsing def set_function(self, state, col=-1, freq=-1): if col != -1: self.colour = col if freq != -1: self.period_delay = 1.0 / float(freq) / 2.0 self.neo_state = state # Update Frequency def update_frequency(self, freq): self.period_delay = 1.0 / float(freq) / 2.0 # Thread to exit gracefully def exit(self): self.fill((0, 0, 0)) self.pixels.show() print("Exiting Neo Thread") # Thread to update colour from Modbus def set_colour(self, colour_dict): col = list(self.colour) if 'red' in colour_dict: col[0] = colour_dict['red'] if 'green' in colour_dict: col[1] = colour_dict['green'] if 'blue' in colour_dict: col[2] = colour_dict['blue'] self.colour = tuple(col) # Main thread def run(self): period = False # Initialise Chaser Values reg_on = 0 reg_leds = 0 leds_on_off = self.chaser_leds_on + self.chaser_leds_off led_mask = pow(2, self.leds) - 1 for j in range(self.chaser_leds_on): reg_on |= 1 << j # Initial Pulse Values pulse_x = range(pulse_data_points) pulse_vals = [] for i in pulse_x: pulse_vals.append(pow(1.15, i)) pulse_vals = [i / max(pulse_vals) for i in pulse_vals] tmp = pulse_vals.copy() tmp.sort(reverse=True) pulse_vals = pulse_vals + tmp # Bounce variables bounce_led = 0 bounce_dir = False # main loop while not self.stop: # Update colour/delay time at start of each cycle colour = self.colour period_delay = self.period_delay # Reset brightness if state isn't pulsing if self.neo_state != self.neo_state_pulse: self.pixels.brightness = self.brightness # Leds off if self.neo_state == self.neo_state_off: self.fill((0, 0, 0)) self.pixels.show() # Leds on elif self.neo_state == self.neo_state_solid: self.fill(colour) self.pixels.show() # Flash On/Off elif self.neo_state == self.neo_state_flashing: if not period: self.fill(colour) self.pixels.show() else: self.fill((0, 0, 0)) self.pixels.show() time.sleep(period_delay) # Pulsing on/off elif self.neo_state == self.neo_state_pulse: self.fill(colour) for i in pulse_vals: self.pixels.brightness = i self.pixels.show() # Bounce 1 led swings from end to end elif self.neo_state == self.neo_state_bounce: if not bounce_dir: self.fill((0, 0, 0)) self.pixels[bounce_led] = colour if bounce_led >= self.leds - 1: bounce_dir = True else: bounce_led += 1 else: self.fill((0, 0, 0)) self.pixels[bounce_led] = colour if bounce_led <= 0: bounce_dir = False else: bounce_led -= 1 self.pixels.show() # Adjustable chaser (every few leds on or off and shifts along the strip) elif self.neo_state == self.neo_state_chase: # cycle through each section of LEDs in strip for i in range(leds_on_off): for j in range( int( math.ceil( float(self.leds) / float(leds_on_off)))): reg_leds |= (reg_on << (j * leds_on_off)) & led_mask # Reverse binary string if Leds to chase backwards if self.chaser_reverse: reg_leds = int( format(reg_leds, "0{}b".format(self.leds))[::-1], 2) # Shift left and mask with No of LEDs reg_on = reg_on << 1 reg_on &= led_mask # Wrap around if i >= leds_on_off - self.chaser_leds_on: reg_on |= 1 # Write to the LEDs for i in range(self.leds): if (1 << i) & reg_leds: self.pixels[i] = colour else: self.pixels[i] = (0, 0, 0) self.pixels.show() time.sleep(period_delay) # Reset test reg reg_leds = 0 # Every second led alternates from on to off elif self.neo_state == self.neo_state_alternate: if not period: for i in range(self.leds): if i % 2: self.pixels[i] = colour else: self.pixels[i] = (0, 0, 0) self.pixels.show() else: for i in range(self.leds): if i % 2: self.pixels[i] = (0, 0, 0) else: self.pixels[i] = colour self.pixels.show() time.sleep(period_delay) # Invalid amount of states else: self.neo_state = self.neo_state_off period = not period self.exit()
class NeoPixel: def __init__( self, pin_num=None, n=30, start_led=0, test=False, overwrite_line=True, debug=False, target='micropython' # or 'adafruit' ): self.debug = debug self.target = target self.strip_length = n self.addressable_strip_length = n self.start_led = start_led self.test = test self.pin_num = pin_num if pin_num else 10 if self.target == 'micropython' else 18 if self.target == 'adafruit' else None self.overwrite_line = overwrite_line self.sections = self.get_sections() if self.test: self.leds = [[0, 0, 0] for x in range(self.strip_length)] else: from neopixel import NeoPixel as NeoPixelOriginal if self.target == 'micropython': self.leds = NeoPixelOriginal(self.get_pin(), self.strip_length) elif self.target == 'adafruit': self.leds = NeoPixelOriginal(self.get_pin(), self.strip_length, auto_write=False) def get_pin(self): if self.target == 'micropython': from machine import Pin return Pin(self.pin_num, Pin.OUT) elif self.target == 'adafruit': import board if self.pin_num == 18: return board.D18 elif self.pin_num == 23: return board.D23 elif self.pin_num == 24: return board.D24 elif self.pin_num == 24: return board.D24 elif self.pin_num == 25: return board.D25 elif self.pin_num == 12: return board.D12 elif self.pin_num == 16: return board.D16 elif self.pin_num == 4: return board.D4 elif self.pin_num == 17: return board.D17 elif self.pin_num == 27: return board.D27 elif self.pin_num == 22: return board.D22 elif self.pin_num == 5: return board.D5 elif self.pin_num == 6: return board.D6 elif self.pin_num == 13: return board.D13 elif self.pin_num == 26: return board.D26 def get_sections(self): if self.debug: print('NeoPixel().get_sections()') sections_length = 15 sections = [] counter = 0 while counter < self.addressable_strip_length: sections.append( [x for x in range(counter, counter + sections_length)]) counter += sections_length return sections def get_led_selectors(self, sections='all'): if self.debug: print('NeoPixel().get_led_selectors(sections={})'.format(sections)) if type(sections) == str: if sections == 'all': return range(self.addressable_strip_length) elif sections == 'random': return self.sections[randint(0, len(self.sections) - 1)] else: selected_leds = [] # if "sections" is a list of strings, first convert them to counter numbers (0,1,2,3) instead of "Section 1","Section 2" etc. if type(sections[0]) == str: sections = [ int(x.lower().replace(' ', '').split('section')[-1]) - 1 for x in sections ] for entry in sections: selected_leds += self.sections[entry] return selected_leds def write(self, s_after_wait=1.0 / 36.0): if self.debug: print('NeoPixel().write(s_after_wait={})'.format(s_after_wait)) if self.test: from colr import color print(''.join( color(' ', back=(x[0], x[1], x[2])) for x in self.leds), end='\r' if self.overwrite_line and not self.debug else '\n') else: if self.target == 'micropython': self.leds.write() elif self.target == 'adafruit': self.leds.show() time.sleep(s_after_wait) def insert_led(self, position=0, rgb=[0, 0, 0]): if self.debug: print('NeoPixel().insert_led(position={},rgb={})'.format( position, rgb)) # save state of all leds as list, insert LED at position, then write LEDs leds = [[x[0], x[1], x[2]] for x in self.leds] leds.insert(position, rgb) leds = leds[:-1] for i in range(len(leds)): self.leds[i] = leds[i] def append_led(self, rgb=[0, 0, 0]): if self.debug: print('NeoPixel().append_led(rgb={})'.format(rgb)) # save state of all leds as list, append LED at the end, then write LEDs leds = [[x[0], x[1], x[2]] for x in self.leds] leds.append(rgb) leds = leds[1:] for i in range(len(leds)): self.leds[i] = leds[i] def fadeout(self): # get current colors of leds and make them darker step by step brightness = 0.9 while brightness >= 0: for x in range(self.strip_length): r = round(self.leds[x][0] * brightness) g = round(self.leds[x][1] * brightness) b = round(self.leds[x][2] * brightness) self.leds[x] = [ r if r <= 255 and r >= 0 else 255 if r > 255 else 0, g if g <= 255 and g >= 0 else 255 if g > 255 else 0, b if b <= 255 and b >= 0 else 255 if b > 255 else 0, ] brightness -= 0.1 self.write(0.001) def get_led(self, i, start=None): if self.debug: print('NeoPixel().get_led(i={},start={}'.format(i, start)) i = i + self.start_led if i < 0: i += self.addressable_strip_length if start and start == 'end': i += (self.strip_length - self.addressable_strip_length) return i def off(self): if self.debug: print('NeoPixel().off()') for i in range(self.strip_length): self.leds[i] = (0, 0, 0) self.write() def on(self, num=None): if self.debug: print('NeoPixel().on(num={})'.format(num)) if type(num) == int: num = self.get_led(num) self.leds[num] = (255, 255, 255) else: for i in range(self.strip_length): self.leds[i] = (255, 255, 255) self.write() def test_animations(self): # run all the animations for testing print('Start testing animations...') while True: self.rainbow_animation(loop_limit=2) self.beats(loop_limit=3) self.beats(loop_limit=3, start='end') self.beats(loop_limit=3, start='start + end') self.beats(loop_limit=3, start='center', brightness=0.5) self.moving_dot(loop_limit=3) self.moving_dot(loop_limit=3, start='end', brightness=0.5) self.light_up(loop_limit=3) self.light_up(loop_limit=3, sections='random') self.light_up(loop_limit=3, sections=[0]) self.transition(loop_limit=3) self.transition(loop_limit=3, sections=[0]) def color(self, rgb_colors=[randint(0, 255), randint(0, 255), randint(0, 255)], customization_json={}): try: print('color:') original_r = customization_json['rgb_colors'][0][ 0] if customization_json and 'rgb_colors' in customization_json else rgb_colors[ 0][0] original_g = customization_json['rgb_colors'][0][ 1] if customization_json and 'rgb_colors' in customization_json else rgb_colors[ 0][1] original_b = customization_json['rgb_colors'][0][ 2] if customization_json and 'rgb_colors' in customization_json else rgb_colors[ 0][2] brightness = 0.1 while brightness <= 1: for i in range(self.strip_length): r = round(original_r * brightness) g = round(original_g * brightness) b = round(original_b * brightness) i = self.get_led(i) self.leds[i] = [ r if r <= 255 and r >= 0 else 255 if r > 255 else 0, g if g <= 255 and g >= 0 else 255 if g > 255 else 0, b if b <= 255 and b >= 0 else 255 if b > 255 else 0, ] self.write() brightness += 0.1 while True: # await keyboard interrupt time.sleep(10) except KeyboardInterrupt: self.fadeout() import sys print() sys.exit(0) def rainbow_animation(self, loop_limit=None, brightness=1, duration_ms=1000, pause_ms=None, customization_json={}): RainbowAnimation( led_strip=self, loop_limit=customization_json['loop_limit'] if customization_json and 'loop_limit' in customization_json else loop_limit, brightness=customization_json['brightness'] if customization_json and 'brightness' in customization_json else brightness, duration_ms=customization_json['duration_ms'] if customization_json and 'duration_ms' in customization_json else duration_ms, pause_ms=customization_json['pause_ms'] if customization_json and 'pause_ms' in customization_json else pause_ms).glow() def beats(self, rgb_colors=None, brightness=1, brightness_fixed=False, max_height=1, loop_limit=None, duration_ms=200, pause_ms=300, start='start', num_random_colors=5, customization_json={}): BeatsUpAndDown( led_strip=self, rgb_colors=customization_json['rgb_colors'] if customization_json and 'rgb_colors' in customization_json else rgb_colors, brightness=customization_json['brightness'] if customization_json and 'brightness' in customization_json else brightness, brightness_fixed=customization_json['brightness_fixed'] if customization_json and 'brightness_fixed' in customization_json else brightness_fixed, max_height=customization_json['max_height'] if customization_json and 'max_height' in customization_json else max_height, loop_limit=customization_json['loop_limit'] if customization_json and 'loop_limit' in customization_json else loop_limit, duration_ms=customization_json['duration_ms'] if customization_json and 'duration_ms' in customization_json else duration_ms, pause_ms=customization_json['pause_ms'] if customization_json and 'pause_ms' in customization_json else pause_ms, start=customization_json['start'] if customization_json and 'start' in customization_json else start, num_random_colors=customization_json['num_random_colors'] if customization_json and 'num_random_colors' in customization_json else num_random_colors).glow() def moving_dot(self, rgb_colors=None, brightness=1, loop_limit=None, duration_ms=200, pause_a_ms=0, pause_b_ms=300, start='start', num_random_colors=5, customization_json={}): MovingDot( led_strip=self, rgb_colors=customization_json['rgb_colors'] if customization_json and 'rgb_colors' in customization_json else rgb_colors, brightness=customization_json['brightness'] if customization_json and 'brightness' in customization_json else brightness, loop_limit=customization_json['loop_limit'] if customization_json and 'loop_limit' in customization_json else loop_limit, duration_ms=customization_json['duration_ms'] if customization_json and 'duration_ms' in customization_json else duration_ms, pause_a_ms=customization_json['pause_a_ms'] if customization_json and 'pause_a_ms' in customization_json else pause_a_ms, pause_b_ms=customization_json['pause_b_ms'] if customization_json and 'pause_b_ms' in customization_json else pause_b_ms, start=customization_json['start'] if customization_json and 'start' in customization_json else start, num_random_colors=customization_json['num_random_colors'] if customization_json and 'num_random_colors' in customization_json else num_random_colors).glow() def light_up(self, rgb_colors=None, brightness=1, loop_limit=None, duration_ms=200, pause_ms=200, num_random_colors=5, sections='all', customization_json={}): LightUp( led_strip=self, rgb_colors=customization_json['rgb_colors'] if customization_json and 'rgb_colors' in customization_json else rgb_colors, brightness=customization_json['brightness'] if customization_json and 'brightness' in customization_json else brightness, loop_limit=customization_json['loop_limit'] if customization_json and 'loop_limit' in customization_json else loop_limit, duration_ms=customization_json['duration_ms'] if customization_json and 'duration_ms' in customization_json else duration_ms, pause_ms=customization_json['pause_ms'] if customization_json and 'pause_ms' in customization_json else pause_ms, num_random_colors=customization_json['num_random_colors'] if customization_json and 'num_random_colors' in customization_json else num_random_colors, sections=customization_json['sections'] if customization_json and 'sections' in customization_json else sections).glow() def transition(self, rgb_colors=None, brightness=1, loop_limit=None, duration_ms=200, pause_ms=200, num_random_colors=5, sections='all', customization_json={}): Transition( led_strip=self, rgb_colors=customization_json['rgb_colors'] if customization_json and 'rgb_colors' in customization_json else rgb_colors, brightness=customization_json['brightness'] if customization_json and 'brightness' in customization_json else brightness, loop_limit=customization_json['loop_limit'] if customization_json and 'loop_limit' in customization_json else loop_limit, duration_ms=customization_json['duration_ms'] if customization_json and 'duration_ms' in customization_json else duration_ms, pause_ms=customization_json['pause_ms'] if customization_json and 'pause_ms' in customization_json else pause_ms, num_random_colors=customization_json['num_random_colors'] if customization_json and 'num_random_colors' in customization_json else num_random_colors, sections=customization_json['sections'] if customization_json and 'sections' in customization_json else sections).glow()
# 4 NeoPixels all connected to pin 15 neo_pixels = NeoPixel(pin15, 4) # define colors as list variables color_red = [255, 0, 0] # red color_grn = [0, 255, 0] # green color_blu = [0, 0, 255] # blue color_wht = [255, 255, 255] # white while True: # set all neopixels to red neo_pixels[0] = color_red neo_pixels[1] = color_red neo_pixels[2] = color_red neo_pixels[3] = color_red neo_pixels.show() sleep(1000) # set all neopixels to green neo_pixels[0] = color_grn neo_pixels[1] = color_grn neo_pixels[2] = color_grn neo_pixels[3] = color_grn neo_pixels.show() sleep(1000) # set all neopixels to blue neo_pixels[0] = color_blu neo_pixels[1] = color_blu neo_pixels[2] = color_blu neo_pixels[3] = color_blu neo_pixels.show() sleep(1000)
class LedMatrix(collections.abc.Sequence): """Abstraction over the NeoPixel class for working with a NeoPixel strip as a matrix.""" def __init__( self, gpio_pin_name=DEFAULT_GPIO_PIN_NAME, # type: str num_rows=DEFAULT_NUM_ROWS, # type: int num_cols=DEFAULT_NUM_COLS, # type: int brightness=1, # type: float auto_write=False, # type: bool pixel_order=GRB, # type: ColorOrder origin=MATRIX_ORIGIN.NORTHEAST, # type: MATRIX_ORIGIN orientation=MATRIX_ORIENTATION.ROW, # type: MATRIX_ORIENTATION default_color=RED, # type: Color ): # type: (...) -> None num_pixels = num_rows * num_cols gpio_pin = getattr(board, gpio_pin_name) self.width = num_cols self.height = num_rows self.origin = origin self.orientation = orientation self.default_color = default_color self.pixel_order = pixel_order # coerce pixel_order to plain tuple if pixel_order.white is None: pixel_order_raw = (pixel_order.red, pixel_order.green, pixel_order.blue) else: pixel_order_raw = ( # type: ignore pixel_order.red, pixel_order.green, pixel_order.blue, pixel_order.white, ) # initialize underlying NeoPixel self._neopixel = NeoPixel( gpio_pin, num_pixels, brightness=brightness, auto_write=auto_write, pixel_order=pixel_order_raw, ) # initialize each row in matrix self._matrix = deque([], maxlen=num_rows) # type: Deque[_LedMatrixRow] for row_index in range(num_rows): self._matrix.append(_LedMatrixRow(self, row_index, num_cols)) def render(self): # type: () -> None """Render current state of matrix to the neopixel (only useful when auto_write is False).""" # print to STDOUT if using a mock if isinstance(self._neopixel, mock_neopixel.MockNeoPixel): os.system('clear') # noqa: S605 S607 print(self) # otherwise call the "show" method on the underlying neopixel else: self._neopixel.show() def fill(self, value): # type: (Color) -> None """Fill the entire matrix with the given color value.""" for row in self._matrix: row.fill(value) def shift_left(self, values): # type: (List[Color]) -> None """Shift all current pixel values left one unit.""" for row_index in range(self.height): row = self._matrix[row_index] value = values[row_index] row.shift_left(value) def deinit(self): # type: () -> None """Turn off and unmount the neopixel.""" self._neopixel.deinit() def _neopixel_set( self, matrix_row_index, # type: int matrix_col_index, # type: int value, # type: Color ): # type: (...) -> None """Update the NeoPixel pixel at the index corresponding to this position in the matrix. TODO: make this less of a clusterfuck. """ # do nothing if row index is out of range if matrix_row_index < 0 or matrix_row_index >= self.height: return None # do nothing if col index is out of range if matrix_col_index < 0 or matrix_col_index >= self.width: return None # the "neopixel row index" is the index of the first pixel for the specified row neopixel_row_index = matrix_row_index * self.width if self.origin == MATRIX_ORIGIN.NORTHWEST: neopixel_col_index = matrix_col_index * self.height else: neopixel_col_index = ( (self.width - 1) - matrix_col_index) * self.height # whether this row / column orientation is swapped neopixel_col_alt = neopixel_col_index % 2 neopixel_row_alt = neopixel_row_index % 2 # strips are laid horizontal across the board if self.orientation == MATRIX_ORIENTATION.ROW: # the first pixel is in the top-left corner of the board if self.origin == MATRIX_ORIGIN.NORTHWEST: neopixel_index = neopixel_row_index + matrix_col_index # the first pixel is in the bottom-right corner of the board elif self.origin == MATRIX_ORIGIN.SOUTHEAST: # NOTE: this is probably wrong neopixel_index = (self.height - neopixel_row_index) + ( self.width - matrix_col_index) - 2 # noqa: E501 # the first pixel is in the top-right corner of the board else: neopixel_index = neopixel_row_index + (self.width - matrix_col_index) - 1 # strips are laid vertically across the board elif self.orientation == MATRIX_ORIENTATION.COLUMN: # the first pixel is in the top-left corner of the board if self.origin == MATRIX_ORIGIN.NORTHWEST: neopixel_index = neopixel_col_index + matrix_row_index # the first pixel is in the bottom-right corner of the board elif self.origin == MATRIX_ORIGIN.SOUTHEAST: # NOTE: this is probably wrong neopixel_index = neopixel_col_index + matrix_row_index # the first pixel is in the top-right corner of the board else: neopixel_index = neopixel_col_index + (self.height - matrix_row_index) - 1 # strips are laid horizontally across the board and alternate left-right orientations elif self.orientation == MATRIX_ORIENTATION.ALTERNATING_ROW: # the first pixel is in the top-left corner of the board if self.origin == MATRIX_ORIGIN.NORTHWEST: # this strip is oriented left-to-right if not neopixel_row_alt: neopixel_index = neopixel_row_index + matrix_col_index # this strip's orientation is switched right-to-left else: neopixel_index = (neopixel_row_index - (self.width - 1)) + matrix_col_index # the first pixel is in the bottom-right corner of the board elif self.origin == MATRIX_ORIGIN.SOUTHEAST: # this strip is oriented right-to-left if neopixel_row_alt: neopixel_index = neopixel_row_index + ( (self.width - 1) - matrix_col_index) # this strip's orientation is switched left-to-right else: neopixel_index = neopixel_row_index + matrix_col_index # the first pixel is in the top-right corner of the board else: # this strip is oriented right-to-left if not neopixel_row_alt: neopixel_index = neopixel_row_index + ( (self.width - 1) - matrix_col_index) # this strip's orientation is switched left-to-right else: neopixel_index = neopixel_row_index + matrix_col_index # strips are laid vertically across the board and alternate down-up orientations else: # the first pixel is in the top-left corner of the board if self.origin == MATRIX_ORIGIN.NORTHWEST: # this strip is oriented top-to-bottom if not neopixel_col_alt: neopixel_index = neopixel_col_index + matrix_row_index # this strip's orientation is switched bottom-to-top else: neopixel_index = neopixel_col_index + ( (self.height - 1) - matrix_row_index) # the first pixel is in the bottom-right corner of the board elif self.origin == MATRIX_ORIGIN.SOUTHEAST: # this strip is oriented top-to-bottom if neopixel_col_alt: neopixel_index = neopixel_col_index + matrix_row_index # this strip's orientation is switched bottom-to-top else: neopixel_index = neopixel_col_index + ( (self.height - 1) - matrix_row_index) # the first pixel is in the top-right corner of the board else: # this strip is oriented top-to-bottom if not neopixel_col_alt: neopixel_index = neopixel_col_index + matrix_row_index # this strip's orientation is switched bottom-to-top else: neopixel_index = neopixel_col_index + ( (self.height - 1) - matrix_row_index) # set value on pixel if value.white is None: self._neopixel[neopixel_index] = (value.red, value.green, value.blue) else: self._neopixel[neopixel_index] = (value.red, value.green, value.blue, value.white) # print if using a mock neopixel and auto_write is True if isinstance(self._neopixel, mock_neopixel.MockNeoPixel): if self._neopixel.auto_write: os.system('clear') # noqa: S605 S607 print(self) def __repr__(self): # type: () -> str buf = '' for row in self._matrix: for color in row: if not isinstance(color, Color): if len(color) == 4: color = Color(*color) else: color = Color(color[0], color[1], color[2], None) buf += color.__repr__() buf += '\n' return buf def __len__(self): # type: () -> int return len(self._neopixel) def __getitem__(self, index): # type: (Union[int, slice]) -> Color return self._matrix[index] # type: ignore def __setitem__(self, index, color): # type: (int, Color) -> None return self._matrix[index] # type: ignore
from neopixel import NeoPixel from time import sleep from music import play, stop, BA_DING from KitronikMOVEMotor import * #MOVEMotor.setup() buggy = MOVEMotor() buggyLights = NeoPixel(pin8, 4) #Slightly Blue tint on the Headlights buggyLights[0] = [200, 200, 255] buggyLights[1] = [200, 200, 255] #Red tail lights buggyLights[2] = [255, 0, 0] buggyLights[3] = [255, 0, 0] buggyLights.show() while True: #drive around in a semi random manner play(BA_DING, pin0, True, False) buggy.LeftMotor(255) buggy.RightMotor(255) sleep(1000) buggy.StopMotors() sleep(100) buggy.LeftMotor(-255) buggy.RightMotor(255) sleep(250) buggy.StopMotors() sleep(100) buggy.LeftMotor(255)
# Initialize API interface loader = APILoader(4) loader.start() print("[*] Starting...") while True: for led in leds: leds[led].draw((0, 0, 0)) data = loader.getData() for door in data: if door in leds: leds[door].draw((0, 255, 0) if data[door] else (255, 0, 0)) strip.show() # Wait for a button press try: sensor.sleep(2) except ButtonPress as press: selection = str(press) if selection == "aerie": leds["cellar"].draw((255, 0, 0)) elif selection == "cellar": leds["aerie"].draw((255, 0, 0)) else: continue leds[selection].draw((0, 0, 0))
action %= numactions state = 0 display.show(str(action)) else: if state == 0: np.clear() lights = 0 state = 1 time = running_time() elif state == 1: display.show(Image.SURPRISED) lights = min(5,int((running_time() - time)/1000)) for i in range(lights): np[i] = (255,0,0) np.show() if int( (running_time() - time)/1000 ) >= 6: np.clear() state = 2 elif state == 2: display.show(Image.TORTOISE) doAction(action) state = 3 time = running_time() elif state == 3: display.show(Image.CONFUSED) lights = min(5,int((running_time() - time)/1000)) for i in range(lights): np[4 - i] = (0,0,255) np.show() if int( (running_time() - time)/1000 ) >= 6:
class Glock(object): def __init__(self): self.code = utils.get_code() print("CURRENT KP CODE:", self.code) self.result_count = 0 self.last = -1 self.names = [ "Joel", "Obed", "Malcolm", "Omar", "Matt", "Chris", "Chinny" ] #thread variables self.kp_thread = None self.camera_thread = None self.stream_thread = None self.main_thread = None self.idle_thread = None #thread event signals self.kp_stop_signal = None self.camera_stop_signal = None self.stream_stop_signal = None self.main_stop_signal = None self.idle_stop_signal = None self.idle_blue_signal = Event() #system variables self.camera = None self.system_active_idle = False self.ran_validation = False self.keypad = None self.killed = False self.stream_process = None self.stream = None self.result_count = None self.init_done = False self.bytes = None self.key = None self.fps = None self.kp_active = False self.result_count = None self.frame_counter = 0 self.verification_frame_count = 0 # NeoPixel Setup self.pixel_pin = board.D21 self.num_pixels = 60 self.ORDER = GRB self.pixels = NeoPixel(self.pixel_pin, self.num_pixels, brightness=0.2, auto_write=False, pixel_order=self.ORDER) #setup GPIO pins self.GPIO_TRIGGER = 13 self.GPIO_ECHO = 19 self.GPIO_STRIKE = 20 self.LED_PIN = 25 #set GPIO direction (IN / OUT) #GPIO SETUP GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT) GPIO.setup(self.GPIO_ECHO, GPIO.IN) GPIO.setup(self.GPIO_STRIKE, GPIO.OUT) GPIO.setup(self.LED_PIN, GPIO.OUT) # LED pin def detect_face_frame(self, image): final = [] cascPath = "haarcascade_frontalface_default.xml" # Create the haar cascade faceCascade = opencv.CascadeClassifier(cascPath) gray = opencv.cvtColor(image, opencv.COLOR_BGR2GRAY) print("frame processing...") # cv2.destroyAllWindows() # Detect faces in the image faces = faceCascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) #If no faces were found tweak parameters if len(faces) == 0: faces = faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5) if len(faces) == 0: faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) # Draw a rectangle around the faces for (x, y, w, h) in faces[::-1]: print("Found a face!") #Resize image to 120 pixels cropped = gray[y - 20:y + h + 20, x:x + w] final = np.array(opencv.resize(cropped, (100, 100))) opencv.imshow("Display WIndow", final) opencv.waitKey(0) opencv.destroyAllWindows() return final def find_face(self, img): global model_sigmoid global model_softmax global sig_input_details global soft_input_details global sig_output_details global soft_output_details face = self.detect_face_frame(img) #If no face found if face == []: return 0, -1 #Sigmoid output sig_input_data = np.reshape(np.array(face, dtype=np.float32), sig_input_details[0]['shape']) model_sigmoid.set_tensor(sig_input_details[0]['index'], sig_input_data) model_sigmoid.invoke() sig_output = model_sigmoid.get_tensor(sig_output_details[0]['index']) #Softmax Output soft_input_data = np.divide( np.reshape(np.array(face, dtype=np.float32), soft_input_details[0]['shape']), 255.0) model_softmax.set_tensor(soft_input_details[0]['index'], soft_input_data) model_softmax.invoke() soft_output = model_softmax.get_tensor(soft_output_details[0]['index']) sig = np.argmax(sig_output) soft = np.argmax(soft_output) print("Sig Raw Value: ", sig_output) print("Soft Raw Value: ", soft_output) print("Person: ", self.names[sig]) #If 2 differnt people if sig != soft: return -1, -1 #If not above threshold #elif else: return 1, sig def distance(self): #set Trigger to HIGH GPIO.output(self.GPIO_TRIGGER, True) # set Trigger after 0.01ms to LOW sleep(0.00001) GPIO.output(self.GPIO_TRIGGER, False) StartTime = time() StopTime = time() # save StartTime while GPIO.input(self.GPIO_ECHO) == 0: StartTime = time() # save time of arrival while GPIO.input(self.GPIO_ECHO) == 1: StopTime = time() # time difference between start and arrival TimeElapsed = StopTime - StartTime # multiply with the sonic speed (34300 cm/s) # and divide by 2, because there and back distance = (TimeElapsed * 34300) / 2 return distance def led_unlock_success(self): #stop idle led to allow for GREEN light if self.idle_stop_signal != None: self.idle_stop_signal.set() self.idle_thread.join() #start with green flash and then pulse self.pixels.fill((0, 225, 0)) for i in range(60): self.pixels[i] = (0, 125, 0) self.pixels.show() sleep(.01) for i in range(60): self.pixels[60 - i - 1] = (0, 50, 0) self.pixels.show() sleep(.01) def led_unlock_fail(self): #stop idle led to allow for RED light if self.idle_stop_signal != None: self.idle_stop_signal.set() self.idle_thread.join() #pluse in red for eek in range(3): for i in range(20): self.pixels.fill((225 - i, 0, 0)) self.pixels.show() sleep(.0005) sleep(.5) def restart_idle(self): #Function to restart IDLE LED Thread sleep(1) self.idle_stop_signal = Event() self.idle_blue_signal.clear() self.idle_thread = Thread(target=self.idle) self.idle_thread.start() def idle(self): print("starting IDLE LED thread") #Process to pulse either white or blue #will plulse in blue if signal is sent by keypad handler while not self.idle_stop_signal.wait(0): if self.idle_blue_signal.isSet(): for i in range(60): self.pixels[i] = (0, 0, 125) self.pixels.show() sleep(.01) for i in range(60): self.pixels[60 - i - 1] = (0, 0, 50) self.pixels.show() sleep(.01) else: for i in range(60): self.pixels[i] = (125, 125, 125) self.pixels.show() sleep(.01) for i in range(60): self.pixels[60 - i - 1] = (50, 50, 50) self.pixels.show() sleep(.01) def Validated(self): #add mutex on gpio ops? #activate strike for 10 sec GPIO.output(self.GPIO_STRIKE, GPIO.HIGH) print("GLOCK STRIKE ACTIVATED") sendText(True) self.led_unlock_success() #unlock strike and wait sleep(16) GPIO.output(self.GPIO_STRIKE, GPIO.LOW) self.ran_validation = True #send signal to restaart idle thread def Invalidated(self): #add mutex on gpips? print("GLOCK INVALID") sendText(False) self.led_unlock_fail() self.ran_validation = True def setup_stream(self): global output #loop to send cameera feed to streaming output class while not self.stream_stop_signal.wait(0): with PiCamera(resolution='1024x768', framerate=24) as self.camera: output = StreamingOutput() self.camera.start_recording(output, format='mjpeg', splitter_port=1, quality=0) sleep(_ONE_DAY_IN_SECONDS) self.camera.stop_recording() def CameraHandler(self): #Load models global model_sigmoid global model_softmax global sig_input_details global soft_input_details global sig_output_details global soft_output_details model_sigmoid = tf.lite.Interpreter(model_path="sigmoid.tflite") model_sigmoid.allocate_tensors() sig_input_details = model_sigmoid.get_input_details() sig_output_details = model_sigmoid.get_output_details() model_softmax = tf.lite.Interpreter(model_path="softmax.tflite") model_softmax.allocate_tensors() soft_input_details = model_softmax.get_input_details() soft_output_details = model_softmax.get_output_details() self.init_done = True print("Enter CameraHandler...") log_handler.emit("Enter CameraHandler...") self.result_count = 0 while not self.camera_stop_signal.wait(0): #if no one infrom of door or keypad currently in use then skip processing frame if self.system_active_idle == False or self.kp_active: # print("loop until motion") continue #grab every third frame from the camera to verfiy face if (self.verification_frame_count % 3 == 0): #capture image in array and send to ML suite rawCapture = PiRGBArray(self.camera, size=(1024, 768)) sleep(0.1) self.camera.capture(rawCapture, format="bgr", use_video_port=True, splitter_port=2) image = rawCapture.array result, person = self.find_face(image) rawCapture.truncate(0) if result == 0: #no face found in image print("NO FACE FOUND") log_handler.emit("NO FACE FOUND") continue elif (result == 1 and self.last == -1) or (result == 1 and self.last == person): #corect face found self.result_count += 1 last = person print("RESIDENT FACE FOUND") log_handler.emit("RESIDENT FACE FOUND") else: #face found but incorrect self.result_count -= 1 print("INCORRECT FACE FOUND") log_handler.emit("INCORRECT FACE FOUND") #need to see the same face twice in order to verify resident if (self.result_count == 2): self.Validated() self.result_count = 0 #reset "correct score" self.last = -1 #same logic..if two wrong faces then signal invalid elif (self.result_count == -2): self.Invalidated() self.result_count = 0 self.last = -1 else: continue self.verification_frame_count += 1 # count +=1 # #call verification on captured image def KeypadHandler(self): print("Enter KeypadHandler") log_handler.emit("Enter KeypadHandler") code_as_list = list(self.code) print("code as list: ", code_as_list) log_handler.emit("code as list: ", code_as_list) #create empty buffer for entered code entered_code = list() new_code_list = list() code_active = False # flag for signaling when input seq ready reset_active = False self.kp_active = False looking_new_code = False while not self.kp_stop_signal.wait(0): keys = self.keypad.pressed_keys #grab key pressed if len(keys) != 1: #eliminate multi press for keypad continue if keys == ["#"] and looking_new_code: #clear newcode being entered while in "enter code state" new_code_list = list() elif keys == ['*']: #input is reset and now look for code entered_code = list() new_code_list = list() code_active = True reset_active = False self.kp_active = True looking_new_code = False self.idle_blue_signal.clear() #reset master key code (usual '#' case) elif keys == ['#']: self.idle_blue_signal.set() entered_code = list() new_code_list = list() code_active = False reset_active = True self.kp_active = True looking_new_code = False elif reset_active: #regualar number is pressed while setting new key code ] #or to verifty old code for kp code change new_code_list += keys if looking_new_code: #if case will short to here if alrady entered old code to change to new if len(code_as_list) == len(new_code_list): #get new code print("new_code", new_code_list) log_handler.emit("new_code", new_code_list) as_string = [str(elem) for elem in new_code_list] as_string = ''.join(as_string) #update code variavles self.code = as_string utils.change_code(as_string) code_as_list = new_code_list #flash blue new_code_list = list() entered_code = list() looking_new_code = False reset_active = False self.idle_blue_signal.clear() self.kp_active = False elif len(code_as_list) == len( new_code_list): #submit old code for verification verification_res = (new_code_list == [ int(i) for i in code_as_list ]) #verify list print("old_code", new_code_list, "verified:", str(verification_res)) log_handler.emit("old_code", new_code_list, "verified:", str(verification_res)) if verification_res: #flash blue # time.sleep(1) # time.sleep(1) looking_new_code = True self.led_unlock_success() else: #flash red reset_active = False self.kp_active = False self.Invalidated() new_code_list = list() entered_code = list() elif code_active: entered_code += keys #add key to code if len(code_as_list) == len( entered_code): #submit code for verification code_active = False self.kp_active = False print("code", entered_code) log_handler.emit("code", entered_code) verification_res = (entered_code == [ int(i) for i in code_as_list ]) #verify list if verification_res == True: print("Validated") log_handler.emit("Validated") self.Validated() else: print("Invalidated") log_handler.emit("Invalidated") self.Invalidated() else: continue print("code", entered_code) print("reset_code", new_code_list) sleep(0.3) def MainHandler(self): print("Enter Main MainHandler...") # distances = [1000,1000,1000] #track last three disances #create queue of seen distances distances = [0, 0, 0] d_count = 0 d_max = 0 while not self.init_done: continue while not self.main_stop_signal.wait(0): sleep(0.5) distance = self.distance() distances[d_count % 3] = distance d_count += 1 print("Measured Distance = %.1f cm" % distance) # print(self.system_active_idle) # print(self.ran_validation) if (max(distances) < 90 and self.system_active_idle == False): #start process for camera and LED print("idlewake") self.system_active_idle = True self.restart_idle() self.kp_stop_signal = Event() self.kp_thread = Thread(target=self.KeypadHandler) self.kp_thread.start() elif (self.ran_validation == True): print("ran validation, restarting idle") log_handler.emit("ran validation, restarting idle") #clear pixels self.pixels.fill((0, 0, 0)) self.pixels.show() #restart the killed idle thread if person in front of sensor if max(distances) < 90: self.restart_idle() self.system_active_idle = True else: self.system_active_idle = False self.ran_validation = False elif (min(distances) > 90 and self.system_active_idle == True): #close ML and turn off LED print("no motion detected...close idle") log_handler.emit("no motion detected...close idle") self.system_active_idle = False self.idle_blue_signal.clear() self.idle_stop_signal.set() self.kp_stop_signal.set() self.idle_thread.join() self.kp_thread.join() print("kp joined") self.pixels.fill((0, 0, 0)) self.pixels.show() self.ran_validation = False try: self.camera_stop_signal.set() self.camera_thread.join() print("camera joined") self.idle_stop_signal.set( ) #stop self.idle_thread when main function exits self.idle_thread.join() except: return def run(self): #clear pixels self.pixels.fill((0, 0, 0)) self.pixels.show() self.stream_stop_signal = Event() self.stream_thread = Thread(target=self.setup_stream) self.stream_thread.start() self.keypad = keypad.keypad_setup() self.camera_stop_signal = Event() self.camera_thread = Thread(target=self.CameraHandler) self.camera_thread.start() self.main_stop_signal = Event() self.main_thread = Thread(target=self.MainHandler) self.main_thread.start() print("G_LOCK HAS BEEN STARTED") log_handler.emit("G_LOCK HAS BEEN STARTED") # def stream_serve(self): # p0 = subprocess.call(['sudo', 'pkill', 'uv4l']) #exit any hanging uv4l processes # command = "sudo uv4l -nopreview --auto-video_nr --driver raspicam --encoding mjpeg --width 640 --height 480 --framerate 20 --server-option '--port=2020' --server-option '--max-queued-connections=30' --server-option '--max-streams=25' --server-option '--max-threads=29'" # args = shlex.split(command) # p1 = subprocess.Popen(args) #start streaming server # print("BEGIN UV4L STREAMING") def kill(self): self.killed = True print("GLOCK KILL: Stopping threads") self.main_stop_signal.set() self.stream_stop_signal.set() self.stream_thread.join() self.main_thread.join() #clear pixels self.pixels.fill((0, 0, 0)) self.pixels.show()
class LedCube: def __init__(self, pixel_count=125, pixel_pin=D18): """ :param pixel_count: amount of pixels :param pixel_pin: The neopixel library makes use of the BCM pin numbering scheme. """ self.pixels = NeoPixel(pixel_pin, pixel_count, auto_write=False, pixel_order=GRB) \ if pixel_count > 0 else None def set_color(self, x, y, z, r, g, b): pxid = self.xyz2pxid(x, y, z) self.pixels[pxid] = (r, g, b) def show(self): self.pixels.show() def xyz2pxid(self, x, y, z) -> int: transform = { (0, 0, 0): 20, (1, 0, 0): 19, (2, 0, 0): 10, (3, 0, 0): 9, (4, 0, 0): 0, (0, 1, 0): 29, (1, 1, 0): 30, (2, 1, 0): 39, (3, 1, 0): 40, (4, 1, 0): 49, (0, 2, 0): 70, (1, 2, 0): 69, (2, 2, 0): 60, (3, 2, 0): 59, (4, 2, 0): 50, (0, 3, 0): 79, (1, 3, 0): 80, (2, 3, 0): 89, (3, 3, 0): 90, (4, 3, 0): 99, (0, 4, 0): 120, (1, 4, 0): 119, (2, 4, 0): 110, (3, 4, 0): 109, (4, 4, 0): 100, (0, 0, 1): 21, (1, 0, 1): 18, (2, 0, 1): 11, (3, 0, 1): 8, (4, 0, 1): 1, (0, 1, 1): 28, (1, 1, 1): 31, (2, 1, 1): 38, (3, 1, 1): 41, (4, 1, 1): 48, (0, 2, 1): 71, (1, 2, 1): 68, (2, 2, 1): 61, (3, 2, 1): 58, (4, 2, 1): 51, (0, 3, 1): 78, (1, 3, 1): 81, (2, 3, 1): 88, (3, 3, 1): 91, (4, 3, 1): 98, (0, 4, 1): 121, (1, 4, 1): 118, (2, 4, 1): 111, (3, 4, 1): 108, (4, 4, 1): 101, (0, 0, 2): 22, (1, 0, 2): 17, (2, 0, 2): 12, (3, 0, 2): 7, (4, 0, 2): 2, (0, 1, 2): 27, (1, 1, 2): 32, (2, 1, 2): 37, (3, 1, 2): 42, (4, 1, 2): 47, (0, 2, 2): 72, (1, 2, 2): 67, (2, 2, 2): 62, (3, 2, 2): 57, (4, 2, 2): 52, (0, 3, 2): 77, (1, 3, 2): 82, (2, 3, 2): 87, (3, 3, 2): 92, (4, 3, 2): 97, (0, 4, 2): 122, (1, 4, 2): 117, (2, 4, 2): 112, (3, 4, 2): 107, (4, 4, 2): 102, (0, 0, 3): 23, (1, 0, 3): 16, (2, 0, 3): 13, (3, 0, 3): 6, (4, 0, 3): 3, (0, 1, 3): 26, (1, 1, 3): 33, (2, 1, 3): 36, (3, 1, 3): 43, (4, 1, 3): 46, (0, 2, 3): 73, (1, 2, 3): 66, (2, 2, 3): 63, (3, 2, 3): 56, (4, 2, 3): 53, (0, 3, 3): 76, (1, 3, 3): 83, (2, 3, 3): 86, (3, 3, 3): 93, (4, 3, 3): 96, (0, 4, 3): 123, (1, 4, 3): 116, (2, 4, 3): 113, (3, 4, 3): 106, (4, 4, 3): 103, (0, 0, 4): 24, (1, 0, 4): 15, (2, 0, 4): 14, (3, 0, 4): 5, (4, 0, 4): 4, (0, 1, 4): 25, (1, 1, 4): 34, (2, 1, 4): 35, (3, 1, 4): 44, (4, 1, 4): 45, (0, 2, 4): 74, (1, 2, 4): 65, (2, 2, 4): 64, (3, 2, 4): 55, (4, 2, 4): 54, (0, 3, 4): 75, (1, 3, 4): 84, (2, 3, 4): 85, (3, 3, 4): 94, (4, 3, 4): 95, (0, 4, 4): 124, (1, 4, 4): 115, (2, 4, 4): 114, (3, 4, 4): 105, (4, 4, 4): 104 } return transform[x, y, z]
from microbit import * # import Micro:Bit module from neopixel import NeoPixel # import NeoPixel module # Note: the NeoPixels will only light up if your robot has batteries and is turned on # 4 NeoPixels all connected to pin 15 neo_pixels = NeoPixel(pin15, 4) # set NeoPixels to different colors using RGB color codes neo_pixels[0] = [255, 0, 0] # red neo_pixels[1] = [0, 255, 0] # green neo_pixels[2] = [0, 0, 255] # blue neo_pixels[3] = [255, 255, 255] # white neo_pixels.show() # write the color code values to the NeoPixels
action %= numactions state = 0 display.show(str(action)) else: if state == 0: np.clear() lights = 0 state = 1 time = running_time() elif state == 1: display.show(Image.SURPRISED) lights = min(5, int((running_time() - time) / 1000)) for i in range(lights): np[i] = (255, 0, 0) np.show() if int((running_time() - time) / 1000) >= 6: np.clear() state = 2 elif state == 2: display.show(Image.TORTOISE) doAction(action) state = 3 time = running_time() elif state == 3: display.show(Image.CONFUSED) lights = min(5, int((running_time() - time) / 1000)) for i in range(lights): np[4 - i] = (0, 0, 255) np.show() if int((running_time() - time) / 1000) >= 6:
neo = NeoPixel(28, n=8, brightness=0.3, autowrite=False) RED = (255, 0, 0) YELLOW = (255, 150, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) WHITE = (255, 255, 255) BLACK = (0, 0, 0) COLORS = (RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK) # fill for color in COLORS: neo.fill(color) neo.show() time.sleep(0.25) # chase for color in COLORS: for i in range(neo.n): neo[i] = color neo.show() time.sleep(0.025) # rainbow for i in range(255): neo.rainbow_cycle(i) neo.show() time.sleep(0.0025)
# r, g, b = map(scale, accelerometer.acceleration) switch.update() if switch.fell: # Check for button press try: uart_connection[UARTService].write( button_packet.to_bytes()) # Transmit press except OSError: pass uart_connection = None time.sleep(0.3) while True: uart_addresses = [] pixels[0] = BLUE # Blue LED indicates disconnected status pixels.show() # Keep trying to find target UART peripheral while not uart_addresses: uart_addresses = uart_client.scan(scanner) for address in uart_addresses: if TARGET in str(address): uart_client.connect(address, 5) # Connect to target while uart_client.connected: # Connected switch.update() if switch.fell: # Check for button press try: uart_client.write(button_packet.to_bytes()) # Transmit press except OSError: pass
""" up_down = 1 status = 1 build_red() display.show(str(status)) glitter_timer_counter = random.randint(1000, 2000) glitter_position = random.randint(0, 49) wave_timer_counter = 3 while True: if up_down == 2: glitter_timer_counter = glitter_timer_counter - 1 if glitter_timer_counter == 10: glitter_position = random.randint(0, 49) ring[glitter_position] = [0xff, 0xff, 0xff] ring.show() if glitter_timer_counter < 10: ring[glitter_position] = [0xff, 0xff, 0xff] ring.show() if glitter_timer_counter == 0: glitter_timer_counter = random.randint(1000, 2000) # for i in range(0, num_pixels): # ring[i] = data[i] # ring.show() wave_timer_counter = wave_timer_counter - 1 if wave_timer_counter == 0: wave_timer_counter = random.randint(1, 10) tmp = data.pop(-1) data.insert(0, tmp) for i in range(0, num_pixels): ring[i] = data[i]