Пример #1
0
def strand_test():
    """ Basically the same as the Adafruit stand test """

    test_strip = Adafruit_DotStar(ALL_LIGHTS, 12000000, order='bgr')
    test_strip.begin()
    test_strip.show()

    head = 0  # Index of first 'on' pixel
    tail = -10  # Index of last 'off' pixel
    color = 0xFF0000  # 'On' color (starts red)

    counter = ALL_LIGHTS * 3 + 10
    while counter > 0:  # Loop forever
        test_strip.setPixelColor(head, color)  # Turn on 'head' pixel
        test_strip.setPixelColor(tail, 0)  # Turn off 'tail'
        test_strip.show()  # Refresh strip
        time.sleep(1.0 / 100)  # Pause 20 milliseconds (~50 fps)
        head += 1  # Advance head position
        if head >= ALL_LIGHTS:  # Off end of strip?
            head = 0  # Reset to start
            color >>= 8  # Red->green->blue->black
            if color == 0:
                color = 0xFF0000  # If black, reset to red
        tail += 1  # Advance tail position
        if tail >= ALL_LIGHTS:
            tail = 0  # Off end? Reset
        counter -= 1
Пример #2
0
class LedStrip:
    forward = True
    numpixels = 80
    head = 0
    tail = -10

    def random_color(self):
        return random.choice(colors)

    def __init__(self, datapin, clockpin):
        self.datapin = datapin
        self.clockpin = clockpin
        self.strip = Adafruit_DotStar(self.numpixels,
                                      self.datapin,
                                      self.clockpin,
                                      order='bgr')
        self.strip.begin()
        self.strip.setBrightness(255)
        self.color = self.random_color()

    def display_pixel(self, pos, color):
        self.strip.setPixelColor(pos, color)

    def render(self):
        self.strip.show()
Пример #3
0
class LedStrip:
    forward = True
    numpixels = 80
    head = 0
    tail = -10

    def random_color(self):
        return random.choice(color_library)

    def __init__(self, datapin, clockpin, brightness):
        self.datapin = datapin
        self.clockpin = clockpin
        self.strip = Adafruit_DotStar(self.numpixels,
                                      self.datapin,
                                      self.clockpin,
                                      order='bgr')
        self.strip.begin()
        self.set_brightness(brightness)
        self.color = self.random_color()

    def set_pixel(self, pos, color):
        r, g, b = toRGB(color)
        self.strip.setPixelColor(pos, gamma[r], gamma[g], gamma[b])

    def set_brightness(self, brightness):
        self.brightness = clamp(brightness, 0, 255)
        self.strip.setBrightness(self.brightness)

    def render(self):
        self.strip.show()
Пример #4
0
def strandtest():
    #!/usr/bin/python

    # Simple strand test for Adafruit Dot Star RGB LED strip.
    # This is a basic diagnostic tool, NOT a graphics demo...helps confirm
    # correct wiring and tests each pixel's ability to display red, green
    # and blue and to forward data down the line.  By limiting the number
    # and color of LEDs, it's reasonably safe to power a couple meters off
    # USB.  DON'T try that with other code!

    import time
    from dotstar import Adafruit_DotStar

    numpixels = 72 # Number of LEDs in strip

    # Here's how to control the strip from any two GPIO pins:
    datapin  = 23
    clockpin = 24
    strip    = Adafruit_DotStar(numpixels, datapin, clockpin)

    # Alternate ways of declaring strip:
    #  Adafruit_DotStar(npix, dat, clk, 1000000) # Bitbang @ ~1 MHz
    #  Adafruit_DotStar(npix)                    # Use SPI (pins 10=MOSI, 11=SCLK)
    #  Adafruit_DotStar(npix, 32000000)          # SPI @ ~32 MHz
    #  Adafruit_DotStar()                        # SPI, No pixel buffer
    #  Adafruit_DotStar(32000000)                # 32 MHz SPI, no pixel buf
    # See image-pov.py for explanation of no-pixel-buffer use.
    # Append "order='gbr'" to declaration for proper colors w/older DotStar strips)

    strip.begin()           # Initialize pins for output
    strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle

    # Runs 10 LEDs at a time along strip, cycling through red, green and blue.
    # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

    head  = 0               # Index of first 'on' pixel
    tail  = -10             # Index of last 'off' pixel
    color = 0xFF0000        # 'On' color (starts red)

    stranditer = 4
    strandnum = 0
    while strandnum <= stranditer:                              # Loop forever

        strip.setPixelColor(head, color) # Turn on 'head' pixel
        strip.setPixelColor(tail, 0)     # Turn off 'tail'
        strip.show()                     # Refresh strip
        time.sleep(1.0 / 50)             # Pause 20 milliseconds (~50 fps)

        head += 1                        # Advance head position
        if(head >= numpixels):           # Off end of strip?
            head    = 0              # Reset to start
            color >>= 8              # Red->green->blue->black
            if(color == 0): color = 0xFF0000 # If black, reset to red

        tail += 1                        # Advance tail position
        if(tail >= numpixels): tail = 0  # Off end? Reset
        strandnum += 1
Пример #5
0
class PhysicalStrip:
    def __init__(self, numpixels):
        self._strip = Adafruit_DotStar(numpixels)
        self._strip.begin()

    def setPixelColor(self, i, color):
        self._strip.setPixelColor(i, color)

    def show(self):
        self._strip.show()
Пример #6
0
def main():
	
	# set up audio input...	
	recorder = alsaaudio.PCM(alsaaudio.PCM_CAPTURE)
	recorder.setchannels(CHANNELS)
	recorder.setrate(RATE)
	recorder.setformat(INFORMAT)
	recorder.setperiodsize(FRAMESIZE)
	
	# Set up off button	
	GPIO.setmode(GPIO.BCM)
	GPIO.setup(23,GPIO.IN,pull_up_down = GPIO.PUD_UP)
	
	# Initialize colors of each LED...
	strip = Adafruit_DotStar(numpixels)
	strip.begin()
	for i in range(15):
		time.sleep(float(1.0/float(i+1)))
		strip.setBrightness(int(stripBright*(i+1)/15))
		strip.setPixelColor(i,colors[i][0],colors[i][1],colors[i][2])
		strip.setPixelColor(29-i,colors[29-i][0],colors[29-i][1],colors[29-i][2])
		strip.show()
	time.sleep(1)

	# MAIN LOOP:
	i=0
	bigtime = 0.0
	valsold = []
	print "IN MAIN LOOP"
	try:
		while True:
			
			# Check for off button press
			on = GPIO.input(23)
			if on == False:
				shutdown(strip)
			
			# Read music and get magnitudes for FRAMESIZE length 
			Y = getMagnitudes(recorder)
			if Y != None:
				# Update LED strip based on magnitudes
				vals = controlLights(strip,Y,valsold)
				# Update valsold list which is used by my smoothAvg function
				# to make a running average of brightnesses rather than actual brightnesses
				valsold.insert(0,vals)
				if len(valsold) > 20:
					valsold.pop()
				if i % 1000 == 0:
					print "TIME:",time.time()-bigtime
					print "ITERATION: ",i
					bigtime = time.time()
				i+=1
	except KeyboardInterrupt:
		pass
Пример #7
0
def lightshow():
    numpixels = 72  # Number of LEDs in strip

    # Here's how to control the strip from any two GPIO pins:
    datapin = 23
    clockpin = 24
    strip = Adafruit_DotStar(numpixels, datapin, clockpin)

    strip.begin()  # Initialize pins for output
    strip.setBrightness(128)  # Limit brightness to ~1/4 duty cycle

    #First, turn all black
    offspot = 1
    offcolor = 0x000000
    while offspot >= 1:
        strip.setPixelColor(offspot, offcolor)
        offspot += 1
        if offspot == 72:
            break

    #set initial spots and colors of Jupiter and moons

    jupspot = 36  #jupiter position
    jupcolor = 0xFF8801  #jupiter color

    iospot = iopos  #Io position
    iocolor = 0x9932cc  #Io color

    eurspot = eurpos  #Europa position
    eurcolor = 0x9932cc  #Europa color

    ganspot = ganpos  #Ganymede position
    gancolor = 0x9932cc  #Ganymede color

    calspot = calpos  #Calisto position
    calcolor = 0x9932cc  #Calisto color

    lastcolor = 0x000000
    lastiospot = (iospot - 1)

    gang = [iospot, eurspot, ganspot,
            calspot]  #list of the four moon positions

    while True:  # Loop forever

        strip.setBrightness(128)  # Limit brightness
        strip.setPixelColor(jupspot, jupcolor)  # Turn on jupiter to orange
        strip.setPixelColor(gang, 0)  #Turn off last plots
        gang[:] = [x + 1 for x in a]  # +=1 for each member of gang
        strip.setPixelColor(gang, iocolor)  # Turn all moons to blue
        strip.show()  # Refresh strip
        time.sleep(1.0 / 5)
        if t == now:
            strip.setBrightness(128)  #max brightness
            time.sleep(3)
        if (iospot >= numpixels):
            iospot = 0
        if (lastiospot >= numpixels):
            lastiospot = 0
Пример #8
0
def rgbStrip(R, G, B):
    numpixels = 30; # Number of LEDs in strip
    # strip     = Adafruit_DotStar(numpixels, rgb_strip_datapin, rgb_strip_clockpin)
    strip = Adafruit_DotStar(numpixels) # SPI @ ~32 MHz

    strip.begin()           # Initialize pins for output
    strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle

    # Runs 10 LEDs at a time along strip, cycling through red, green and blue.
    # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

    led  = 0               # Index of first 'on' pixel
    while (led != 30): # Loop for each light
        strip.setPixelColor(led, R, G, B) # Set pin color
        strip.show()                     # Refresh strip

        led += 1                        # Advance head position\
Пример #9
0
class Blinkt:
    def __init__(self, host):
        self.host = host
        self.strip = Adafruit_DotStar(numpixels, datapin, clockpin)
        self.strip.begin()
        self.strip.setBrightness(32)

        green = self.to_rgb(0,255,0)
        self.show_all(green)
    def to_rgb(self,r,g,b):
        return (g << 16) + (r << 8) + b
    def show(self, colour, pixel):
        self.strip.setPixelColor(pixel, colour)
        self.strip.show()
    def show_all(self, colour):
        for x in range(0,8):
            self.strip.setPixelColor(x, colour)
        self.strip.show()
