Example #1
0
wlan.connect('VM910566-2G', 'K@ramb0lsk!') # connect to an AP
# wlan.config('mac')      # get the interface's MAC address
# wlan.ifconfig()         # get the interface's IP/netmask/gw/DNS addresses

# ap = network.WLAN(network.AP_IF) # create access-point interface
# ap.config(essid='ESP-AP') # set the ESSID of the access point
# # ap.config(max_clients=10) # set how many clients can connect to the network
# ap.active(True)         # activate the interface

# time.sleep(1)

###############################

import machine, neopixel

nph = neopixel.NeoPixel(machine.Pin(12), 24)
npm = neopixel.NeoPixel(machine.Pin(14), 24)


#########
clMin = (0,2,0)
clMout = (0,0,0)

def onMin(m):
    hin = round(m * 24 / 60)
    for i in range(hin):
        npm[i] = clMin

def onMout(m):
    hin = round(m * 24 / 60)
    for i in range(hin, 24):
Example #2
0
#!/usr/bin/env python3
import random
import board
import neopixel
import time

pixel_pin = board.D18

num_pixels = 110

ORDER = neopixel.GRB

pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER)
colors = []
offset = 0.0


def wheel(pos):
    if(pos < 2*255/5):
        return (0,32,0)
    if(pos < 4*255/5):
        return (186, 0, 0)
    return(255, 128, 32)
oldcolors=[]
for i in range(0,num_pixels-1):
	pixels[i]=(0,0,0)
	oldcolors.append((0,0,0))
pixels.show()
fadesteps=15.0
while(True):
	for i in range(0,num_pixels-1):
Example #3
0
button1 = AnalogIn(board.D4)
button2 = AnalogIn(board.D1)
button3 = AnalogIn(board.D2)
#play a sound on startup
#cpx.play_file("Coin.wav")

#set our middle pixel strip (the 10 on the CircuitPlayground)
#middle_pixels = cpx.pixels
#middle_pixels.brightness = .2

#define the number of pixels each strip will have
num_pixels = 10

#set up the pixel strip for the 4 players.
pixels = neopixel.NeoPixel(board.D0, (4 * num_pixels),
                           brightness=0.1,
                           auto_write=False)
pixels.show()
print(pixels)
#load the buttons to an array, one for each player
buttons = [button0, button1, button2, button3]

#predefine some colors
RED = (100, 0, 0)
GREEN = (0, 100, 0)
WHITE = (100, 100, 100)
BLACK = (0, 0, 0)

pixels[1] = BLACK
pixels.show()
Example #4
0
import machine, time, os, neopixel
numpixels = 60
np = neopixel.NeoPixel(machine.Pin(4), numpixels)

def demo():
    # fade in/out

    for i in range(0, 4 * 256, 8):
        for j in range(numpixels):
            if (i // 256) % 2 == 0:
                val = i & 0xff
            else:
                val = 255 - (i & 0xff)
            np[j] = (val, 0, 0)
        time.sleep(0.01)
        np.write()

demo()
while (True):
    demo()
Example #5
0
# Metro IO demo
# Welcome to CircuitPython 2.2.0 :)

import board
import time
import neopixel
from digitalio import DigitalInOut, Direction, Pull
from analogio import AnalogIn
import audioio
import touchio
import simpleio

# One pixel connected internally!
dot = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)

# Built in red LED
led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT

# Digital input with pullup on D2, D3, and D4
buttons = []
for p in [board.D2, board.D3, board.D4]:
    button = DigitalInOut(p)
    button.direction = Direction.INPUT
    button.pull = Pull.UP
    buttons.append(button)

######################### HELPERS ##############################
##

Example #6
0
from touchio import TouchIn
import adafruit_dotstar as dotstar
import board
import neopixel
from hoodie import Hoodie
import time

jewel = neopixel.NeoPixel(board.A1, 7, brightness=0.1, auto_write=True)
dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)

touchL = TouchIn(board.A0)
touchR = TouchIn(board.A2)
touchL.threshold = touchL.raw_value + 200
touchR.threshold = touchR.raw_value + 200

hoodie = Hoodie(jewel)

while True:
    # print(touchL.raw_value)

    if touchL.value and touchR.value:
        print("touched both")
        hoodie.handleColor(hoodie.HOP)

    elif touchL.value:
        print("touched left")
        dot[0] = [0, 255, 0]
        hoodie.handleColor(hoodie.WHEEL)

    elif touchR.value:
        print("touched right")
Example #7
0
import board
import neopixel
import time
import argparse
import random
import numpy as np
import colorsys
import random
import colorsys
import operator

from rpi_ws281x import *

pixelOutput = neopixel.NeoPixel(board.D18, 209, auto_write=False)

