def __init__(self, event_end_start): self._event_end_start = event_end_start self._strip1 = np.PixelStrip(lsc.list[0]["count"], lsc.list[0]["pin"], lsc.conf["freq"], lsc.conf["dma"], lsc.list[0]["invert"], lsc.list[0]["brighness"], lsc.list[0]["channel"]) self._strip2 = np.PixelStrip(lsc.list[1]["count"], lsc.list[1]["pin"], lsc.conf["freq"], lsc.conf["dma"], lsc.list[1]["invert"], lsc.list[1]["brighness"], lsc.list[1]["channel"]) self._strip1.begin() self._strip2.begin()
def __init__(self, num, pin, dma=10, brightness=255, channel=0): super().__init__(pin) self.ws281x = rpi_ws281x.PixelStrip(num, pin, dma=dma, brightness=brightness, channel=channel) self.bck_dma = dma self.bck_brightness = brightness self.bck_channel = channel self.thread_lock = threading.Lock()
def __init__(self): self.shape = (45, 20) # H x W num = self.shape[0] * self.shape[1] pin = 18 freq = 800000 # maybe higher dma = 5 invert = False brightness = 100 channel = 0 led_type = None # ?? self.strip = ws.PixelStrip(num, pin, freq, dma, invert, brightness, channel, led_type) self.strip.begin()
def __init__(self, count, pin, frequency, dma_channel, invert, brightness, channel): if util.is_raspi(): self.strip = rpi_ws281x.PixelStrip(count, pin, frequency, dma_channel, invert, brightness, channel) self.strip.begin() else: self.strip = None self.led_panel_simulator = led_panel_simulator.LedPanelSimulator( count, pin, frequency, dma_channel, invert, brightness, channel)
def __init__(self, config): self.strip = rpi_ws281x.PixelStrip( config['COUNT'], config['PIN'], config['FREQ_HZ'], config['DMA'], config['INVERT'], config['BRIGHTNESS'], config['CHANNEL'] ) self.strip.begin() # This lock will hopefully help prevent white flashing self.strip_lock = threading.Lock() # This is the color that pixels will gravitate towards self.base_red = 0 # range 0 - 255 self.base_blue = 0 # range 0 - 255 self.base_green = 0 # range 0 - 255 # Pixels can mutate to any color with +- the tolerance from the base # A tolerance of 0 means all pixels will be the base_color # A tolerance of 255 means pixels color will randomly span the entire color space self.tolerance = 0 # range 0 - 255 # This is the % chance that a color value of a pixel has to mutate self.mutation_rate = 0 # range 0 - 100 # A mutated color will change by this value, either + or - # increasing this will increase the speed that the colors change self.mutation_step = 2 # range 0 - 255 # This offset is applied to the hue color wheel and will create a phase change from the valence mapping to the RGB mapping. # This website has a good demonstration of HSV color: http://aleto.ch/color-mixer/ # A offset value of 0.66 would be equivelent of a Hue value of 240 on the above site. # Our mapping of the range 0 - 1 to the RGB color space is then represented by the circumpfrence of the HSV color wheel. # Note that this only allows mixing of two of the three colors, one will always be zero. # Thankfully our mutations will take care of this and we can rely on them to produce more colors. self.hue_offset = 0.66 # range 0 - 1 # These HSV values allow a direct mapping from the 0 - 1 range to the RGB space # See: https://en.wikipedia.org/wiki/HSL_and_HSV # maximum values for S and V create more vivid and intense colors, and are a good choice with these cheep LEDs self.hsv_S = 1 self.hsv_V = 1 # This will allow us to detect when all the lights are off, and we don't have to bother doing all the music effects self.idle = False
def __initstate__(self): try: import rpi_ws281x logger.debug('Initializing RaspberryPI LED device') self._strip = rpi_ws281x.PixelStrip(num=self.num_pixels, pin=self.pin, freq_hz=self.freq_hz, dma=self.dma, invert=self.invert, brightness=self.brightness) self._strip.begin() except ImportError: url = 'learn.adafruit.com/neopixels-on-raspberry-pi/software' logger.error('Could not import the neopixel library') logger.error('For installation instructions, see {}'.format(url)) logger.error('If running on RaspberryPi, please install.') logger.error('------------------------------------------') logger.error('Otherwise rely on dependency injection') logger.error('Disconnecting Device.')
def __init__(self, err_xmit_url: str, led_cfg_dict: dict) -> None: """ Instantiates object :param err_xmit_url: str :param led_cfg_dict: dict """ self.err_xmit_url = err_xmit_url info = inspect.getframeinfo(frame=inspect.stack()[1][0]) err_msg_base = 'FILE: ' + info.filename + ' ' + \ 'FUNCTION: ' + info.function # Create LED object for pixels attached to given pin try: self.led = rpi_ws281x.PixelStrip( num=led_cfg_dict['count'], pin=led_cfg_dict['pin'], freq_hz=led_cfg_dict['freq_hz'], dma=led_cfg_dict['dma'], invert=led_cfg_dict['invert'], brightness=led_cfg_dict['brightness'], channel=led_cfg_dict['channel'], strip_type=rpi_ws281x.SK6812_STRIP_GRBW) self.led.begin() log = 'LEDs initialized.' logger.info(msg=log) print(log) self.off() except Exception as exc: log = 'Failed to initialize LEDs.' logger.error(msg=log) logger.error(msg=exc) print(log) print(exc) err_msg = err_msg_base + ' ' + \ 'MESSAGE: ' + log + '\n' errors.errors(err_xmit_url=self.err_xmit_url, err_msg=err_msg)
def __init__(self, width=20, height=32, pin=18, freq_hz=800000, dma=5, invert=False, brightness=50): # 1D LED strip self._strip = rpi_ws281x.PixelStrip(width * height, pin, freq_hz, dma, invert, brightness) self._strip.begin() self._width = width self._height = height # Color data for each pixel, in list-of-lists format self._array = [[Color(0, 0, 0) for i in range(height)] for j in range(width)] #Index as _array[row][col] # List to use for indexing into led strip (vectorization) self._indices = [i for i in range(width * height)]
def command_brightness(): new_brightness = 0 while not 0 < new_brightness < 256: new_brightness = input("Please enter a brightness between 1 & 255(q to abort): ") if new_brightness == "q": menu() return None try: new_brightness = int(new_brightness) except ValueError: print("This is not a number.") new_brightness = 0 global LED_BRIGHTNESS global grid LED_BRIGHTNESS = new_brightness grid = rpi_ws281x.PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) grid.begin() for cell in cells: cell.display_state() grid.show() menu()
def __init__( self, width=16, # Number of pixels in width height=16, # Number of pixels in height led_pin=18, # PWM pin freq=800000, # 800khz dma_channel=10, invert=False, # Invert Shifter, should not be needed brightness=0.1, # 1: 100%, 0: 0% everything in between. led_channel=0, # set to '1' for GPIOs 13, 19, 41, 45 or 53 led_type=None, # Read the documentation to get your strip type. fps=10 # frames per second. ): if width < 1 or height < 1: raise Exception('Invalid Dimensions') if brightness < 0 or brightness > 1: raise Exception('Brightness can only be between 0 and 1') else: brightness = int(brightness * 255) # Make this more relevant. self.width = width self.height = height self.fps = fps self.wh_ratio = float(width) / height self.pixels = width * height # Init the strip here. self.strip = ws.PixelStrip(self.pixels, led_pin, freq, dma_channel, invert, brightness, led_channel, led_type) self.strip.begin() # Maintaining the state of the strip. self.power = True self.buffer = Queue() self.reset() # Init the loop so that we can start displaying the buffer. self.loop()
WEATHER_ANIMATIONS["Drizzle"] = lambda strip, runtime, reverse: display_image( strip=strip, image_filename="drizzle.jpeg", runtime=runtime, reverse=reverse) WEATHER_ANIMATIONS["Clouds"] = lambda strip, runtime, reverse: display_image( strip=strip, image_filename="clouds.jpeg", runtime=runtime, reverse=reverse) NUM_LEDS = 150 LED_PIN = 18 RUNTIME = 20 * 60 STRIP = ws.PixelStrip(NUM_LEDS, LED_PIN) app = Flask(__name__) app.config.from_object(CONFIG) def get_weather(location: str = "Oxford,GB") -> str: """ Get the weather from OpenWeatherMap :param location: an owm location string to get weather data for :return: the simple weather status """ try: owm = OWM(CONFIG.WEATHER_API_KEY)
def begin(self) -> bool: """Setup the LED array""" self._log.info( "Setting up '%s' on GPIO%02d with %d %s LEDS %s", self._name, self._pin, self._count, self._chip, f"with {self._per_pixel} LEDs per pixel" if self._per_pixel > 1 else "", ) try: import rpi_ws281x except ModuleNotFoundError: self._log.error( "MQTTany's LED module requires 'rpi-ws281x' to be installed, " "please see the wiki for instructions on how to install requirements" ) return False if self._pin != 10: if not os.access("/dev/mem", os.R_OK | os.W_OK, effective_ids=True): self._log.error( "No read/write access to '/dev/mem', try running with root privileges" ) return False if gpio.board.lock(self._pin, gpio.common.Mode.SOC): try: self._array = rpi_ws281x.PixelStrip( num=self._count * self._per_pixel, pin=self._pin, freq_hz=self._frequency * 1000, dma=DMA_CHANNEL[self._pin], invert=self._invert, brightness=self._init_brightness, channel=PWM_CHANNEL[self._pin], strip_type=LED_COLOR_ORDERS[self._order] + LED_TYPES[self._chip], ) self._array.begin() except: self._log.error("An error occured while setting up '%s'", self._name) logger.log_traceback(self._log) return False else: super().begin() common.publish_queue.put_nowait( PublishMessage(path=f"{self.id}/gpio", content=self._pin, mqtt_retained=True)) common.publish_queue.put_nowait( PublishMessage(path=f"{self.id}/chip", content=self._chip, mqtt_retained=True)) common.publish_queue.put_nowait( PublishMessage( path=f"{self.id}/frequency", content=self._frequency, mqtt_retained=True, )) common.publish_queue.put_nowait( PublishMessage( path=f"{self.id}/invert", content=self._invert, mqtt_retained=True, )) del self._init_brightness del self._chip del self._frequency del self._invert self._setup = True return self._setup
LED_DMA = 10 # DMA channel to use for generating signal (try 10) LED_BRIGHTNESS = 1 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 # Other Constants BUTTON_LEFT_GPIO_PIN = 23 BUTTON_MIDDLE_GPIO_PIN = 24 BUTTON_RIGHT_GPIO_PIN = 25 HABIT_DATA_FILE = "habit-data.json" # LED array representing the colors of the display. leds = [Color.BLANK] * LED_COUNT # Initialize the Strip of LEDS. strip = rpi_ws281x.PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) strip.begin() # Currently selected day. selectedDay = datetime.datetime.now() # Habit tracker data in JSON format. habitData = None lastInputTime = datetime.datetime.now() # Clears LEDs colors. def clearLeds(): global leds leds = [Color.BLANK] * LED_COUNT
def Pixels(num_pixels=12): strip = rpi_ws281x.PixelStrip(num_pixels, PIN, channel=1) strip.begin() strip.clear = functools.partial(clear_pixels, strip) return strip
""" Read api keys from a filename for usage in this program. The file should have keys in the format 'name=api key', each on a new line. Don't add that file to git! :param filename: the filename of the file containing api keys :return: a dictionary keyed by api name, with api keys as values. """ key_dict = {} with open(filename) as fi: for line in fi: key, val = [item.strip() for item in line.split("=")] key_dict[key] = val return key_dict if __name__ == "__main__": os.chdir(os.path.dirname(os.path.realpath(__file__))) WEATHER_API_KEY = read_api_keys("./.apikey")["openweathermap"] NUM_LEDS = 150 LED_PIN = 18 RUNTIME = 20 * 60 strip = ws.PixelStrip(NUM_LEDS, LED_PIN) try: main(strip) except KeyboardInterrupt: for pixel in range(strip.numPixels()): strip.setPixelColor(pixel, ws.Color(0, 0, 0)) strip.show() raise KeyboardInterrupt