Пример #10
0
def rgbStrip(R, G, B):
    numpixels = 30
    # Number of LEDs in strip
    # strip     = Adafruit_DotStar(numpixels, rgb_strip_datapin, rgb_strip_clockpin)
    strip = Adafruit_DotStar(numpixels)  # SPI @ ~32 MHz

    strip.begin()  # Initialize pins for output
    strip.setBrightness(64)  # Limit brightness to ~1/4 duty cycle

    # Runs 10 LEDs at a time along strip, cycling through red, green and blue.
    # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

    led = 0  # Index of first 'on' pixel
    while (led != 30):  # Loop for each light
        strip.setPixelColor(led, R, G, B)  # Set pin color
        strip.show()  # Refresh strip

        led += 1  # Advance head position\
Пример #11
0
class LedStrip:
    forward = True
    numpixels = 80
    head = 0
    tail = -10

    def random_color(self):
        return random.choice(colors)

    def __init__(self, datapin, clockpin):
        self.datapin = datapin
        self.clockpin = clockpin
        self.strip = Adafruit_DotStar(self.numpixels,
                                      self.datapin,
                                      self.clockpin,
                                      order='bgr')
        self.strip.begin()
        self.strip.setBrightness(255)
        self.color = self.random_color()

    def step(self):
        if self.forward:
            if self.head < self.numpixels:
                self.strip.setPixelColor(self.head,
                                         self.color)  # Turn on 'head' pixel
                self.strip.setPixelColor(self.tail, 0)  # Turn off 'tail'
                self.head += 1
                self.tail += 1
            else:
                self.color = self.random_color()
                self.head = 70
                self.tail = 80
                self.forward = False

        else:  # backwards
            if self.head >= 0:
                self.strip.setPixelColor(self.head,
                                         self.color)  # Turn on 'head' pixel
                self.strip.setPixelColor(self.tail, 0)  # Turn off 'tail'
                self.head = self.head - 1
                self.tail = self.tail - 1
            else:
                self.head = 10
                self.tail = 0
                self.color = self.random_color()
                self.forward = True

    def render(self):
        self.strip.show()
Пример #12
0
class StripClient(object):
    def __init__(self, numpixels):
        self.numpixels = numpixels
        self.strip = Adafruit_DotStar(numpixels)
        self.strip.begin()
        self.strip.setBrightness(64)

    def clear(self):
        self.strip.clear()
        print("clear")

    def setBrightness(self, value):
        self.strip.setBrightness(value)
        self.strip.show()
        print("setBrightness:", value)

    def setPixelColor(self, pixel, color):
        color_value = ((color[0] & 0xFF) << 8) | (
            (color[1] & 0xFF) << 16) | (color[2] & 0xFF)
        self.strip.setPixelColor(pixel, color_value)
        self.strip.show()
        print("setPixelColor:", pixel, color)

    def show(self):
        self.strip.show()
        print("show")

    def getPixelColor(self):
        self.strip.getPixelColor()
        print("getPixelColor")

    def numPixels(self):
        return self.strip.numPixels()
        return self.numpixels

    def getBrightness(self):
        return self.strip.getBrightness()
        return 64
Пример #13
0
def rgbStripTest():
    numpixels = 30
    # Number of LEDs in strip

    # strip     = Adafruit_DotStar(numpixels, datapin, clockpin)
    strip = Adafruit_DotStar(numpixels, 12000000)  # SPI @ ~32 MHz

    strip.begin()  # Initialize pins for output
    strip.setBrightness(64)  # Limit brightness to ~1/4 duty cycle

    # Runs 10 LEDs at a time along strip, cycling through red, green and blue.
    # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

    head = 0  # Index of first 'on' pixel
    tail = -10  # Index of last 'off' pixel
    color = 0xFF0000  # 'On' color (starts red)
    repeat = 0

    while True:  # Loop forever
        strip.setPixelColor(head, color)  # Turn on 'head' pixel
        strip.setPixelColor(tail, 0)  # Turn off 'tail'
        strip.show()  # Refresh strip
        time.sleep(1.0 / 50)  # Pause 20 milliseconds (~50 fps)

        head += 1  # Advance head position
        if (head >= numpixels):  # Off end of strip?
            head = 0  # Reset to start
            color >>= 8  # Red->green->blue->black
            if (color == 0): color = 0xFF0000  # If black, reset to red

        tail += 1  # Advance tail position
        if (tail >= numpixels):
            tail = 0  # Off end? Reset
            repeat += 1

        if (repeat == 10):
            rgbStripOff(strip)
            break
Пример #14
0
def rgbStripTest():
    numpixels = 30; # Number of LEDs in strip

    # strip     = Adafruit_DotStar(numpixels, datapin, clockpin)
    strip   = Adafruit_DotStar(numpixels, 12000000) # SPI @ ~32 MHz

    strip.begin()           # Initialize pins for output
    strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle

    # Runs 10 LEDs at a time along strip, cycling through red, green and blue.
    # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

    head  = 0               # Index of first 'on' pixel
    tail  = -10             # Index of last 'off' pixel
    color = 0xFF0000        # 'On' color (starts red)
    repeat = 0

    while True:                              # Loop forever
        strip.setPixelColor(head, color) # Turn on 'head' pixel
        strip.setPixelColor(tail, 0)     # Turn off 'tail'
        strip.show()                     # Refresh strip
        time.sleep(1.0 / 50)             # Pause 20 milliseconds (~50 fps)

        head += 1                        # Advance head position
        if(head >= numpixels):           # Off end of strip?
            head    = 0              # Reset to start
            color >>= 8              # Red->green->blue->black
            if(color == 0): color = 0xFF0000 # If black, reset to red

        tail += 1                        # Advance tail position
        if(tail >= numpixels):
            tail = 0  # Off end? Reset
            repeat += 1

        if(repeat == 10):
            rgbStripOff(strip)
            break;
Пример #15
0
numpixels = 72                  # Number of LEDs in strip

# Here's how to control the strip from any two GPIO pins:
datapin  = 23
clockpin = 24
strip    = Adafruit_DotStar(numpixels, datapin, clockpin)

strip.begin()                   # Initialize pins for output
strip.setBrightness(8)         # Limit brightness to ~1/4 duty cycle

#turn all leds to black (off)
offspot = 1
offcolor = 0x000000
nump = 73
while offspot < nump:
        strip.setPixelColor(offspot, offcolor)
        offspot += 1
        strip.show()

#PYEPHEM PART--GET MOON SPOTS

moons = ((ephem.Io(), 'i'),
         (ephem.Europa(), 'e'),
         (ephem.Ganymede(), 'g'),
         (ephem.Callisto(), 'c'))

linelen = 72
maxradii = 36

def put(line, character, radii):
    if abs(radii) > maxradii:
        # Don't add anything new
        for i in range(16):
            for j in range(16):
                matrixLEDintensity[16 * i + j] = 0

    # Add the line intensity to the map and display it
    for i in range(16):
        for j in range(16):
            matrixLEDcurrent[16 * i + j] = matrixLEDcurrent[
                16 * i + j] + matrixLEDintensity[16 * i +
                                                 j]  # Store current values
            ## pixels( matrixLEDindex[ 16*i+j] ) = matrixLEDcurrent[ 16*i+j ]
            if flagPi:
                # strip.setPixelColor( matrixLEDindex[ 16*i+j ] , 0 , 0 , matrixLEDcurrent[16*i+j] ) # Write to pixel o/p, g,r,b
                strip.setPixelColor(
                    matrixLEDindex[16 * i + j], colscale *
                    matrixLEDcurrent[16 * i + j])  # Write to pixel o/p, g,r,b

# --------------------------------------------------------
# DISK
# --------------------------------------------------------

# --------------------------------------------------------
# STRIP
# --------------------------------------------------------

#----- Rest of Strip
    pixstart = 0
    #    pixstop = pixstart+3*300  # Just strip
    pixstop = pixstart + 3 * 300 + 255  # Strip and disk
    pixlistall = list(range(pixstart, pixstop))
Пример #17
0
        hat.clear()
        hat.show()
        time.sleep(2)
        continue

    annimation = None
    animation_file = "{}{}.json".format(ANIMATION_PATH, status['name'])
    with open(animation_file, 'r') as infile:
        annimation = json.loads(infile.read())

    fps = 15
    for frame in annimation['frames']:
        # munge frame array into list of pixels
        frame_width = len(frame)
        frame_height = len(frame[0])
        pixel_index = 0
        for y in range(frame_height - 1, -1, -1):
            for x in range(0, frame_width):
                pixel = frame[x][y].split(",")
                hat.setPixelColor(pixel_index, int(pixel[0]), int(pixel[1]),
                                  int(pixel[2]))
                pixel_index += 1
        hat.show()
        time.sleep(1.0 / fps)


@atexit.register
def shutdown():
    hat.clear()
    hat.show()
Пример #18
0
        r_start = 0xFF
        g_start = 0x00
        b_start = 0x00

        for s in range(0x00,0xFF):
                r = r_start - s
                g = g_start + s
                b = b_start
                
                color = r*0x010000 + g*0x000100 + b*0x000001
                time.sleep(delay)
                head += 1

                for i in range(31):             #Step through all pixels in my led strip (1-30)
#                        strip.setPixelColor(i, color) # Turn on pixel #i
                        strip.setPixelColor(i, color + i * 0xFF / 32 + s + head) # Turn on pixel #i

                strip.show()                     # Refresh strip

                time.sleep(delay)            # pause delay seconds
                head += 1
        
        #------------------#
        # Green -> Blue
        #------------------#
         
        r_start = 0x00
        g_start = 0xFF
        b_start = 0x00

        for s in range(0x00,0xFF):