# maps
BackwardEdgeMaps = [0, 7, 14, 21, 28]
ForwardEdgeMaps = [6, 13, 20, 27, 34]
pixelBuffer = [(0, 0, 0)] * 7 * 30
objectList = []

Junction = {
    6: [7, 99],
    7: [99, 6],
    13: [14, 99],
    14: [99, 13],
    20: [21, 99],
    21: [99, 20],
    27: [28, 99],
    28: [99, 27],
    34: [0, 99],
Example #8
0
from microbit import *
import microbit
import superbit
import neopixel

k = 0
flag = 2
display.show(Image.HAPPY)
np = neopixel.NeoPixel(pin12, 4)


def limit_change():
    global flag
    if microbit.button_a.is_pressed():
        superbit.motor_control(superbit.M1, -255, 0)
        flag = 0
        display.show(Image.ARROW_S)

    elif microbit.button_b.is_pressed():
        superbit.motor_control(superbit.M1, 255, 0)
        flag = 1
        display.show(Image.ARROW_N)


while True:
    limit_change()
    if flag == 1:
        while k < 255:
            np[0] = (k, 0, 0)
            np[1] = (k, 0, 0)
            np[2] = (k, 0, 0)
Example #9
0
import time
import board
from adafruit_pyportal import PyPortal
from adafruit_button import Button
import neopixel
import analogio

# Set the background color
BACKGROUND_COLOR = 0x443355

# Set the NeoPixel brightness
BRIGHTNESS = 0.3

light_sensor = analogio.AnalogIn(board.LIGHT)

strip_1 = neopixel.NeoPixel(board.D4, 30, brightness=BRIGHTNESS)
strip_2 = neopixel.NeoPixel(board.D3, 30, brightness=BRIGHTNESS)

# Turn off NeoPixels to start
strip_1.fill(0)
strip_2.fill(0)

# Setup PyPortal without networking
pyportal = PyPortal(default_bg=BACKGROUND_COLOR)

# Button colors
RED = (255, 0, 0)
ORANGE = (255, 34, 0)
YELLOW = (255, 170, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
Example #10
0
class CameraInterface(Ui_Form, Camera):

    config = configparser.ConfigParser()
    pixels = neopixel.NeoPixel(board.D18, 8, brightness=0.2)

    def __init__(self, title=""):
        self.title = title
        cv2.namedWindow('capture', cv2.WINDOW_NORMAL)
        cv2.resizeWindow('capture', int(round(1920 / 2)), int(round(1080 / 2)))
        cv2.setMouseCallback('capture', self.mouseCallback)
        self.picture = None
        self.img_index = 1

    def mouseCallback(self, e, x, y, f, p):
        if e == cv2.EVENT_LBUTTONDOWN:
            self.x1y1 = (x, y)
        elif e == cv2.EVENT_LBUTTONUP:
            self.x2y2 = (x, y)
            if self.picture is not None and self.x1y1 != self.x2y2:
                self.picture = self.picture[self.x1y1[1]:self.x2y2[1],
                                            self.x1y1[0]:self.x2y2[0]]
                self.resizeWindow(int(self.picture.shape[1]),
                                  int(self.picture.shape[0]), True)
                cv2.imshow('capture', self.picture)

    def setupUi(self, MainWindow):
        super().setupUi(MainWindow)
        self.loadConfig()
        self.preview()
        MainWindow.setWindowTitle(self.title)
        self.brightnessSliderLabel.setText(str(self.brightnessSlider.value()))
        self.contrastSliderLabel.setText(str(self.contrastSlider.value()))
        self.saturationSliderLabel.setText(str(self.saturationSlider.value()))
        self.shutterspeedSliderLabel.setText(
            str(self.shutterspeedSlider.value()))
        self.isoSliderLabel.setText(str(self.isoSlider.value()))
        self.blueSliderLabel.setText(str(int(self.blueSlider.value()) / 100))
        self.redSliderLabel.setText(str(int(self.redSlider.value()) / 100))
        try:
            self.ipaddrLabel.setText(
                os.popen('ip addr show wlan0').read().split('inet ')[1].split(
                    '/')[0])
        except:
            self.ipaddrLabel.setText('xx.xx.xxx.xxx')
        self.resolutionBox.currentIndexChanged.connect(
            lambda: self.objValueChange(self.resolutionBox, 'resolution'))
        self.rotationBox.currentIndexChanged.connect(
            lambda: self.objValueChange(self.rotationBox, 'rotation'))
        self.redSlider.valueChanged.connect(lambda: self.objValueChange(
            self.redSlider, self.redSliderLabel, 'red_color'))
        self.blueSlider.valueChanged.connect(lambda: self.objValueChange(
            self.blueSlider, self.blueSliderLabel, 'blue_color'))
        self.isoSlider.valueChanged.connect(lambda: self.objValueChange(
            self.isoSlider, self.isoSliderLabel, 'iso'))
        self.brightnessSlider.valueChanged.connect(lambda: self.objValueChange(
            self.brightnessSlider, self.brightnessSliderLabel, 'brightness'))
        self.contrastSlider.valueChanged.connect(lambda: self.objValueChange(
            self.contrastSlider, self.contrastSliderLabel, 'contrast'))
        self.saturationSlider.valueChanged.connect(lambda: self.objValueChange(
            self.saturationSlider, self.saturationSliderLabel, 'saturation'))
        self.shutterspeedSlider.valueChanged.connect(
            lambda: self.objValueChange(self.shutterspeedSlider, self.
                                        shutterspeedSliderLabel,
                                        'shutter_speed'))
        self.saveSettingButton.clicked.connect(self.saveConfig)
        self.previewButton.clicked.connect(lambda: self.preview())
        self.captureButton.clicked.connect(lambda: self.captureEvent())
        self.resetSettingButton.clicked.connect(lambda: self.resetSetting())
        self.neoBrightSlider.valueChanged.connect(lambda: self.objValueChange(
            self.neoBrightSlider, self.neoBrightSliderLabel,
            'neopixel_brigntness'))
        self.neoBSlider.valueChanged.connect(lambda: self.objValueChange(
            self.neoBSlider, self.neoBSliderLabel, 'neopixel_blue'))
        self.neoGSlider.valueChanged.connect(lambda: self.objValueChange(
            self.neoGSlider, self.neoGSliderLabel, 'neopixel_green'))
        self.neoRSlider.valueChanged.connect(lambda: self.objValueChange(
            self.neoRSlider, self.neoRSliderLabel, 'neopixel_red'))
        self.saveImageButton.clicked.connect(self.savePicture)
        self.colorCvtButton.clicked.connect(self.colorConverter)
        self.histogramButton.clicked.connect(self.histogram)
        MainWindow.keyPressEvent = self.pressEvent

    def objValueChange(self, obj, label, conf=None):
        if conf is not None:
            self.config['configs'][conf] = str(obj.value())
            label.setText(self.config['configs'][conf])
        if conf == 'iso':
            self.camera.iso = obj.value()
        elif conf == 'brightness':
            self.camera.brightness = obj.value()
        elif conf == 'contrast':
            self.camera.contrast = obj.value()
        elif conf == 'saturation':
            self.camera.saturation = obj.value()
        elif conf == 'shutter_speed':
            self.camera.shutter_speed = obj.value()
        elif conf == 'red_color':
            self.config['configs']['red_color'] = str(
                round(obj.value() * 0.01, 2))
            label.setText(self.config['configs']['red_color'])
            self.camera.awb_gains = (float(
                round(self.redSlider.value() * 0.01,
                      2)), float(round(self.blueSlider.value() * 0.01, 2)))
        elif conf == 'blue_color':
            self.config['configs']['blue_color'] = str(
                round(obj.value() * 0.01, 2))
            label.setText(self.config['configs']['blue_color'])
            self.camera.awb_gains = (float(
                round(self.redSlider.value() * 0.01,
                      2)), float(round(self.blueSlider.value() * 0.01, 2)))
        elif label == 'resolution':
            self.config['configs'][
                label] = self.camera.resolution = obj.currentText()
            if str(self.camera.resolution) == '1920x1080':
                self.use_video_port = True
            else:
                self.use_video_port = False
            self.config['configs']['use_video_port'] = str(self.use_video_port)
            w, h = self.config['configs'][label].split('x')
            self.resizeWindow(int(w), int(h))
        elif label == 'rotation':
            self.config['configs'][label] = str(obj.currentText())
            self.camera.rotation = int(self.config['configs'][label])
        elif conf == 'neopixel_brigntness':
            self.config['configs']['neopixel_brigntness'] = str(
                round(obj.value() / 10, 1))
            label.setText(self.config['configs']['neopixel_brigntness'])
            self.pixels.brightness = float(
                self.config['configs']['neopixel_brigntness'])
            self.pixels.show()
        elif conf in ['neopixel_blue', 'neopixel_green', 'neopixel_red']:
            self.config['configs']['neopixel_blue'] = str(
                self.neoBSlider.value())
            self.config['configs']['neopixel_green'] = str(
                self.neoGSlider.value())
            self.config['configs']['neopixel_red'] = str(
                self.neoRSlider.value())
            label.setText(str(obj.value()))
            self.pixels.fill((self.neoRSlider.value(), self.neoGSlider.value(),
                              self.neoBSlider.value()))
            self.pixels.show()

    def saveConfig(self):
        print('saveConfig')
        with open(self.path + '/camera.ini', 'w') as configfile:
            self.config.write(configfile)

    def loadConfig(self):
        if os.path.isfile(self.path + '/camera.ini'):
            self.config.read(self.path + '/camera.ini')
            self.resolutionBox.setCurrentIndex(
                self.resolutionBox.findText(
                    self.config['configs']['resolution'],
                    QtCore.Qt.MatchFixedString))
            self.rotationBox.setCurrentIndex(
                self.rotationBox.findText(self.config['configs']['rotation'],
                                          QtCore.Qt.MatchFixedString))
            self.brightnessSliderLabel.setText(
                self.config['configs']['brightness'])
            self.contrastSliderLabel.setText(
                self.config['configs']['contrast'])
            self.saturationSliderLabel.setText(
                self.config['configs']['saturation'])
            self.shutterspeedSliderLabel.setText(
                self.config['configs']['shutter_speed'])
            self.isoSliderLabel.setText(self.config['configs']['iso'])
            self.redSliderLabel.setText(self.config['configs']['red_color'])
            self.blueSliderLabel.setText(self.config['configs']['blue_color'])
            self.brightnessSlider.setValue(
                int(self.config['configs']['brightness']))
            self.contrastSlider.setValue(
                int(self.config['configs']['contrast']))
            self.saturationSlider.setValue(
                int(self.config['configs']['saturation']))
            self.shutterspeedSlider.setValue(
                int(self.config['configs']['shutter_speed']))
            self.isoSlider.setValue(int(self.config['configs']['iso']))
            self.blueSlider.setValue(
                int(float(self.config['configs']['blue_color']) * 100))
            self.redSlider.setValue(
                int(float(self.config['configs']['red_color']) * 100))
            self.neoBrightSlider.setValue(
                int(float(self.config['configs']['neopixel_brigntness']) * 10))
            self.neoBSlider.setValue(
                int(self.config['configs']['neopixel_blue']))
            self.neoGSlider.setValue(
                int(self.config['configs']['neopixel_green']))
            self.neoRSlider.setValue(
                int(self.config['configs']['neopixel_red']))
            self.neoBrightSliderLabel.setText(
                self.config['configs']['neopixel_brigntness'])
            self.neoBSliderLabel.setText(
                self.config['configs']['neopixel_blue'])
            self.neoGSliderLabel.setText(
                self.config['configs']['neopixel_green'])
            self.neoRSliderLabel.setText(
                self.config['configs']['neopixel_red'])
            self.use_video_port = self.config['configs']['use_video_port']
        else:
            self.config['configs'] = {
                'resolution':
                str(self.resolutionBox.currentText()),
                'rotation':
                self.rotationBox.currentText(),
                'red_color':
                str(int(self.redSlider.value()) / 100),
                'blue_color':
                str(int(self.blueSlider.value()) / 100),
                'iso':
                self.isoSlider.value(),
                'brightness':
                self.brightnessSlider.value(),
                'contrast':
                self.contrastSlider.value(),
                'saturation':
                self.saturationSlider.value(),
                'shutter_speed':
                self.shutterspeedSlider.value(),
                'neopixel_blue':
                self.neoBSlider.value(),
                'neopixel_green':
                self.neoGSlider.value(),
                'neopixel_red':
                self.neoRSlider.value(),
                'neopixel_brigntness':
                str(round(self.neoBrightSlider.value() / 10, 1)),
                'use_video_port':
                False
            }

        self.backup_config = {}
        for k, v in self.config['configs'].items():
            self.backup_config[k] = v

        super().setup(self.config['configs']['resolution'])
        self.camera.rotation = self.config['configs']['rotation']
        self.camera.awb_gains = (float(self.config['configs']['red_color']),
                                 float(self.config['configs']['blue_color']))
        self.camera.iso = int(self.config['configs']['iso'])
        self.camera.brightness = int(self.config['configs']['brightness'])
        self.camera.contrast = int(self.config['configs']['contrast'])
        self.camera.saturation = int(self.config['configs']['saturation'])
        self.camera.shutter_speed = int(
            self.config['configs']['shutter_speed'])
        if self.config['configs']['resolution'] == '1920x1080':
            self.use_video_port = True
        else:
            self.use_video_port = False
        sleep(1)

        color = (int(self.config['configs']['neopixel_red']),
                 int(self.config['configs']['neopixel_green']),
                 int(self.config['configs']['neopixel_blue']))
        self.pixels.fill(color)
        self.pixels.brightness = float(
            self.config['configs']['neopixel_brigntness'])
        self.pixels.show()

    def resetSetting(self):
        self.resolutionBox.setCurrentIndex(
            self.resolutionBox.findText(self.backup_config['resolution'],
                                        QtCore.Qt.MatchFixedString))
        self.rotationBox.setCurrentIndex(
            self.rotationBox.findText(self.backup_config['rotation'],
                                      QtCore.Qt.MatchFixedString))
        self.brightnessSliderLabel.setText(self.backup_config['brightness'])
        self.contrastSliderLabel.setText(self.backup_config['contrast'])
        self.saturationSliderLabel.setText(self.backup_config['saturation'])
        self.shutterspeedSliderLabel.setText(
            self.backup_config['shutter_speed'])
        self.isoSliderLabel.setText(self.backup_config['iso'])
        self.redSliderLabel.setText(self.backup_config['red_color'])
        self.blueSliderLabel.setText(self.backup_config['blue_color'])
        self.brightnessSlider.setValue(int(self.backup_config['brightness']))
        self.contrastSlider.setValue(int(self.backup_config['contrast']))
        self.saturationSlider.setValue(int(self.backup_config['saturation']))
        self.shutterspeedSlider.setValue(
            int(self.backup_config['shutter_speed']))
        self.isoSlider.setValue(int(self.backup_config['iso']))
        self.blueSlider.setValue(
            int(float(self.backup_config['blue_color']) * 100))
        self.redSlider.setValue(
            int(float(self.backup_config['red_color']) * 100))

        self.config['configs'] = {
            'resolution': self.resolutionBox.currentText(),
            'rotation': self.rotationBox.currentText(),
            'red_color': str(int(self.redSlider.value()) / 100),
            'blue_color': str(int(self.blueSlider.value()) / 100),
            'iso': self.isoSlider.value(),
            'brightness': self.brightnessSlider.value(),
            'contrast': self.contrastSlider.value(),
            'saturation': self.saturationSlider.value(),
            'shutter_speed': self.shutterspeedSlider.value()
        }

    def pressEvent(self, event):
        # print('press', event.key())
        if event.key() == 16777275:
            self.preview()

    def resizeWindow(self, w, h, mode=False):
        if mode:
            cv2.resizeWindow('capture', int(round(int(w))), int(round(int(h))))
        else:
            cv2.resizeWindow('capture', int(round(int(w) / 2.5)),
                             int(round(int(h) / 2.5)))

    def captureEvent(self):
        self.picture = self.capture()
        self.resizeWindow(int(self.picture.shape[1]),
                          int(self.picture.shape[0]))
        cv2.imshow('capture', self.picture)

    def colorConverter(self):
        self.picture = cv2.cvtColor(self.picture, cv2.COLOR_BGR2GRAY)
        cv2.imshow('capture', self.picture)

    def histogram(self):
        if len(self.picture.shape) == 2:
            hist = self.picture.ravel()
            plt.hist(hist, 256, [0, 256])
            plt.show()
        else:
            for i, col in enumerate(('b', 'g', 'r')):
                histr = cv2.calcHist([self.picture], [i], None, [256],
                                     [0, 256])
                plt.plot(histr, color=col)
                plt.xlim([0, 256])
            plt.show()

    def savePicture(self):
        cv2.imwrite(self.path + '/pictures/' + str(self.img_index) + '.bmp',
                    self.picture)
        self.img_index += 1
Example #11
0
# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time

import analogio
import board
import neopixel

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0)
light = analogio.AnalogIn(board.LIGHT)

# Turn only pixel #1 green
pixels[1] = (0, 255, 0)

# How many light readings per sample
NUM_OVERSAMPLE = 10
# How many samples we take to calculate 'average'
NUM_SAMPLES = 20
samples = [0] * NUM_SAMPLES

while True:
    for i in range(NUM_SAMPLES):
        # Take NUM_OVERSAMPLE number of readings really fast
        oversample = 0
        for s in range(NUM_OVERSAMPLE):
            oversample += float(light.value)
        # and save the average from the oversamples
        samples[i] = oversample / NUM_OVERSAMPLE  # Find the average
Example #12
0
Control led lights in model house based on MQTT messages
"""
import machine
import neopixel
import network
import time
import uos

from umqtt.simple import MQTTClient

topic = 'model'
broker = '192.168.1.117' #'jarvis'
client= MQTTClient('model', broker)

np = neopixel.NeoPixel(machine.Pin(4), 6)


def cycle(iterations, speed):
    for i in range(0, iterations):
        for i in range(0, np.n):
            np[(i-1) % np.n] = (0, 0, 0)
            np[i] = (10, 10, 10)
            np.write()
            time.sleep_ms(speed)


def diagnostic():

    n = np.n
    print("Count = ", n)
Example #13
0
# SPDX-FileCopyrightText: 2017 Mikey Sklar for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time

import board
import neopixel
from digitalio import DigitalInOut, Direction

pix_pin = board.D1
num_pix = 5

led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT

strip = neopixel.NeoPixel(pix_pin, num_pix, brightness=1, auto_write=True)


def color_wipe(color, wait):
    for j in range(len(strip)):
        strip[j] = (color)
        time.sleep(wait)


while True:
    color_wipe((50, 0, 50), .1)  # Purple LEDs
Example #14
0
	def __init__(self):
		self.rgbleds = neopixel.NeoPixel(microbit.pin15, 4)
		print("MAQUEEN initialized")
Example #15
0
# Use python 3.x
from time import sleep, time
import random
import argparse

import board
import neopixel

NO_PIXELS = 300

RED = (255, 0, 0)
pixels = neopixel.NeoPixel(board.D18, NO_PIXELS, auto_write=False)

parser = argparse.ArgumentParser(description='Wheel of Fortune!')
parser.add_argument('--running_time', default=10)
args = parser.parse_args()
running_time = int(args.running_time)


def turn_off(pixels, index):
    pixels[index] = (0, 0, 0)


def turn_on(pixels, index, color):
    pixels[index] = color


def clear(pixels):
    pixels.fill((0, 0, 0))

Example #16
0
import time

import board
import neopixel
from analogio import AnalogIn

pot = AnalogIn(board.A1)  # what pin the pot is on
pixpin = board.D0  # what pin the LEDs are on
numpix = 16  # number of LEDs in ring!
BPP = 4  # required for RGBW ring

ring = neopixel.NeoPixel(pixpin, numpix, bpp=BPP, brightness=0.9)


def val(pin):
    # divides voltage (65535) to get a value between 0 and 255
    return pin.value / 257


while True:
    # Two lines for troubleshooting to see analog value in REPL
    # print("A0: %f" % (pot.value / 65535 * 3.3))
    # time.sleep(1)

    # change floating point value to an int
    ring.fill((0, 0, 0, int(val(pot))))
    time.sleep(0.01)
import board
import neopixel
import time

pixels = neopixel.NeoPixel(board.D18, 150, brightness=0.2, auto_write=False)

while True:
    for i in range(0, 150, 2):
        pixels[i] = (255, 0, 0)

    for i in range(1, 150, 2):
        pixels[i] = (0, 255, 0)

    pixels.show()

    time.sleep(1)

    for i in range(1, 150, 2):
        pixels[i] = (255, 0, 0)

    for i in range(0, 150, 2):
        pixels[i] = (0, 255, 0)

    pixels.show()

    time.sleep(1)
import neopixel as neo  # Feather M4
from simpleio import map_range, tone
import adafruit_ds3231
from analogio import AnalogIn
from cedargrove_unit_converter.chronos import adjust_dst
from cedargrove_clock_builder.repl_display import ReplDisplay
from cedargrove_clock_builder.bigled_7x4_display import BigLed7x4Display  # 7-segment LED

i2c = board.I2C()
ds3231 = adafruit_ds3231.DS3231(i2c)

# Feather M4 battery monitor and piezo
batt = AnalogIn(board.VOLTAGE_MONITOR)

# Feather M4 NeoPixel, purple indicator
pixel = neo.NeoPixel(board.NEOPIXEL, 1, brightness=0.01, auto_write=False)
pixel[0] = (200, 0, 200)
pixel.write()
time.sleep(0.1)

print("Battery: {:01.2f} volts".format((batt.value / 65520) * 6.6))

### SETTINGS ###
clock_display = ["big_led", "repl"]  # List of active display(s)
clock_zone = "Pacific"  # Name of local time zone
clock_24_hour = False  # 24-hour clock = True; 12-hour AM/PM = False
clock_auto_dst = True  # Automatic US DST = True
clock_sound = False  # Sound is active = True
clock_tick = True  # One-second tick sound

### Instatiate displays
  for l in range(leds):
		pixels[l] = vu[l]
		pixels[9-l] = vu[l]
    
  #Si no hemos iluminado todos los leds, encendemos uno más según el color correspondiente con un factor de escala correspondiente a bright
  if leds < 4:
    dim = tuple(round(bright*x) for x in vu[leds+1])
    pixels[leds] = dim
    pixels[9-leds] = dim
    
  pixels.show()

# Programa principal

# Configuramos los neopixels y los apagamos
pixels = neopixel.NeoPixel(board.NEOPIXEL, NUM_PIXELS,brightness=0.1, auto_write=False)
pixels.fill(0)
pixels.show()

mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA,sample_rate=16000, bit_depth=16)

# Calibramos el vu-meter. Se asume que este será el valor mínimo, silencio.
samples = array.array('H', [0] * NUM_SAMPLES)
mic.record(samples, len(samples))
input_floor = normalized_rms(samples) + 10

# Ajustamos la sensibilidad
sensitivity = 500
input_ceiling = input_floor + sensitivity

while True:
Example #20
0
rssi = -80  # -80 is good, -20 is very close, -120 is very far away
scan_timeout = 0.25
unique_contacts = set()

# set up Bluefruit Connect (from ej)
if 1:
    from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
    from adafruit_ble.services.nordic import UARTService
    from adafruit_bluefruit_connect.packet import Packet
    uart_server = UARTService()
    advertisement = ProvideServicesAdvertisement(uart_server)
    was_connected = False
    radio.start_advertising(advertisement)

pixels = neopixel.NeoPixel(board.NEOPIXEL,
                           10,
                           brightness=0.2,
                           auto_write=False)
pixels[0] = (10, 255, 38)
pixels[1] = (0, 255, 242)
pixels[2] = (2, 20, 255)
pixels[3] = (40, 2, 200)
pixels[4] = (167, 8, 211)
pixels[5] = (185, 211, 12)
pixels[6] = (211, 132, 4)
pixels[7] = (211, 66, 8)
pixels[8] = (211, 4, 7)
pixels[9] = (255, 0, 0)
pixels.show()
debug_test = 0
multstage = 0
multipliers = [25]
from board import A1
import lightening
import neopixel
import time

pixel_pin = A1
num_pixels = 64
rows = 8
cols = 8

rain = lightening.Lightening()

pixels = neopixel.NeoPixel(pixel_pin, num_pixels, auto_write=False)


def convert_to_num(row, col):
    if row % 2 == 0:
        return (row * 8) + col
    else:
        return ((row + 1) * 8) - (col + 1)


while True:
    frame = rain.calc_next_frame()
    for x in range(0, rows):
        for y in range(0, cols):
            pixels[convert_to_num(y, x)] = rain.frame[x][y]
    pixels.show()
    time.sleep(0.1)
Example #22
0
            'raw_metar': metar[0],
            'flight_category': metar[30],
            'wind_speed_kt': metar[8],
            'wind_gust_kt': metar[9],
            'pixel': airports[station_id],
            'lightning': True if 'LTG' in metar[0] else False,
            'last_state': 'on',
        }
    return stations


stations = get_metars()
last_fetched = utime.time(
)  # The number of seconds, as an integer, since power on
while True:
    np = neopixel.NeoPixel(machine.Pin(pin),
                           len(airports))  # Initialize neopixels
    # Check if we want to refresh the metars
    if (utime.time() - last_fetched) > metar_update_frequency:
        stations = get_metars()
        last_fetched = utime.time()
    for station, data in stations.items():
        color = None
        # Uncomment one of the below items to test
        # data['lightning'] = True
        # data['wind_speed_kt'] = '16'
        # data['wind_gust_kt'] = '16'
        flight_category = data['flight_category']
        if data['lightning']:
            # Use white for lightning
            color = flight_category_rgb['WHITE']
        elif int(data['wind_speed_kt']) > wind_threshold:
Example #23
0
Nixie1 = Exixe(cs2, spi, False, 0)
Nixie1.set_led(0, 0, 0)
Nixie2.set_led(0, 0, 0)

# High powered non addressable LED for muzzle flash
red = pulseio.PWMOut(board.D11, duty_cycle=0, frequency=20000)
green = pulseio.PWMOut(board.D12, duty_cycle=0, frequency=20000)
blue = pulseio.PWMOut(board.D13, duty_cycle=0, frequency=20000)

# trigger switch
switch = digitalio.DigitalInOut(TRIGGER_PIN)
switch.direction = digitalio.Direction.INPUT
switch.pull = digitalio.Pull.UP

# Neopixels
strip = neopixel.NeoPixel(board.D5, NUM_PIXELS, brightness=1)


def fire():
    wave_file = open(WAV_FIRE, "rb")
    wave = audioio.WaveFile(wave_file)
    fired = False
    Nixie2.set_digit(0)
    Nixie1.set_digit(0)
    strip.fill((0, 0, 0))
    audio.play(wave)
    while audio.playing:
        if not fired:
            for i in range(-100, 1):
                red.duty_cycle = int(i * -65535 / 100)
                green.duty_cycle = int(i * -65535 / 100)
Example #24
0
# SPDX-License-Identifier: MIT
"""
This example animates a jade comet that bounces from end to end of the strip.

For QT Py Haxpress and a NeoPixel strip. Update pixel_pin and pixel_num to match your wiring if
using a different board or form of NeoPixels.

This example will run on SAMD21 (M0) Express boards (such as Circuit Playground Express or QT Py
Haxpress), but not on SAMD21 non-Express boards (such as QT Py or Trinket).
"""
import board
import neopixel

from adafruit_led_animation.animation.comet import Comet
from adafruit_led_animation.color import JADE

# Update to match the pin connected to your NeoPixels
pixel_pin = board.A3
# Update to match the number of NeoPixels you have connected
pixel_num = 30

pixels = neopixel.NeoPixel(pixel_pin,
                           pixel_num,
                           brightness=0.5,
                           auto_write=False)

comet = Comet(pixels, speed=0.02, color=JADE, tail_length=10, bounce=True)

while True:
    comet.animate()
Example #25
0
# CircuitPlaygroundExpress_NeoPixel

import time

import board
import neopixel
import math

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0)
spixels = neopixel.NeoPixel(board.A1, 30, brightness=0.5)

pixels.fill((0, 0, 0))
pixels.show()

rbow1 = 0
rbow2 = 64
rbow3 = 128
rbow4 = 192

# choose which demos to play
# 1 means play, 0 means don't!
simpleCircleDemo = 0
flashDemo = 0
rainbowDemo = 0
rainbowCycleDemo = 0
rainbowPixels = 1


def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    'ff6897': '0',
    'ff30cf': '1',
    'ff18e7': '2',
    'ff7a85': '3',
    'ff10ef': '4',
    'ff38c7': '5',
    'ff5aa5': '6',
    'ff42bd': '7',
    'ff4ab5': '8',
    'ff52ad': '9',
    'ff9867': '-',
    'ffb04f': '+',
}

ir = IR_RECV(Pin(12), timeout=80)
np = neopixel.NeoPixel(Pin(19), 1)
rgb = 3 * [0]
color = 0
np[0] = tuple(rgb)  # rgb color = (0,0,0)
np.write()

try:
    prev_key = None
    while True:
        codes = ir.read()  # read IR code
        if len(codes) > 0 and codes[0] in keys:
            code = codes[0]
            print(code, keys[code])
            if code != '0':
                prev_key = keys[code]
            key = prev_key
Example #27
0
        Pwm.freq(value)  # set frequency
        print('Pwm.freq ' + str(Pwm.freq()))  # get current frequency

        Pwm.duty(randint(100, 200))  # set duty cycle
        print('Pwm.duty ' + str(Pwm.duty()))  # get current duty cycle

        array.reverse()

    Pwm.deinit()  # turn off PWM on the pin

    NeoPixelPower = Pin(2, Pin.OUT)
    NeoPixelPower.value(1)

    # Setup the Neopixel strip on pin0 with a length of 8 pixels
    np = neopixel.NeoPixel(Pin(4), 25)

    while True:

        value = 0
        for b in range(0, 51):
            np.fill((0, 0, value))
            np.write()
            time.sleep(0.005)
            value = value + 5
        value = 255
        for b in range(0, 51):
            np.fill((0, 0, value))
            np.write()
            time.sleep(0.005)
            value = value - 5
    raise

# ESP32 Setup
try:
    esp32_cs = DigitalInOut(board.ESP_CS)
    esp32_ready = DigitalInOut(board.ESP_BUSY)
    esp32_reset = DigitalInOut(board.ESP_RESET)
except AttributeError:
    esp32_cs = DigitalInOut(board.D9)
    esp32_ready = DigitalInOut(board.D10)
    esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(
    board.NEOPIXEL, 1, brightness=0.2
)  # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4"""
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

# Create an instance of the Adafruit IO HTTP client
io = IO_HTTP(aio_username, aio_key, wifi)

try:
Example #29
0
File: blue.py Project: mkhuthir/rpi
#! /usr/bin/python3

import board
import neopixel

pixels = neopixel.NeoPixel(board.D18, 30)

pixels[0] = (0, 0, 255)
import board
import digitalio
import time
import neopixel
import pwmio
from adafruit_motor import servo
from digitalio import DigitalInOut, Direction, Pull

btn = DigitalInOut(board.SWITCH)
btn.direction = Direction.INPUT
btn.pull = Pull.UP

prev_state = btn.value

pixels = neopixel.NeoPixel(board.NEOPIXEL, 1)
pixels[0] = (0, 0, 0)

BLINK_LIST = [{
    "ON": 0.5,
    "OFF": 0.5,
    "PREV_TIME": -1,
    "PIN": board.D5,
}, {
    "ON": 0.5,
    "OFF": 0.5,
    "PREV_TIME": -1,
    "PIN": board.D6,
}, {
    "ON": 0.5,
    "OFF": 0.5,