Пример #19
0
def run_strip(mode="off", brightness=255):

    numpixels = 240  # Number of LEDs in strip

    print("run_strip inbound mode:", mode)
    # Here's how to control the strip from any two GPIO pins:
    datapin = 10
    clockpin = 11
    strip = Adafruit_DotStar(numpixels, datapin, clockpin)

    # brightness is an integer from 1 to 255
    # mode, in time, should enable other things besides just being full on

    # strip.begin()                       # Initialize pins for output
    # strip.setBrightness(brightness)     # Limit brightness to ~1/4 duty cycle

    # used for mode: comet
    # head = 0               # Index of first 'on' pixel
    # tail = -10             # Index of last 'off' pixel
    color = 0xFFFFFF  # 'On' color (starts red)

    # some control variables for light power on/off easing
    _pow = 3
    _frames = 50
    _maxb = 255  # _max_brightness, might change when brightness configuration is enabled

    if mode == "off":
        print("run_strip: turn off strip")

        try:
            count = 0
            const = _maxb**(1 / (_pow * 1.0))
            is_turning_off = True
            strip.begin()

            while is_turning_off:
                count += 1

                if count == _frames:
                    is_turning_off = False
                    strip.setBrightness(_maxb)  # now that ramping is done set
                    # to max configured brightness
                else:
                    brightness = int(_maxb - (count /
                                              (_frames * 1.0) * const)**_pow)
                    strip.setBrightness(brightness)

                for idx in range(numpixels):
                    strip.setPixelColor(idx, color)

                strip.show()  # Refresh strip
                time.sleep(1.0 / 50)

        except KeyboardInterrupt:
            print("cleaning up")
            GPIO.cleanup()
            strip.clear()
            strip.show()
            print("done")

        # try to set color to black/off before turning off to prevent final flash
        for idx in range(numpixels):
            strip.setPixelColor(idx, 0x000000)
        strip.setBrightness(0)

        # clean up interrupts?
        # GPIO.cleanup()
        # strip.clear()
        strip.show()
        # print("done")

    elif mode == "on":
        print("run_strip: starting strip")
        try:
            count = 0
            const = _maxb**(1 / (_pow * 1.0))
            is_turning_on = True

            strip.begin()

            while True:  # Loop forever

                if is_turning_on:
                    count += 1.0

                    if count == _frames:
                        is_turning_on = False
                        strip.setBrightness(
                            _maxb)  # now that ramping is done set
                        # to max configured brightness
                    else:
                        brightness = int(
                            (count / (_frames * 1.0) * const)**_pow)
                        strip.setBrightness(brightness)

                for idx in range(numpixels):
                    strip.setPixelColor(idx, color)

                # strip.setPixelColor(head, color) # Turn on 'head' pixel
                # strip.setPixelColor(tail, 0)     # Turn off 'tail'
                strip.show()  # Refresh strip
                time.sleep(1.0 / 50)  # Pause 20 milliseconds (~50 fps)

                # head += 1                        # Advance head position
                # if(head >= numpixels):           # Off end of strip?
                #    head    = 0              # Reset to start
                #    color >>= 8              # Red->green->blue->black
                #    if(color == 0): color = 0xFF0000 # If black, reset to red

                # tail += 1                        # Advance tail position
                # if(tail >= numpixels): tail = 0  # Off end? Reset

        except KeyboardInterrupt:
            print("cleaning up")
            GPIO.cleanup()
            strip.clear()
            strip.show()
            print("done")

        except SystemError as err:
            print("SystemError:", err)
Пример #20
0
#!/usr/bin/python

import time
from dotstar import Adafruit_DotStar

numpixels = 230  # Number of LEDs in strip

# Here's how to control the strip from any two GPIO pins:
datapin = 17
clockpin = 27
strip = Adafruit_DotStar(numpixels, datapin, clockpin)

# Alternate ways of declaring strip:
# strip   = Adafruit_DotStar(numpixels)           # Use SPI (pins 10=MOSI, 11=SCLK)
# strip   = Adafruit_DotStar(numpixels, 32000000) # SPI @ ~32 MHz
# strip   = Adafruit_DotStar()                    # SPI, No pixel buffer
# strip   = Adafruit_DotStar(32000000)            # 32 MHz SPI, no pixel buf

# Append "order='gbr'" to declaration for proper colors w/older DotStar strips)
strip.begin()  # Initialize pins for output
strip.setBrightness(192)  # Limit brightness to ~1/4 duty cycle

# green, red, blue

for i in range(numpixels):
    strip.setPixelColor(i, i, 255, 50)

strip.show()  # Refresh strip
Пример #21
0
    active = False

  # call function again
  startTimer()



# initialize
init()

counter = 0
while True:
  counter += 1
  # flash one LED red if there is trouble connecting
  if not active:
    for num in range(1, LED_COUNT):
      strip.setPixelColor(num, 0, 0, 0)
    bri = math.fabs(math.sin(counter * 0.05))
    strip.setPixelColor(0, int(255 * bri), 0, 0)
  else:
    # smooth fade in & out
    for idx, hour in enumerate(precipHours): 
      bri = math.fabs(math.sin((counter + (idx * 25)) * 0.05))
      if hour[0] == 'r':
        precipColor = rain
      elif hour[0] == 's':
        precipColor = snow
      strip.setPixelColor(hour[1], int(precipColor.r * bri), int(precipColor.g * bri), int(precipColor.b * bri))
  strip.show()
  time.sleep(1.0 / 50)             # Pause 20 milliseconds (~50 fps)
Пример #22
0
        return makeColor(255 - wheelPos * 3, 0, wheelPos * 3)

def prog1():
    for j in reversed(range(pixels)):
        for i in range(j):
            strip.setPixelColor(i, 0xFF0000)
            strip.show()
            strip.setPixelColor(i, 0)
            time.sleep(delay)
        strip.setPixelColor(i, 0xFF0000)



while True:
    if GPIO.input(IRLED) == GPIO.LOW:
       	time.sleep(0.0001)  # wait 10 ms to give CPU chance to do other things    
        # print("I saw the LED")
	GPIO.output(LED, False)
    for j in reversed(range(pixels)):
        for i in range(j):
            strip.setPixelColor(i, 0)
            strip.show()
            time.sleep(delay)

	#colorWipe(strip, Color(0,255,0))
    else: 
        #print("I saw an object")
        #GPIO.output(LED, True)  
        prog1()
        
Пример #23
0
import time
from dotstar import Adafruit_DotStar


numpixels = 360 

datapin   = 23
clockpin  = 18
strip     = Adafruit_DotStar(numpixels, 125000000)

strip.begin()           # Initialize pins for output
strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle




for count in xrange(0, 60):
                strip.setPixelColor(count, 0x000000)
                strip.show()


    
    

Пример #24
0
class Elevator(threading.Thread):
    def __init__(self, kill_event, loop_time=1.0 / 60.0):
        self.status = "INIT"
        self.q = Queue()
        self.kill_event = kill_event
        self.timeout = loop_time
        self.baudrate = BAUDRATE
        self.dev      = DEVICE

        self.strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN)
        self.strip.begin()
        self.strip.setBrightness(255)
        self.serial = serial.Serial(self.dev)
        self.serial.baudrate = 115200

        # Initial state
        self.send_elevator_command(ELEVATOR_DOWN)
        self.status = "DOWN"
        self.set_lights(OFF)

        super(Elevator, self).__init__()

    def onThread(self, function, *args, **kwargs):
        self.q.put((function, args, kwargs))

    def run(self):
        self.down()
        while True:
            if self.kill_event.is_set():
                self.close()
                return

            try:
                function, args, kwargs = self.q.get(timeout=self.timeout)
                function(*args, **kwargs)
            except Empty:
                pass

    def send_elevator_command(self, command):
        self.serial.flushInput()  # avoids that the input buffer overfloats
        self.serial.write(command)
        self.serial.flush()

    def up(self):
        self.status = "GOING_UP"
        self.send_elevator_command(ELEVATOR_UP)
        time.sleep(TIME_UP_S)
        self.status = "UP"
        self.set_lights(GREEN)

    def down(self):
        self.status = "GOING_DOWN"
        self.send_elevator_command(ELEVATOR_DOWN)
        self.set_lights(OFF)
        time.sleep(TIME_DOWN_S)
        self.status = "DOWN"
        time.sleep(TIME_TO_LEAVE_ELEVATOR_S)
        self.status = "FREE"
        
    def close(self):
        self.serial.close()

    def set_lights(self, color):
        for i in range(NUMPIXELS):
            self.strip.setPixelColor(i, color)
        if color == OFF:
            self.strip.setBrightness(0)
        else:
            self.strip.setBrightness(255)
        self.strip.show()
Пример #25
0
# Set the strip to all white at lowest brightness, and slowly ramp up.

import time
from dotstar import Adafruit_DotStar

WHITE = 0xFFFFFF
n_pixels = 72	# Number of LEDs in strip
strip   = Adafruit_DotStar(n_pixels)	# Use SPI (pins 10=MOSI, 11=SCLK)
strip.begin()	# Initialize pins for output

# Open log file.
f = open('powerlog.txt', 'w')
f.write("Brightness\tVoltage\n")

for p in range(n_pixels):
	strip.setPixelColor(p, WHITE)

for b in range(256):
	#print b
	# Set the brightness.
	strip.setBrightness(b)
	strip.show()                     # Refresh strip
	# Prompt user for data entry.
	answer = raw_input(str(b)+' ')
	# Log it.
	f.write(str(b)+"\t"+answer+"\n")
	f.flush()
	# Wait a fraction of a second to help ensure that the write completes,
	# in case the next brightness level crashes the system.
	time.sleep(0.1)
        #------------------#
        
        r_start = 0xFF
        g_start = 0x00
        b_start = 0x00

        for s in range(0x00,0xFF):
                r = r_start - s
                g = g_start + s
                b = b_start
                
                color = r*0x010000 + g*0x000100 + b*0x000001

                for i in range(31):             #Step through all pixels in my led strip (1-30)
#                        strip.setPixelColor(i, color) # Turn on pixel #i
                        strip.setPixelColor(i, color + i / 32 * 0xFF) # Turn on pixel #i

                strip.show()                     # Refresh strip

                time.sleep(delay)            # pause delay seconds

        
        #------------------#
        # Green -> Blue
        #------------------#
        
        r_start = 0x00
        g_start = 0xFF
        b_start = 0x00

        for s in range(0x00,0xFF):
Пример #27
0
# first resolve an ContactQuality stream on the lab network
print("looking for a ContactQuality stream...")
streams = resolve_stream('type', 'ContactQuality')

# LED Strip Setup
numpixels = 72  # Number of LEDs in strip
strip = Adafruit_DotStar(numpixels, 125000, order='bgr')

print 'strip object created'

strip.begin()  # Initialize pins for output
strip.setBrightness(8)  # Limit brightness to ~1/4 duty cycle

# reset strip
for ledi in range(0, numpixels):
    strip.setPixelColor(ledi, 0x00FF00)
    strip.show()

    strip.setPixelColor(ledi, 0)
    strip.show()

# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])
info = inlet.info()
print(info.as_xml())

print("The channel labels are as follows:")
ch = info.desc().child("channels").child("channel")
for k in range(info.channel_count()):
    print ",  " + ch.child_value("label"),
    ch = ch.next_sibling()
Пример #28
0
#!/usr/bin/python

import time
from dotstar import Adafruit_DotStar

numpixels = 230 # Number of LEDs in strip

# Here's how to control the strip from any two GPIO pins:
datapin   = 17
clockpin  = 27
strip     = Adafruit_DotStar(numpixels, datapin, clockpin)

# Alternate ways of declaring strip:
# strip   = Adafruit_DotStar(numpixels)           # Use SPI (pins 10=MOSI, 11=SCLK)
# strip   = Adafruit_DotStar(numpixels, 32000000) # SPI @ ~32 MHz
# strip   = Adafruit_DotStar()                    # SPI, No pixel buffer
# strip   = Adafruit_DotStar(32000000)            # 32 MHz SPI, no pixel buf

# Append "order='gbr'" to declaration for proper colors w/older DotStar strips)
strip.begin()           # Initialize pins for output
strip.setBrightness(192) # Limit brightness to ~1/4 duty cycle

# green, red, blue
h = raw_input('Enter hex: ').lstrip('#')
j = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))
print j
for i in range(numpixels):
    strip.setPixelColor(i, j[0], j[1], j[2])

strip.show()                     # Refresh strip
Пример #29
0
#!/usr/bin/python
#Turn off all leds

import time
from dotstar import Adafruit_DotStar

#INITIALIZE AND CLEAR DOTSTAR

numpixels = 72  # Number of LEDs in strip

# Here's how to control the strip from any two GPIO pins:
datapin = 23
clockpin = 24
strip = Adafruit_DotStar(numpixels, datapin, clockpin)

strip.begin()  # Initialize pins for output
strip.setBrightness(32)  # Limit brightness to ~1/4 duty cycle

#turn all leds to black (off)
offspot = 1
offcolor = 0x000000
nump = 73
while offspot < nump:
    strip.setPixelColor(offspot, offcolor)
    offspot += 1
    strip.show()
Пример #30
0
}

CHECK_TIME = 120  # How often to check the website
TIME_BETWEEN_PIXELS = .02  # Seconds from one pixel to the next
led_number = 0  # Which LED are we setting right now?
tot_time = CHECK_TIME  # So we'll check immediately

while True:
    if tot_time >= CHECK_TIME:
        keywords_found = scrape.match_keywords('http://slashdot.org',
                                               topicwords)
        tot_time = 0
        print(keywords_found)

    tot_hits = sum(keywords_found[i] for i in keywords_found)
    if num_pixels % tot_hits == 0 or tot_hits % num_pixels == 0:
        keywords_found['blank'] = 1

    # Loop over the topics:
    for topic in keywords_found:
        # For this topic, keywords_found[topic] is the number of keywords
        # we matched on Twitter. Show that number of pixels.
        # The color for this topic is topiccolors[topic].
        for i in range(keywords_found[topic]):
            strip.setPixelColor(led_number, topiccolors[topic])
            strip.show()

            led_number = (led_number + 1) % num_pixels
            time.sleep(TIME_BETWEEN_PIXELS)
            tot_time += TIME_BETWEEN_PIXELS
Пример #31
0
#!/usr/bin/python

import time
import math
import array
from dotstar import Adafruit_DotStar

numpixels = 72 # Number of LEDs in strip

strip   = Adafruit_DotStar(numpixels)           # Use SPI (pins 10=MOSI, 11=SCLK)

strip.begin()           # Initialize pins for output
strip.setBrightness(64) # Limit brightness to ~1/2 duty cycle

# Initialize CA, for now with 1 pixel
cells = array.array('B',(0,)*numpixels)

# Set strip colors and display them
for i in range(numpixels):
	strip.setPixelColor(i, 0x000000)
strip.show()                     # Refresh strip
Пример #32
0
class Bartender(MenuDelegate):
    def __init__(self):
        self.running = False

        # set the oled screen height
        self.screen_width = SCREEN_WIDTH
        self.screen_height = SCREEN_HEIGHT

        self.btn1Pin = LEFT_BTN_PIN
        self.btn2Pin = RIGHT_BTN_PIN

        # configure interrups for buttons
        GPIO.setup(self.btn1Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.btn2Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        # configure screen
        spi_bus = 0
        spi_device = 0

        #Load the display driver. Attention: 128_64 is the display size. Needed to be changed if different in your setup
        self.led = disp = Adafruit_SSD1306.SSD1306_128_64(
            rst=RST,
            dc=DC,
            spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)
        )  # Change rows & cols values depending on your display dimensions.

        # Initialize library.
        self.led.begin()

        # Clear display.
        self.led.clear()
        self.led.display()

        # Create image buffer.
        # Make sure to create image with mode '1' for 1-bit color.
        self.image = Image.new('1', (self.screen_width, self.screen_height))

        # Load default font.
        #self.font = ImageFont.load_default()
        self.font = ImageFont.truetype(FONTFILE, FONTSIZE)

        # Create drawing object.
        self.draw = ImageDraw.Draw(self.image)

        # load the pump configuration from file
        self.pump_configuration = Bartender.readPumpConfiguration()
        for pump in self.pump_configuration.keys():
            GPIO.setup(self.pump_configuration[pump]["pin"],
                       GPIO.OUT,
                       initial=GPIO.HIGH)

        # setup pixels:
        self.numpixels = NUMBER_NEOPIXELS  # Number of LEDs in strip

        # Here's how to control the strip from any two GPIO pins:
        datapin = NEOPIXEL_DATA_PIN
        clockpin = NEOPIXEL_CLOCK_PIN
        self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin)
        #Auskommentiert solange noch kein LED Strip angebracht.
        #self.strip.begin()           # Initialize pins for output
        self.strip.setBrightness(
            NEOPIXEL_BRIGHTNESS)  # Limit brightness to ~1/4 duty cycle

        # turn everything off
        for i in range(0, self.numpixels):
            self.strip.setPixelColor(i, 0)
        self.strip.show()

        print "Done initializing"

    @staticmethod
    def readPumpConfiguration():
        return json.load(open('pump_config.json'))

    @staticmethod
    def writePumpConfiguration(configuration):
        with open("pump_config.json", "w") as jsonFile:
            json.dump(configuration, jsonFile)

    def startInterrupts(self):
        GPIO.add_event_detect(self.btn1Pin,
                              GPIO.FALLING,
                              callback=self.left_btn,
                              bouncetime=LEFT_PIN_BOUNCE)
        GPIO.add_event_detect(self.btn2Pin,
                              GPIO.FALLING,
                              callback=self.right_btn,
                              bouncetime=RIGHT_PIN_BOUNCE)

    def buildMenu(self, drink_list, drink_options):
        # create a new main menu
        m = Menu("Main Menu")

        # add drink options
        drink_opts = []
        for d in drink_list:
            drink_opts.append(
                MenuItem('drink', d["name"],
                         {"ingredients": d["ingredients"]}))

        configuration_menu = Menu("Configure")

        # add pump configuration options
        pump_opts = []
        for p in sorted(self.pump_configuration.keys()):
            config = Menu(self.pump_configuration[p]["name"])
            # add fluid options for each pump
            for opt in drink_options:
                # star the selected option
                selected = "*" if opt["value"] == self.pump_configuration[p][
                    "value"] else ""
                config.addOption(
                    MenuItem('pump_selection', opt["name"], {
                        "key": p,
                        "value": opt["value"],
                        "name": opt["name"]
                    }))
            # add a back button so the user can return without modifying
            config.addOption(Back("Back"))
            config.setParent(configuration_menu)
            pump_opts.append(config)

        # add pump menus to the configuration menu
        configuration_menu.addOptions(pump_opts)
        # add a back button to the configuration menu
        configuration_menu.addOption(Back("Back"))
        # adds an option that cleans all pumps to the configuration menu
        configuration_menu.addOption(MenuItem('clean', 'Clean'))
        # adds an option that shuts down the rpi
        configuration_menu.addOption(MenuItem('shutdown', 'Shutdown'))

        configuration_menu.setParent(m)

        m.addOptions(drink_opts)
        m.addOption(configuration_menu)

        # create a menu context
        self.menuContext = MenuContext(m, self)

    def filterDrinks(self, menu):
        """
		Removes any drinks that can't be handled by the pump configuration
		"""
        for i in menu.options:
            if (i.type == "drink"):
                i.visible = False
                ingredients = i.attributes["ingredients"]
                presentIng = 0
                for ing in ingredients.keys():
                    for p in self.pump_configuration.keys():
                        if (ing == self.pump_configuration[p]["value"]):
                            presentIng += 1
                if (presentIng == len(ingredients.keys())):
                    i.visible = True
            elif (i.type == "menu"):
                self.filterDrinks(i)

    def selectConfigurations(self, menu):
        """
		Adds a selection star to the pump configuration option
		"""
        for i in menu.options:
            if (i.type == "pump_selection"):
                key = i.attributes["key"]
                if (self.pump_configuration[key]["value"] ==
                        i.attributes["value"]):
                    i.name = "%s %s" % (i.attributes["name"], "*")
                else:
                    i.name = i.attributes["name"]
            elif (i.type == "menu"):
                self.selectConfigurations(i)

    def prepareForRender(self, menu):
        self.filterDrinks(menu)
        self.selectConfigurations(menu)
        return True

    def menuItemClicked(self, menuItem):
        if (menuItem.type == "drink"):
            self.makeDrink(menuItem.name, menuItem.attributes["ingredients"])
            return True
        elif (menuItem.type == "pump_selection"):
            self.pump_configuration[menuItem.attributes["key"]][
                "value"] = menuItem.attributes["value"]
            Bartender.writePumpConfiguration(self.pump_configuration)
            return True
        elif (menuItem.type == "clean"):
            self.clean()
            return True
        elif (menuItem.type == "shutdown"):
            self.shutdown()
            return True
        return False

    def clean(self):
        waitTime = 20
        pumpThreads = []

        # cancel any button presses while the drink is being made
        # self.stopInterrupts()
        self.running = True

        for pump in self.pump_configuration.keys():
            pump_t = threading.Thread(
                target=self.pour,
                args=(self.pump_configuration[pump]["pin"], waitTime))
            pumpThreads.append(pump_t)

        # start the pump threads
        for thread in pumpThreads:
            thread.start()

        # start the progress bar
        self.progressBar(waitTime)

        # wait for threads to finish
        for thread in pumpThreads:
            thread.join()

        # show the main menu
        self.menuContext.showMenu()

        # sleep for a couple seconds to make sure the interrupts don't get triggered
        time.sleep(2)

    def shutdown(self):
        shutdowntext = "Shutdown takes 10 seconds. Bye!"
        self.led.clear()
        self.draw.rectangle((0, 0, self.screen_width, self.screen_height),
                            outline=0,
                            fill=0)

        words_list = WRAPPER.wrap(text=shutdowntext)
        TextNew = ''
        for ii in words_list[:-1]:
            TextNew = TextNew + ii + "\n"
        TextNew += words_list[-1]
        self.draw.text((0, 10), str(TextNew), font=self.font, fill=255)
        self.led.image(self.image)
        self.led.display()
        time.sleep(5)

        #Clean shutdown device
        subprocess.Popen(['shutdown', '-h', 'now'])

    def displayMenuItem(self, menuItem):
        print menuItem.name
        self.led.clear()
        self.draw.rectangle((0, 0, self.screen_width, self.screen_height),
                            outline=0,
                            fill=0)

        words_list = WRAPPER.wrap(text=menuItem.name)
        MenuItemNew = ''
        for ii in words_list[:-1]:
            MenuItemNew = MenuItemNew + ii + "\n"
        MenuItemNew += words_list[-1]
        self.draw.text((0, 10), str(MenuItemNew), font=self.font, fill=255)
        self.led.image(self.image)
        self.led.display()

    def cycleLights(self):
        t = threading.currentThread()
        head = 0  # Index of first 'on' pixel
        tail = -10  # Index of last 'off' pixel
        color = 0xFF0000  # 'On' color (starts red)

        while getattr(t, "do_run", True):
            self.strip.setPixelColor(head, color)  # Turn on 'head' pixel
            self.strip.setPixelColor(tail, 0)  # Turn off 'tail'
            self.strip.show()  # Refresh strip
            time.sleep(1.0 / 50)  # Pause 20 milliseconds (~50 fps)

            head += 1  # Advance head position
            if (head >= self.numpixels):  # Off end of strip?
                head = 0  # Reset to start
                color >>= 8  # Red->green->blue->black
                if (color == 0): color = 0xFF0000  # If black, reset to red

            tail += 1  # Advance tail position
            if (tail >= self.numpixels): tail = 0  # Off end? Reset

    def lightsEndingSequence(self):
        # make lights green
        for i in range(0, self.numpixels):
            self.strip.setPixelColor(i, 0xFF0000)
        self.strip.show()

        time.sleep(5)

        # turn lights off
        for i in range(0, self.numpixels):
            self.strip.setPixelColor(i, 0)
        self.strip.show()

    def pour(self, pin, waitTime):
        GPIO.output(pin, GPIO.LOW)
        time.sleep(waitTime)
        GPIO.output(pin, GPIO.HIGH)

    def progressBar(self, waitTime):
        interval = waitTime / 100.0
        for x in range(1, 101):
            self.led.clear()
            self.draw.rectangle((0, 0, self.screen_width, self.screen_height),
                                outline=0,
                                fill=0)
            self.updateProgressBar(x, y=35)
            self.led.image(self.image)
            self.led.display()
            time.sleep(interval)

    def makeDrink(self, drink, ingredients):
        # cancel any button presses while the drink is being made
        # self.stopInterrupts()
        self.running = True

        # launch a thread to control lighting
        lightsThread = threading.Thread(target=self.cycleLights)
        lightsThread.start()

        # Parse the drink ingredients and spawn threads for pumps
        maxTime = 0
        pumpThreads = []
        for ing in ingredients.keys():
            for pump in self.pump_configuration.keys():
                if ing == self.pump_configuration[pump]["value"]:
                    waitTime = ingredients[ing] * FLOW_RATE
                    if (waitTime > maxTime):
                        maxTime = waitTime
                    pump_t = threading.Thread(
                        target=self.pour,
                        args=(self.pump_configuration[pump]["pin"], waitTime))
                    pumpThreads.append(pump_t)

        # start the pump threads
        for thread in pumpThreads:
            thread.start()

        # start the progress bar
        self.progressBar(maxTime)

        # wait for threads to finish
        for thread in pumpThreads:
            thread.join()

        # show the main menu
        self.menuContext.showMenu()

        # stop the light thread
        lightsThread.do_run = False
        lightsThread.join()

        # show the ending sequence lights
        self.lightsEndingSequence()

        # sleep for a couple seconds to make sure the interrupts don't get triggered
        time.sleep(2)

        # reenable interrupts
        # self.startInterrupts()
        self.running = False

    def left_btn(self, ctx):
        print("LEFT_BTN pressed")
        if not self.running:
            self.running = True
            self.menuContext.advance()
            print("Finished processing button press")
        self.running = False

    def right_btn(self, ctx):
        print("RIGHT_BTN pressed")
        if not self.running:
            self.running = True
            self.menuContext.select()
            print("Finished processing button press")
            self.running = 2
            print("Starting button timeout")

    def updateProgressBar(self, percent, x=15, y=15):
        height = 10
        width = self.screen_width - 2 * x
        for w in range(0, width):
            self.draw.point((w + x, y), fill=255)
            self.draw.point((w + x, y + height), fill=255)
        for h in range(0, height):
            self.draw.point((x, h + y), fill=255)
            self.draw.point((self.screen_width - x, h + y), fill=255)
            for p in range(0, percent):
                p_loc = int(p / 100.0 * width)
                self.draw.point((x + p_loc, h + y), fill=255)

    def run(self):
        self.startInterrupts()
        # main loop
        try:

            try:

                while True:
                    letter = raw_input(">")
                    if letter == "l":
                        self.left_btn(False)
                    if letter == "r":
                        self.right_btn(False)

            except EOFError:
                while True:
                    time.sleep(0.1)
                    if self.running not in (True, False):
                        self.running -= 0.1
                        if self.running == 0:
                            self.running = False
                            print("Finished button timeout")

        except KeyboardInterrupt:
            GPIO.cleanup()  # clean up GPIO on CTRL+C exit
        GPIO.cleanup()  # clean up GPIO on normal exit

        traceback.print_exc()
Пример #33
0
import os
import serial
import random
import png
import struct
from time import sleep, time
from struct import pack, unpack
from dotstar import Adafruit_DotStar

numpixels = 144
gamma_value = 1.1

gamma = bytearray(256)
for i in range(256):
    gamma[i] = int(pow(float(i) / 255.0, gamma_value) * 255.0 + 0.5)

strip   = Adafruit_DotStar(numpixels, order='bgr')

strip.begin()           # Initialize pins for output
strip.setBrightness(128) # Limit brightness to ~1/4 duty cycle

for row in xrange(144):
    strip.setPixelColor(row, 0)
strip.show()

# FF FF F0

for row in xrange(50):
    strip.setPixelColor(row, 0xaaaaa0)
strip.show()
Пример #34
0
                numpixels = 72  # Number of LEDs in strip

                # Here's how to control the strip from any two GPIO pins:
                datapin = 23
                clockpin = 24
                strip = Adafruit_DotStar(numpixels, datapin, clockpin)

                strip.begin()  # Initialize pins for output
                strip.setBrightness(128)  # Limit brightness to ~1/4 duty cycle

                #First, turn all black
                offspot = 1
                offcolor = 0x000000
                while offspot >= 1:
                    strip.setPixelColor(offspot, offcolor)
                    offspot += 1
                    if offspot == 72:
                        break

                #set initial spots and colors of Jupiter and moons

                jupspot = 36  #jupiter position
                jupcolor = 0xFF8801  #jupiter color

                iospot = iopos  #Io position
                iocolor = 0x9932cc  #Io color

                eurspot = eurpos  #Europa position
                eurcolor = 0x9932cc  #Europa color
Пример #35
0
numpixels = 72  # Number of LEDs in strip

# Here's how to control the strip from any two GPIO pins:
datapin = 23
clockpin = 24
strip = Adafruit_DotStar(numpixels, datapin, clockpin)

strip.begin()  # Initialize pins for output
strip.setBrightness(32)  # Limit brightness to ~1/4 duty cycle

#turn all black
offspot = 1
offcolor = 0x000000
while offspot >= 1:
    strip.setPixelColor(offspot, offcolor)
    offspot += 1
    if offspot == 72:
        break

jupspot = 36  #jupiter position
iospot = 1  #Io position ------------->trying for just one moon
jupcolor = 0xFF8801  #jupiter color
iocolor = 0x9932cc  #Io color
lastiocolor = 0x000000
#lastiospot = (iospot - 1)

while True:  # Loop forever

    findmoons()
    strip.setPixelColor(jupspot, jupcolor)  # Turn on jupiter to orange
Пример #36
0
# See image-pov.py for explanation of no-pixel-buffer use.
# Append "order='gbr'" to declaration for proper colors w/older DotStar strips)

strip.begin()  # Initialize pins for output
strip.setBrightness(255)  # Limit brightness to ~1/4 duty cycle

# Runs 10 LEDs at a time along strip, cycling through red, green and blue.
# This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

head = begin  # Index of first 'on' pixel
tail = -15  # Index of last 'off' pixel
color = 0xFFFFFF  # 'On' color (starts red)

b = 0
while b < 400:
    strip.setPixelColor(b, 0)
    b = b + 1
    print(strip.getPixelColor(b))
strip.show()

while True:  # Loop forever

    strip.setPixelColor(head, color)  # Turn on 'head' pixel
    strip.setPixelColor(tail, 0)  # Turn off 'tail'
    strip.show()  # Refresh strip
    time.sleep(1.0 / 50)  # Pause 20 milliseconds (~50 fps)

    head += 1  # Advance head position
    if (head >= px + begin):  # Off end of strip?
        head = begin  # Reset to start
        #color >>= 8              # Red->green->blue->black
Пример #37
0
#!/usr/bin/python

from dotstar import Adafruit_DotStar

LED_COUNT = 7
datapin   = 10
clockpin  = 11
strip     = Adafruit_DotStar(LED_COUNT, datapin, clockpin)
strip.begin()

for num in range(1, LED_COUNT):
	strip.setPixelColor(num, 0, 0, 0)
strip.show()
Пример #38
0
colorScooter = 1
rainbowCounter1 = 4
rainbowCounter2 = 3
rainbowCounter3 = 2
rainbowCounter4 = 1
rainbowCounter5 = 0

oldDataValue = "none"
adaIoCheckerCounter = 0
data = aio.receive(FEED_ID)

while True:  # Loop forever
    if (data.value != oldDataValue):
        i = 0
        for i in range(0, 45):
            strip.setPixelColor(i, black)
            ++i
        strip.show()  # Refresh strip
        oldDataValue = data.value
    if (oldDataValue == "Off"):
        for i in range(0, 45):
            strip.setPixelColor(i, black)
            ++i
        strip.show()
    elif (oldDataValue == "Christmas"):
        i = 0
        for i in range(0, 45):
            if (i >= 0 and i < 10): color = red
            elif (i >= 10 and i < 20): color = green
            elif (i >= 20 and i < 30): color = red
            elif (i >= 30 and i < 40): color = green
tail  = -10             # Index of last 'off' pixel
color = 0xFF0000        # 'On' color (starts red)
pixels = 50
delay = .001

def makeColor(r, g, b):
    return (r << 16) + (g << 8) + b

def colorWheel(wheelPos):
    if wheelPos < 85:
        return makeColor(wheelPos * 3, 255 - wheelPos * 3, 0)
    elif wheelPos < 170:
        wheelPos -= 85
        return makeColor(0, wheelPos * 3, 255 - wheelPos * 3)
    else:
        wheelPos -= 170
        return makeColor(255 - wheelPos * 3, 0, wheelPos * 3)


while True:
    
    for j in reversed(range(pixels)):
        for i in range(j):
            strip.setPixelColor(i, 0xFF0000)
            strip.show()
            strip.setPixelColor(i, 0)
            time.sleep(delay)
        strip.setPixelColor(i, 0xFF0000)


Пример #40
0
strip.begin()           # Initialize pins for output
strip.setBrightness(32) # Limit brightness to ~1/4 duty cycle

# 3-color totalistic cellular automaton
# colors are 0, 1, 2 (we usually show 0 as black)
colors = (0x000000, 0xFF0000, 0x007F7F)
ca = [0,1,2,1,0,0,1]	# code 777 CA
# see http://mathworld.wolfram.com/TotalisticCellularAutomaton.html

# Initialize CA, for now with 1 pixel
cells = array.array('B',(0,)*numpixels)
cells[int(numpixels/2)] = 2
sum = array.array('B',(0,)*numpixels)

while True:                              # Loop forever

	# Set strip colors and display them
	for i in range(numpixels):
		strip.setPixelColor(i, colors[cells[i]])
	strip.show()                     # Refresh strip

	# Update CA
	for i in range(numpixels):
		# Sum up cell and its neighbors (with wraparound)
		sum[i] = cells[(i+numpixels-1)%numpixels] + cells[i] + cells[(i+1)%numpixels]
	for i in range(numpixels):
		cells[i] = ca[sum[i]]
	
	time.sleep(1.0 / fps)
# Append "order='gbr'" to declaration for proper colors w/older DotStar strips)

strip.begin()           # Initialize pins for output
strip.setBrightness(65) # Limit brightness to ~1/4 duty cycle

# Runs 10 LEDs at a time along strip, cycling through red, green and blue.
# This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

head  = 10               # Index of first 'on' pixel
tail  = 0             # Index of last 'off' pixel
color = 0xFF0000        # 'On' color (starts red)
step = -0x010000

while True:                              # Loop forever
        for i in range(31):
                strip.setPixelColor(i, color) # Turn on 'head' pixel
	strip.show()                     # Refresh strip
	time.sleep(1.0 / 400)            # Pause 20 milliseconds (~50 fps)

#	head += 1                        # Advance head position
#	if(head >= numpixels):           # Off end of strip?
#		head    = 0              # Reset to start
#		color >>= 8              # Red->green->blue->black
#		if(color == 0): color = 0xFF0000 # If black, reset to red
#
#	tail += 1                        # Advance tail position
#	if(tail >= numpixels): tail = 0  # Off end? Reset

#        color = (0.99*color)

        if (color>=0xFF0000): step = -0x010000
Пример #42
0
# strip   = Adafruit_DotStar()                    # SPI, No pixel buffer
# strip   = Adafruit_DotStar(32000000)            # 32 MHz SPI, no pixel buf
# See image-pov.py for explanation of no-pixel-buffer use.
# Append "order='gbr'" to declaration for proper colors w/older DotStar strips)

strip.begin()           # Initialize pins for output
strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle

# Runs 10 LEDs at a time along strip, cycling through red, green and blue.
# This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

head  = 0               # Index of first 'on' pixel
tail  = -20             # Index of last 'off' pixel
color = 0xFF0000        # 'On' color (starts red)

while True:                              # Loop forever

	strip.setPixelColor(head, color) # Turn on 'head' pixel
	strip.setPixelColor(tail, 0)     # Turn off 'tail'
	strip.show()                     # Refresh strip
	time.sleep(1.0 / 100)             # Pause 20 milliseconds (~50 fps)

	head += 1                        # Advance head position
	if(head >= numpixels):           # Off end of strip?
		head    = 0              # Reset to start
		color >>= 8              # Red->green->blue->black
		if(color == 0): color = 0xFF0000 # If black, reset to red

	tail += 1                        # Advance tail position
	if(tail >= numpixels): tail = 0  # Off end? Reset
Пример #43
0
class Bartender(MenuDelegate):
    def __init__(self):
        self.running = False

        # set the oled screen height
        self.screen_width = SCREEN_WIDTH
        self.screen_height = SCREEN_HEIGHT

        self.make_drink = MAKE_DRINK

        self.btn1Pin = LEFT_BTN_PIN
        self.btn2Pin = RIGHT_BTN_PIN

        self.clk = CLK_PIN
        self.dt = DT_PIN

        # configure interrupts for buttons
        #GPIO.setup(self.btn1Pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.btn2Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        # configure interrupts for encoder
        GPIO.setup(self.clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

        #Pi config
        RST = 21
        DC = 20
        SPI_PORT = 0
        SPI_DEVICE = 0

        # configure screen
        self.disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
        self.disp.begin()
        self.disp.clear()
        self.disp.display()

        #draw
        self.image = Image.new('1', (SCREEN_WIDTH, SCREEN_HEIGHT))
        self.draw = ImageDraw.Draw(self.image)
        self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),
                            outline=0,
                            fill=0)
        self.font = ImageFont.load_default()

        # Very important... This lets py-gaugette 'know' what pins to use in order to reset the display
        # Change rows & cols values depending on your display dimensions.

        # load the pump configuration from file
        self.pump_configuration = Bartender.readJson(
            '/home/pi/Documents/PiDrink/static/json/pump_config.json')
        for pump in self.pump_configuration.keys():
            GPIO.setup(self.pump_configuration[pump]["pin"],
                       GPIO.OUT,
                       initial=GPIO.HIGH)

        # load the current drink list
        self.drink_list = Bartender.readJson(
            '/home/pi/Documents/PiDrink/static/json/drink_list.json')
        self.drink_list = self.drink_list["drink_list"]

        # load the current drink options
        self.drink_options = Bartender.readJson(
            '/home/pi/Documents/PiDrink/static/json/drink_options.json')
        self.drink_options = self.drink_options["drink_options"]

        # setup pixels:
        self.numpixels = NUMBER_NEOPIXELS  # Number of LEDs in strip

        # Here's how to control the strip from any two GPIO pins:
        datapin = NEOPIXEL_DATA_PIN
        clockpin = NEOPIXEL_CLOCK_PIN
        self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin)
        self.strip.begin()  # Initialize pins for output
        self.strip.setBrightness(
            NEOPIXEL_BRIGHTNESS)  # Limit brightness to ~1/4 duty cycle

        # turn everything off
        for i in range(0, self.numpixels):
            self.strip.setPixelColor(i, 0)
        self.strip.show()

        print('Done initializing')

    # def check_email(self):
    # 	status, email_ids = self.imap_server.search(None, '(UNSEEN)')
    # 	if email_ids == ['']:
    # 		mail_list = []
    # 	else:
    # 		mail_list = self.get_subjects(email_ids) #FYI when calling the get_subjects function, the email is marked as 'read'
    # 	self.imap_server.close()
    # 	return mail_list

    # def get_subjects(self, email_ids):
    # 	subjects_list = []
    # 	for e_id in email_ids[0].split():
    # 		resp, data = self.imap_server.fetch(e_id, '(RFC822)')
    # 		perf = HeaderParser().parsestr(data[0][1])
    # 		subjects_list.append(perf['Subject'])

    # 	return subjects_list

    def voice_command(self, mail_list):
        for mail in mail_list:
            found = False
            while (found == False):
                currmen = self.menuContext.currentMenu.getSelection()
                if (currmen.name == mail):
                    self.makeDrink(currmen.name,
                                   currmen.attributes["ingredients"])
                    self.make_drink = False
                    found = True
                else:
                    self.menuContext.currentMenu.nextSelection()
            found = False

    @staticmethod
    def readJson(file):
        return json.load(open(file))

    @staticmethod
    def writePumpConfiguration(configuration):
        with open("/home/pi/Documents/PiDrink/static/json/pump_config.json",
                  "w") as jsonFile:
            json.dump(configuration, jsonFile)

    def startInterrupts(self):
        #GPIO.add_event_detect(self.btn1Pin, GPIO.FALLING, callback=self.left_btn, bouncetime=LEFT_PIN_BOUNCE)
        GPIO.add_event_detect(self.btn2Pin,
                              GPIO.FALLING,
                              callback=self.right_btn,
                              bouncetime=RIGHT_PIN_BOUNCE)
        GPIO.add_event_detect(self.clk,
                              GPIO.BOTH,
                              callback=self.rotary_on_change,
                              bouncetime=1000)

    def stopInterrupts(self):
        #GPIO.remove_event_detect(self.btn1Pin)
        GPIO.remove_event_detect(self.btn2Pin)
        GPIO.remove_event_detect(self.clk)

    def buildMenu(self):
        # create a new main menu
        m = Menu("Main Menu")

        # add drink options
        drink_opts = []
        for d in self.drink_list:
            drink_opts.append(
                MenuItem('drink', d["name"],
                         {"ingredients": d["ingredients"]}))

        configuration_menu = Menu("Configure")

        # add pump configuration options
        pump_opts = []
        for p in sorted(self.pump_configuration.keys()):
            config = Menu(self.pump_configuration[p]["name"])
            # add fluid options for each pump
            for opt in self.drink_options:
                # star the selected option
                selected = "*" if opt["value"] == self.pump_configuration[p][
                    "value"] else ""
                config.addOption(
                    MenuItem('pump_selection', opt["name"], {
                        "key": p,
                        "value": opt["value"],
                        "name": opt["name"]
                    }))

            # add a back button so the user can return without modifying
            config.addOption(Back("Back"))
            config.setParent(configuration_menu)
            pump_opts.append(config)

        # add pump menus to the configuration menu
        configuration_menu.addOptions(pump_opts)
        # add a back button to the configuration menu
        configuration_menu.addOption(Back("Back"))
        # adds an option that cleans all pumps to the configuration menu
        configuration_menu.addOption(MenuItem('clean', 'Clean'))
        configuration_menu.setParent(m)

        m.addOptions(drink_opts)
        m.addOption(configuration_menu)
        # create a menu context
        self.menuContext = MenuContext(m, self)

    def filterDrinks(self, menu):
        """
		Removes any drinks that can't be handled by the pump configuration
		"""
        for i in menu.options:
            if (i.type == "drink"):
                i.visible = False
                ingredients = i.attributes["ingredients"]
                presentIng = 0
                for ing in ingredients.keys():
                    for p in self.pump_configuration.keys():
                        if (ing == self.pump_configuration[p]["value"]):
                            presentIng += 1
                if (presentIng == len(ingredients.keys())):
                    i.visible = True
            elif (i.type == "menu"):
                self.filterDrinks(i)

    def selectConfigurations(self, menu):
        """
		Adds a selection star to the pump configuration option
		"""
        for i in menu.options:
            if (i.type == "pump_selection"):
                key = i.attributes["key"]
                if (self.pump_configuration[key]["value"] ==
                        i.attributes["value"]):
                    i.name = "%s %s" % (i.attributes["name"], "*")
                else:
                    i.name = i.attributes["name"]
            elif (i.type == "menu"):
                self.selectConfigurations(i)

    def prepareForRender(self, menu):
        self.filterDrinks(menu)
        self.selectConfigurations(menu)
        return True

    def menuItemClicked(self, menuItem):
        if (menuItem.type == "drink"):
            if self.make_drink:
                self.makeDrink(menuItem.name,
                               menuItem.attributes["ingredients"])
                self.make_drink = False
            return True
        elif (menuItem.type == "pump_selection"):
            self.pump_configuration[menuItem.attributes["key"]][
                "value"] = menuItem.attributes["value"]
            Bartender.writePumpConfiguration(self.pump_configuration)
            return True
        elif (menuItem.type == "clean"):
            if self.make_drink:
                self.clean()
                self.make_drink = False
            return True
        return False

    def changeConfiguration(self, pumps):
        # Change configuration of every pump
        for i in range(1, 7):
            self.pump_configuration["pump_" + str(i)]["value"] = pumps[i - 1]

        Bartender.writePumpConfiguration(self.pump_configuration)

    def clean(self):
        waitTime = 30
        pumpProcesses = []

        # cancel any button presses while the drink is being made
        # self.stopInterrupts()
        self.running = True

        for pump in self.pump_configuration.keys():
            pump_p = threading.Thread(target=self.pour,
                                      args=(
                                          self.pump_configuration[pump]["pin"],
                                          waitTime,
                                      ))
            pumpProcesses.append(pump_p)

        disp_process = threading.Thread(target=self.progressBar,
                                        args=(waitTime, ))
        pumpProcesses.append(disp_process)

        # start the pump threads
        for process in pumpProcesses:
            process.start()

        # wait for threads to finish
        for process in pumpProcesses:
            process.join()

        # sleep for a couple seconds to make sure the interrupts don't get triggered
        time.sleep(2)

        # reenable interrupts
        # self.startInterrupts()
        self.running = False
        self.make_drink = True

        self.menuContext.showMenu()

    def displayMenuItem(self, menuItem):
        #Clear display
        self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),
                            outline=0,
                            fill=0)
        self.draw.text((20, 10), menuItem.name, font=self.font, fill=255)
        self.disp.image(self.image)
        self.disp.display()

    def cycleLights(self):
        t = threading.currentThread()
        head = 0  # Index of first 'on' pixel
        tail = -10  # Index of last 'off' pixel
        color = 0xFF0000  # 'On' color (starts red)

        while getattr(t, "do_run", True):
            self.strip.setPixelColor(head, color)  # Turn on 'head' pixel
            self.strip.setPixelColor(tail, 0)  # Turn off 'tail'
            self.strip.show()  # Refresh strip
            time.sleep(1.0 / 50)  # Pause 20 milliseconds (~50 fps)

            head += 1  # Advance head position
            if (head >= self.numpixels):  # Off end of strip?
                head = 0  # Reset to start
                color >>= 8  # Red->green->blue->black
                if (color == 0): color = 0xFF0000  # If black, reset to red

            tail += 1  # Advance tail position
            if (tail >= self.numpixels): tail = 0  # Off end? Reset

    def lightsEndingSequence(self):
        # make lights green
        for i in range(0, self.numpixels):
            self.strip.setPixelColor(i, 0xFF0000)
        self.strip.show()

        time.sleep(5)

        # turn lights off
        for i in range(0, self.numpixels):
            self.strip.setPixelColor(i, 0)
        self.strip.show()

    def pour(self, pin, waitTime):
        GPIO.output(pin, GPIO.LOW)
        time.sleep(waitTime)
        GPIO.output(pin, GPIO.HIGH)

    def progressBar(self, waitTime):
        interval = waitTime / 116.3

        for x in range(1, 101):
            # Clear display
            self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),
                                outline=0,
                                fill=0)
            #self.draw.text((55,20), str(x) + '%', font = self.font, fill=255)
            self.updateProgressBar(x, y=10)
            self.disp.image(self.image)
            self.disp.display()
            time.sleep(interval)
        # 	# self.disp.clear()
        # 	# self.disp.display()

        # self.image = Image.open('happycat_oled_32.ppm').convert('1')

        # self.disp.image(self.image)
        # self.disp.display()

    def makeDrink(self, drink, ingredients):
        if self.running:
            return

        # cancel any button presses while the drink is being made
        # self.stopInterrupts()
        print('Making a ' + drink)
        self.running = True

        # launch a thread to control lighting
        lightsThread = threading.Thread(target=self.cycleLights)
        lightsThread.start()

        # Make a list for each potential time

        maxTime = 0
        pumpProcesses = []
        for ing in ingredients.keys():
            for pump in self.pump_configuration.keys():
                if ing == self.pump_configuration[pump]["value"]:
                    waitTime = ingredients[ing] * FLOW_RATE
                    if (waitTime > maxTime):
                        maxTime = waitTime
                    pump_p = threading.Thread(
                        target=self.pour,
                        args=(self.pump_configuration[pump]["pin"], waitTime))
                    pumpProcesses.append(pump_p)

        disp_process = threading.Thread(target=self.progressBar,
                                        args=(maxTime, ))
        pumpProcesses.append(disp_process)

        # start the pump threads
        for process in pumpProcesses:
            process.start()

        # wait for threads to finish
        for process in pumpProcesses:
            process.join()

        # stop the light thread
        lightsThread.do_run = False
        lightsThread.join()

        # show the ending sequence lights
        self.lightsEndingSequence()

        # reenable interrupts
        # sleep for a couple seconds to make sure the interrupts don't get triggered
        time.sleep(2)
        # self.startInterrupts()
        self.running = False
        print('Finished making ' + drink)
        self.make_drink = True

        # show the main menu
        self.menuContext.showMenu()

    def left_btn(self, ctx):
        if not self.running:
            self.menuContext.advance()

    def right_btn(self, ctx):
        if not self.running:
            self.menuContext.select()

    def rotary_on_change(self, ctx):
        if not self.running:
            if GPIO.input(self.dt):
                self.menuContext.retreat()
            else:
                self.menuContext.advance()

    def get_ingredients_time(self, drink):
        # Get the ingredients for the specified drink
        found = False
        while (found == False):
            currmen = self.menuContext.currentMenu.getSelection()
            if (currmen.name == drink):
                ingredients = currmen.attributes["ingredients"]
                self.make_drink = False
                found = True
            else:
                self.menuContext.currentMenu.nextSelection()

        # Get the drink making time
        maxTime = 0
        for ing in ingredients.keys():
            for pump in self.pump_configuration.keys():
                if ing == self.pump_configuration[pump]["value"]:
                    waitTime = ingredients[ing] * FLOW_RATE
                    if (waitTime > maxTime):
                        maxTime = waitTime

        # Return making time and ingredients for drink
        return ingredients, maxTime

    def updateProgressBar(self, percent, x=15, y=10):

        height = 10
        width = self.screen_width - 2 * x

        for w in range(0, width):
            self.draw.point((w + x, y), fill=255)
            self.draw.point((w + x, y + height), fill=255)
        for h in range(0, height):
            self.draw.point((x, h + y), fill=255)
            self.draw.point((self.screen_width - x, h + y), fill=255)
            for p in range(0, percent):
                p_loc = int(p / 100.0 * width)
                self.draw.point((x + p_loc, h + y), fill=255)
                self.draw.text((55, 20),
                               str(percent) + '%',
                               font=self.font,
                               fill=255)
                #self.disp.image(self.image)
            #self.disp.display()

    def endprogram(self):
        global stopprogram

        stopprogram = True

        # Goodbye message
        self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),
                            outline=0,
                            fill=0)
        self.draw.text((25, 10), "Goodbye...", font=self.font, fill=255)
        self.disp.image(self.image)
        self.disp.display()
        time.sleep(3)

        self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),
                            outline=0,
                            fill=0)
        self.draw.text((15, 10), "Have a great day!", font=self.font, fill=255)
        self.disp.image(self.image)
        self.disp.display()

        time.sleep(3)
        self.disp.clear()
        self.disp.display()

    def run(self):
        self.startInterrupts()
        # main loop
        try:
            while True:
                if stopprogram:
                    return
                # self.imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
                # self.imap_server.login(USERNAME, PASSWORD)
                # self.imap_server.select('INBOX')
                # mail_list = self.check_email()
                # if mail_list and not self.running:
                # 	self.voice_command(mail_list)
                time.sleep(0.1)

        except KeyboardInterrupt:
            GPIO.cleanup()  # clean up GPIO on CTRL+C exit
            sys.exit(0)

        GPIO.cleanup()  # clean up GPIO on normal exit

        traceback.print_exc()
Пример #44
0
while True:                              # Loop forever

	# rotate color through rainbow
	if (color & 0xFF0000) and not (color & 0x0000FF):
		color = color - 0x010000 # decrement red
		color = color + 0x000100 # increment green
	elif(color & 0x00FF00):
		color = color - 0x000100 # decrement green
		color = color + 0x000001 # increment blue
	elif(color & 0x0000FF):
		color = color - 0x000001 # decrement blue
		color = color + 0x010000 # increment red

	# Turn off old dot
	strip.setPixelColor(dot, 0)

	# Calculate wave based on time
	now = time.time()
	angle = angle_mult * (now - start)
	amplitude = math.cos(now/mod_period)
	wave = amplitude * math.cos(angle)
	#dot = int(math.floor(((wave + 1.0)*(numpixels-1) + 1.0)/2.0))
	#dot = int(((wave + 1.0)*(numpixels-1)/2.0 + 1.0)//2.0 + numpixels/2)
	dot = int(((wave + 1.0)*(numpixels-1) + 1.0)//2.0)

	# Turn on new dot
	strip.setPixelColor(dot, color)
	strip.show()                     # Refresh strip

	#time.sleep(1.0 / 50)             # Pause 20 milliseconds (~50 fps)
Пример #45
0
strip.begin()  # Initialize pins for output

# Load image in RGB format and get dimensions:
print "Loading..."
img = Image.open(filename).convert("RGB")
pixels = img.load()
width = img.size[0]
height = img.size[1]
print "%dx%d pixels" % img.size

if (height > strip.numPixels()): height = strip.numPixels()

# Calculate gamma correction table, makes mid-range colors look 'right':
gamma = bytearray(256)
for i in range(256):
    gamma[i] = int(pow(float(i) / 255.0, 2.7) * 255.0 + 0.5)

print "Displaying..."
while True:  # Loop forever

    for x in range(width):  # For each column of image...
        for y in range(height):  # For each pixel in column...
            value = pixels[x, y]  # Read pixel in image
            strip.setPixelColor(
                y,  # Set pixel in strip
                gamma[value[0]],  # Gamma-corrected red
                gamma[value[1]],  # Gamma-corrected green
                gamma[value[2]])  # Gamma-corrected blue
        strip.show()  # Refresh LED strip
# Runs 10 LEDs at a time along strip, cycling through red, green and blue.
# This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel.

head = 10  # Index of first 'on' pixel
tail = 0  # Index of last 'off' pixel
r = 0xFF
g = 0x00
b = 0x00
color = r * 0x010000 + g * 0x000100 + b * 0x000001
# 'On' color (starts red)
step = -0x01

while True:  # Loop forever
    for i in range(31):
        strip.setPixelColor(i, color)  # Turn on 'head' pixel
    strip.show()  # Refresh strip
    time.sleep(1.0 / 100)  # Pause 20 milliseconds (~50 fps)

    #	head += 1                        # Advance head position
    #	if(head >= numpixels):           # Off end of strip?
    #		head    = 0              # Reset to start
    #		color >>= 8              # Red->green->blue->black
    #		if(color == 0): color = 0xFF0000 # If black, reset to red
    #
    #	tail += 1                        # Advance tail position
    #	if(tail >= numpixels): tail = 0  # Off end? Reset

    r = r + step
    g = g - step
    color = r * 0x010000 + g * 0x000100 + b * 0x000001
Пример #47
0
					pos = abs(mousepos) * scale
					if pos > 1.0: break
					lightpaint.dither(ledBuf, pos)
					strip.show(ledBuf)

			if btn() != pin_go: # Button released?
				strip.show(clearBuf)

		elif b == 2:
			# Decrease paint duration
			if speed_pixel > 0:
				speed_pixel -= 1
				duration = (min_time + time_range *
				  speed_pixel / (num_leds - 1))
			strip.setPixelColor(speed_pixel, 0x000080)
			strip.show()
			startTime = time.time()
			while (btn() == 2 and ((time.time() - startTime) <
			  rep_time)): continue
			strip.clear()
			strip.show()
		elif b == 3:
			# Increase paint duration (up to 10 sec maximum)
			if speed_pixel < num_leds - 1:
				speed_pixel += 1
				duration = (min_time + time_range *
				  speed_pixel / (num_leds - 1))
			strip.setPixelColor(speed_pixel, 0x000080)
			strip.show()
			startTime = time.time()
Пример #48
0
			print hue
			print sat
			print val
			print ""
			
			h = scale(hue, 0, 255, 0, 1)
			s = scale(sat, 0, 255, 0, 1)
			v = scale(val, 0, 255, 0, 1)
			
			r,g,b = colorsys.hsv_to_rgb(h,s,v)
			
			
			print r
			print g
			print b
			print ""
			
			r = int(scale(r, 0, 1, 0, 255))
			g = int(scale(g, 0, 1, 0, 255))
			b = int(scale(b, 0, 1, 0, 255))
			
			print r
			print g
			print b
			
			color = strip.Color(g,r,b)
			
			for i in range(numpixels):
				strip.setPixelColor(i, color)
			strip.show()
Пример #49
0
#The following is an example LED program that flashes the LEDs in
#random colors.

import time
from dotstar import Adafruit_DotStar
import random

numpixels = 2  # Number of LEDs in strip
strip = Adafruit_DotStar(numpixels, 12000000)

strip.begin()  # Initialize pins for output
strip.setBrightness(64)  # Limit brightness to ~1/4 duty cycle

head = 0  # First LED in the ball
tail = 1  # Second LED int the ball
head_color = 0xFF0000  # Color of first LED
tail_color = 0x00FF00  # Color of second LED

while True:
    strip.setPixelColor(head, head_color)
    strip.setPixelColor(tail, tail_color)
    strip.show()

    #Delay for a time before the colors switch
    time.sleep(0.4)

    #scroll the color across the two leds in the ball
    #generate a new random color each time (from red to white)
    tail_color = head_color
    head_color = random.randint(255, 16777215)
Пример #50
0
	else:
		# Time to switch completely to the new kaleidoscope
		ks_map = ks_new_map
		ks_old_n = ks_new_n
		ks_old_map = ks_new_map
		ks_new_n = random.randrange(len(ks.maps))
		ks_new_map = ks.maps[ks_new_n]
		ks_fade_start = now + ks.HoldTime
		ks_fade_end = ks_fade_start + ks.FadeTime
		print "ks =", ks.names[ks_old_n], " -> ", ks.names[ks_new_n]
	# Apply the Kaleidoscope.
	ks_screen = [screen[ks_map[p]] for p in range(n_pixels)]

	# Set up all pixels for draw at beginning of next cycle.
	for p in range(n_pixels):
		strip.setPixelColor(p, cm_interp(cm_map,ks_screen[p]))

	# Strobe.
	# Fade to black if volume is low.
	#st_brightness = min(brightness,(osc_max-osc_min)//2)
	st_brightness = min(brightness,(osc_max-osc_min)*brightness//MAX_BRIGHTNESS)
	#print 'st_brightness =', st_brightness
	now = time.time()
	# Turn strobing on or off?
	if (st_enabled):
		if (now > st_end):
			# Turn strobing off.
			st_enabled = False
			print 'st = off'
			st_start = now + st_DownTime
	else:
Пример #51
0
# Load image in RGB format and get dimensions:
print "Loading..."
img = Image.open(filename).convert("RGB")
pixels = img.load()
width = img.size[0]
height = img.size[1]
print "%dx%d pixels" % img.size

if height > strip.numPixels():
    height = strip.numPixels()

# Calculate gamma correction table, makes mid-range colors look 'right':
gamma = bytearray(256)
for i in range(256):
    gamma[i] = int(pow(float(i) / 255.0, 2.7) * 255.0 + 0.5)

print "Displaying..."
while True:  # Loop forever

    for x in range(width):  # For each column of image...
        for y in range(height):  # For each pixel in column...
            value = pixels[x, y]  # Read pixel in image
            strip.setPixelColor(
                y,  # Set pixel in strip
                gamma[value[0]],  # Gamma-corrected red
                gamma[value[1]],  # Gamma-corrected green
                gamma[value[2]],
            )  # Gamma-corrected blue
        strip.show()  # Refresh LED strip