Beispiel #1
0
def SetupUI():
    global rotPot, zoomPot, nodePot
    rotPot = AnalogIn(board.A1)
    zoomPot = AnalogIn(board.A0)
    nodePot = AnalogIn(board.A2)
Beispiel #2
0
# SPDX-License-Identifier: MIT
"""Bluetooth Key Tracker."""
from adafruit_ble import BLERadio
from adafruit_led_animation.animation import Pulse, Solid
import adafruit_led_animation.color as color
from analogio import AnalogIn
from array import array
from audiobusio import I2SOut
from audiocore import RawSample, WaveFile
from board import BATTERY, D5, D6, D9, NEOPIXEL, RX, TX
from digitalio import DigitalInOut, Direction, Pull
from math import pi, sin
from neopixel import NeoPixel
from time import sleep

battery = AnalogIn(BATTERY)

ble = BLERadio()
hit_status = [color.RED, color.ORANGE, color.AMBER, color.GREEN]

pixel = NeoPixel(NEOPIXEL, 1)
pulse = Pulse(
    pixel,
    speed=0.01,
    color=color.PURPLE,  # Use CYAN for Male Key
    period=3,
    min_intensity=0.0,
    max_intensity=0.5)

solid = Solid(pixel, color.GREEN)
Beispiel #3
0
# Pin setup
SERVO_PIN = board.A1
FEEDBACK_PIN = board.A5

# Calibration setup
ANGLE_MIN = 0
ANGLE_MAX = 180

# Setup servo
pwm = pulseio.PWMOut(SERVO_PIN, duty_cycle=2**15, frequency=50)
servo = servo.Servo(pwm)
servo.angle = None

# Setup feedback
feedback = AnalogIn(FEEDBACK_PIN)

print("Servo feedback calibration.")
# Move to MIN angle
print("Moving to {}...".format(ANGLE_MIN), end="")
servo.angle = ANGLE_MIN
time.sleep(2)
print("Done.")
feedback_min = feedback.value
# Move to MAX angle
print("Moving to {}...".format(ANGLE_MAX), end="")
servo.angle = ANGLE_MAX
time.sleep(2)
print("Done.")
feedback_max = feedback.value
# Print results
Beispiel #4
0
import adafruit_adt7410
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label
from adafruit_button import Button
import adafruit_touchscreen
from adafruit_pyportal import PyPortal
from adafruit_display_shapes.rect import Rect

# ------------- Inputs and Outputs Setup ------------- #
# init. the temperature sensor
i2c_bus = busio.I2C(board.SCL, board.SDA)
adt = adafruit_adt7410.ADT7410(i2c_bus, address=0x48)
adt.high_resolution = True

# init. the light sensor
light_sensor = AnalogIn(board.LIGHT)

pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=1)
WHITE = 0xffffff
RED = 0xff0000
YELLOW = 0xffff00
GREEN = 0x00ff00
BLUE = 0x0000ff
PURPLE = 0xff00ff
BLACK = 0x000000

# ---------- Sound Effects ------------- #
soundDemo = '/sounds/sound.wav'
soundBeep = '/sounds/beep.wav'
soundTab = '/sounds/tab.wav'
Beispiel #5
0
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import time
import board
from analogio import AnalogIn
import digitalio
import datetime as dt

pot_top = digitalio.DigitalInOut(board.G0)
pot_top.direction = digitalio.Direction.OUTPUT
pot_top.value = True
pot_bot = digitalio.DigitalInOut(board.G2)
pot_bot.direction = digitalio.Direction.OUTPUT
pot_bot = False
lightSensor = AnalogIn(board.G1)
now = dt.datetime.now()


def get_voltage(raw):
    return (raw * 3.3) / 65535


# Parameters
x_len = 200  # Number of points to display
y_range = [0, 3.3]  # Range of possible Y values to display

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = list(range(0, 200))
# WIRING:
# 1 Wire connecting  VCC to RH to make a voltage divider using the
#   internal resistor between RH and RW
# 2 Wire connecting RW to A0
def wiper_voltage(_wiper_pin):
    raw_value = _wiper_pin.value
    return raw_value / (2 ** 16 - 1) * _wiper_pin.reference_voltage


i2c = busio.I2C(board.SCL, board.SDA)
ds = adafruit_ds1841.DS1841(i2c)


LUT_MAX_INDEX = 71
WIPER_MAX = 127
wiper_pin = AnalogIn(board.A0)

ds.lut_mode_enabled = True

# you only need to run this once per DS1841 since the LUT is stored to EEPROM
# for i in range(0, LUT_MAX_INDEX+1):
#     new_lut_val = WIPER_MAX-i
#     ds.set_lut(i, new_lut_val)

while True:
    for i in range(0, LUT_MAX_INDEX + 1):
        ds.lut_selection = i
        # for printing to serial terminal:
        print(
            "\tLUTAR/LUT Selection: %s" % hex(ds.lut_selection),
            "\tWiper = %d" % ds.wiper,
Beispiel #7
0
try:
    # Get the 'temperature' feed from Adafruit IO
    temperature_feed = io.get_feed('temperature')
    light_feed = io.get_feed('light')
except AdafruitIO_RequestError:
    # If no 'temperature' feed exists, create one
    temperature_feed = io.create_new_feed('temperature')
    light_feed = io.create_new_feed('light')

# Set up ADT7410 sensor
i2c_bus = busio.I2C(board.SCL, board.SDA)
adt = adafruit_adt7410.ADT7410(i2c_bus, address=0x48)
adt.high_resolution = True

# Set up an analog light sensor on the PyPortal
adc = AnalogIn(board.LIGHT)

while True:
    try:
        light_value = adc.value
        print('Light Level: ', light_value)

        temperature = adt.temperature
        print('Temperature: %0.2f C' % (temperature))

        print('Sending to Adafruit IO...')

        io.send_data(light_feed['key'], light_value)
        io.send_data(temperature_feed['key'], temperature, precision=2)
        print('Sent to Adafruit IO!')
    except (ValueError, RuntimeError) as e:
# Trinket Gemma Servo Control
# for Adafruit M0 boards

import board
import pulseio
from adafruit_motor import servo
from analogio import AnalogIn

# servo pin for the M0 boards:
pwm = pulseio.PWMOut(board.A2, duty_cycle=2 ** 15, frequency=50)
my_servo = servo.Servo(pwm)
angle = 0

# potentiometer
trimpot = AnalogIn(board.A1)  # pot pin for servo control

def remap_range(value, left_min, left_max, right_min, right_max):
    # this remaps a value from original (left) range to new (right) range
    # Figure out how 'wide' each range is
    left_span = left_max - left_min
    right_span = right_max - right_min

    # Convert the left range into a 0-1 range (int)
    value_scaled = int(value - left_min) / int(left_span)

    # Convert the 0-1 range into a value in the right range.
    return int(right_min + (value_scaled * right_span))


while True:
    angle = remap_range(trimpot.value, 0, 65535, 0, 180)
Beispiel #9
0
### THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
### IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
### FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
### AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
### LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
### OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
### SOFTWARE.

import time

import board
from analogio import AnalogIn

### All eight pins on CPX board
pins = [ AnalogIn(board.A0),
         AnalogIn(board.A1),
         AnalogIn(board.A2),
         AnalogIn(board.A3),
         AnalogIn(board.A4),
         AnalogIn(board.A5),
         AnalogIn(board.A6),
         AnalogIn(board.A7) ]     

numpins = len(pins)
refvoltage = pins[0].reference_voltage
adcconvfactor = refvoltage / 65536

### Convert value from pin.value to voltage
def getVoltage(pin):
    return pin.value * adcconvfactor
Beispiel #10
0
import time
from analogio import AnalogIn
from turtle import *

# The LED will illuminate when an object is close enough to reflect IR back to the detector.
# With board attached to computer, lanuch plotter in Mu to see graphical response rates.

print('\nRunning "turtle_obstacles.py"')

# Pin assignments
leftEmitter = digitalio.DigitalInOut(board.D10)
leftLED = digitalio.DigitalInOut(board.D7)
rightEmitter = digitalio.DigitalInOut(board.D13)
rightLED = digitalio.DigitalInOut(board.D11)
button = digitalio.DigitalInOut(board.D12)
rightDetector = AnalogIn(board.A0)
leftDetector = AnalogIn(board.A1)

# Port setup
leftLED.direction = digitalio.Direction.OUTPUT
leftEmitter.direction = digitalio.Direction.OUTPUT
rightLED.direction = digitalio.Direction.OUTPUT
rightEmitter.direction = digitalio.Direction.OUTPUT
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP

# Turn IR LEDs on.  You might be able to see them in a camera.
rightEmitter.value = True
leftEmitter.value = True

    global mode
    if not fastTurn():
        if mode == 0:
            if not fastTurn():
                print("press")
                cc.send(ConsumerControlCode.PLAY_PAUSE)
        if mode == 1:
            kbd.press(Keycode.SPACE)
            # kbd.press(Keycode.ZERO)
    kbd.release_all()


e1 = Encoder(board.D4, board.D3, upCallback=enc1Up, downCallback=enc1Down)
e2 = Encoder(board.D1, board.D0, upCallback=enc2Up, downCallback=enc2Down)

buttonPin = AnalogIn(board.D2)

while True:

    e1.update()
    e2.update()

    v = buttonPin.value
    if 65535 > v > 54500:
        b1 = False
        b2 = False
    elif 54500 > v > 38500:
        b1 = True
        b2 = False
    elif 38500 > v > 29400:
        b1 = False
class Peripherals:
    """Peripherals Helper Class for the MagTag Library"""

    # pylint: disable=too-many-instance-attributes, too-many-locals, too-many-branches, too-many-statements
    def __init__(self):
        # Neopixel power
        try:
            self._neopixel_disable = DigitalInOut(board.NEOPIXEL_POWER)
            self._neopixel_disable.direction = Direction.OUTPUT
            self._neopixel_disable.value = False
        except ValueError:
            self._neopixel_disable = None
        # Neopixels
        self.neopixels = neopixel.NeoPixel(board.NEOPIXEL, 4, brightness=0.3)

        # Battery Voltage
        self._batt_monitor = AnalogIn(board.BATTERY)

        # Speaker Enable
        self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.direction = Direction.OUTPUT
        self._speaker_enable.value = False

        # Light Sensor
        self._light = AnalogIn(board.LIGHT)

        # Buttons
        self.buttons = []
        for pin in (board.BUTTON_A, board.BUTTON_B, board.BUTTON_C,
                    board.BUTTON_D):
            switch = DigitalInOut(pin)
            switch.direction = Direction.INPUT
            switch.pull = Pull.UP
            self.buttons.append(switch)

    def play_tone(self, frequency, duration):
        """Automatically Enable/Disable the speaker and play
        a tone at the specified frequency for the specified duration
        It will attempt to play the sound up to 3 times in the case of
        an error.
        """
        if frequency < 0:
            raise ValueError("Negative frequencies are not allowed.")
        self._speaker_enable.value = True
        attempt = 0
        # Try up to 3 times to play the sound
        while attempt < 3:
            try:
                simpleio.tone(board.SPEAKER, frequency, duration)
                break
            except NameError:
                pass
            attempt += 1
        self._speaker_enable.value = False

    def deinit(self):
        """Call deinit on all resources to free them"""
        self.neopixels.deinit()
        if self._neopixel_disable is not None:
            self._neopixel_disable.deinit()
        self._speaker_enable.deinit()
        for button in self.buttons:
            button.deinit()
        self._batt_monitor.deinit()
        self._light.deinit()

    @property
    def battery(self):
        """Return the voltage of the battery"""
        return (self._batt_monitor.value / 65535.0) * 3.3 * 2

    @property
    def neopixel_disable(self):
        """
        Enable or disable the neopixels for power savings
        """
        if self._neopixel_disable is not None:
            return self._neopixel_disable.value
        return False

    @neopixel_disable.setter
    def neopixel_disable(self, value):
        if self._neopixel_disable is not None:
            self._neopixel_disable.value = value

    @property
    def speaker_disable(self):
        """
        Enable or disable the speaker for power savings
        """
        return not self._speaker_enable.value

    @speaker_disable.setter
    def speaker_disable(self, value):
        self._speaker_enable.value = not value

    @property
    def button_a_pressed(self):
        """
        Return whether Button A is pressed
        """
        return not self.buttons[0].value

    @property
    def button_b_pressed(self):
        """
        Return whether Button B is pressed
        """
        return not self.buttons[1].value

    @property
    def button_c_pressed(self):
        """
        Return whether Button C is pressed
        """
        return not self.buttons[2].value

    @property
    def button_d_pressed(self):
        """
        Return whether Button D is pressed
        """
        return not self.buttons[3].value

    @property
    def any_button_pressed(self):
        """
        Return whether any button is pressed
        """
        return False in [self.buttons[i].value for i in range(0, 4)]

    @property
    def light(self):
        """
        Return the value of the light sensor. The neopixel_disable property
        must be false to get a value.

        .. code-block:: python

            import time
            from adafruit_magtag.magtag import MagTag

            magtag = MagTag()

            while True:
                print(magtag.peripherals.light)
                time.sleep(0.01)

        """
        return self._light.value
Beispiel #13
0
time_delay_button.direction = digitalio.Direction.INPUT
time_delay_button.pull = digitalio.Pull.DOWN

#ADVANCED SETTINGS
cooldown_delay = 200
passive_mode = False
led_brightness = 0.06
time_delay = 2
rainbow_cycle_count = 8
log_limit = 2000  #lines

i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
lis3dh.range = adafruit_lis3dh.RANGE_8_G

analog1in = AnalogIn(board.IR_PROXIMITY)

ir_led = digitalio.DigitalInOut(board.IR_TX)
ir_led.direction = digitalio.Direction.OUTPUT


def set_delay():
    global time_delay
    global boot_time

    for led in range(time_delay):
        pixels[led] = RED
        pixels.show()
    boot_time = time.monotonic()
    time.sleep(1)
    start_time = time.monotonic()
def get_adc():
    with AnalogIn(board.ADC) as ai:
        return ai.value / 65535.0
Beispiel #15
0
# Project home:
#   https://tinys2.io
#

# Import required libraries
import time
import board
from digitalio import DigitalInOut, Direction, Pull
from analogio import AnalogIn

# Setup the NeoPixel power pin
pixel_power = DigitalInOut(board.NEOPIXEL_POWER)
pixel_power.direction = Direction.OUTPUT

# Setup the BATTERY voltage sense pin
vbat_voltage = AnalogIn(board.BATTERY)

# Setup the VBUS sense pin
vbus_sense = DigitalInOut(board.VBUS_SENSE)
vbus_sense.direction = Direction.INPUT

   
# Helper functions
def set_pixel_power(state):
    """Enable or Disable power to the onboard NeoPixel to either show colour, or to reduce power fro deep sleep."""
    global pixel_power
    pixel_power.value = state
    
def get_battery_voltage():
    """Get the approximate battery voltage."""
    # I don't really understand what CP is doing under the hood here for the ADC range & calibration,
Beispiel #16
0
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
import adafruit_dotstar as dotstar

# One pixel connected internally!
dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)

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

# Analog output on A0
aout = AnalogOut(board.A0)

# Analog input on A1
analog1in = AnalogIn(board.A1)

# Capacitive touch on A2
touch2 = TouchIn(board.A2)

# Used if we do HID output, see below
kbd = Keyboard()

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

# Helper to convert analog input to voltage
def getVoltage(pin):
    return (pin.value * 3.3) / 65536

# Helper to give us a nice color swirl
def wheel(pos):
import time
import board
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.led_14x4_display import Led14x4Display  # 14-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 = ["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
from time import sleep
import board
import adafruit_ds3502
from analogio import AnalogIn

####### NOTE ################
# this example will not work with Blinka/rasberry Pi due to the lack of analog pins.
# Blinka and Raspberry Pi users should run the "ds3502_blinka_simpletest.py" example

i2c = board.I2C()
ds3502 = adafruit_ds3502.DS3502(i2c)
wiper_output = AnalogIn(board.A0)

while True:

    ds3502.wiper = 127
    print("Wiper set to %d" % ds3502.wiper)
    voltage = wiper_output.value
    voltage *= 3.3
    voltage /= 65535
    print("Wiper voltage: %.2f V" % voltage)
    print("")
    sleep(1.0)

    ds3502.wiper = 0
    print("Wiper set to %d" % ds3502.wiper)
    voltage = wiper_output.value
    voltage *= 3.3
    voltage /= 65535
    print("Wiper voltage: %.2f V" % voltage)
    print("")
Beispiel #19
0
# Create SPI bus
spi = busio.SPI(board.SCK, board.MOSI)

# Create the display
WIDTH = 128
HEIGHT = 64
DC = DigitalInOut(board.D7)
CS = DigitalInOut(board.D9)
RST = DigitalInOut(board.D10)
display = adafruit_ssd1306.SSD1306_SPI(WIDTH, HEIGHT, spi, DC, RST, CS)
display.fill(0)
display.show()

# Create the knobs
READS = 5
x_knob = AnalogIn(board.A0)
y_knob = AnalogIn(board.A1)

# Create the clear button
clear_button = DigitalInOut(board.D12)
clear_button.direction = Direction.INPUT
clear_button.pull = Pull.UP


def read_knobs(reads):
    avg_x = avg_y = 0
    for _ in range(reads):
        avg_x += x_knob.value
        avg_y += y_knob.value
    avg_x /= reads
    avg_y /= reads
Beispiel #20
0
import touchio
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
import adafruit_dotstar as dotstar
import time
import neopixel

# One pixel connected internally!
dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)

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

# Analog input on D0
analog1in = AnalogIn(board.D0)

# Analog output on D1
aout = AnalogOut(board.D1)

# Digital input with pullup on D2
button = DigitalInOut(board.D2)
button.direction = Direction.INPUT
button.pull = Pull.UP

# Capacitive touch on D3
touch = touchio.TouchIn(board.D3)

# NeoPixel strip (of 16 LEDs) connected on D4
NUMPIXELS = 16
neopixels = neopixel.NeoPixel(board.D4,
Beispiel #21
0
                y = -y
            yv.append(int(y))
    return xv, yv


x1, y1 = happiness(0)
x2, y2 = happiness(1)
xc = len(x1)
yv = [0] * xc


def interp(s, k):
    return round(y2[k] + (y1[k] - y2[k]) * s)


analog_in = AnalogIn(board.A1)

spi = board.SPI()
METRO_PINS = {'cs': board.D5, 'dc': board.D6, 'reset': board.D9}

ITSY_BITSY_PINS = {'cs': board.D7, 'dc': board.D9, 'reset': board.D10}

PINS = ITSY_BITSY_PINS
tft_cs = PINS['cs']
tft_dc = PINS['dc']

displayio.release_displays()
display_bus = displayio.FourWire(spi,
                                 command=tft_dc,
                                 chip_select=tft_cs,
                                 reset=PINS['reset'])
# fscale function:
# Floating Point Autoscale Function V0.1
# Written by Paul Badger 2007
# Modified fromhere code by Greg Shakar
# Ported to Circuit Python by Mikey Sklar

import time

import board
import neopixel
from rainbowio import colorwheel
from analogio import AnalogIn

n_pixels = 16  # Number of pixels you are using
mic_pin = AnalogIn(board.A1)  # Microphone is attached to this analog pin
led_pin = board.D1  # NeoPixel LED strand is connected to this pin
sample_window = .1  # Sample window for average level
peak_hang = 24  # Time of pause before peak dot falls
peak_fall = 4  # Rate of falling peak dot
input_floor = 10  # Lower range of analogRead input
# Max range of analogRead input, the lower the value the more sensitive
# (1023 = max)
input_ceiling = 300

peak = 16  # Peak level of column; used for falling dots
sample = 0

dotcount = 0  # Frame counter for peak dot
dothangcount = 0  # Frame counter for holding peak dot
Beispiel #23
0
# Release any resources currently in use for the displays
displayio.release_displays()

spi = board.SPI()
tft_cs = board.D9
tft_dc = board.D10
touch_cs = board.D6
sd_cs = board.D5
neopix_pin = board.D11

display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs)
display = adafruit_ili9341.ILI9341(display_bus, width=320, height=240)

#battery voltage reader
vbat_voltage = AnalogIn(board.VOLTAGE_MONITOR)

# Define radio parameters.
RADIO_FREQ_MHZ = 915.0  # Frequency of the radio in Mhz. Must match your
# module! Can be a value like 915.0, 433.0, etc.

# Define pins connected to the chip, use these if wiring up the breakout according to the guide:
CS = digitalio.DigitalInOut(board.D13)
RESET = digitalio.DigitalInOut(board.D12)

# Initialze RFM radio
rfm9x = adafruit_rfm9x.RFM9x(spi, CS, RESET, RADIO_FREQ_MHZ)

# Note that the radio is configured in LoRa mode so you can't control sync
# word, encryption, frequency deviation, or other settings!
# Audio output
cpx_audio = audioio.AudioOut(board.A0)
audio = audioio.WaveFile(open(AUDIO_FILENAME, "rb"))

# Rotating dancer
dancer = crickit.servo_2
dancer.angle = 0
MAX_SERVO_ANGLE = 160
move_direction = 1

# neopixels!
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1)
pixels.fill((0, 0, 0))

# light sensor
light = AnalogIn(board.LIGHT)


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.
    if pos < 0 or pos > 255:
        return 0, 0, 0
    if pos < 85:
        return int(255 - pos * 3), int(pos * 3), 0
    if pos < 170:
        pos -= 85
        return 0, int(255 - pos * 3), int(pos * 3)
    pos -= 170
    return int(pos * 3), 0, int(255 - (pos * 3))
def loop():
    for i in (0, numberOfAnalogPins):
        data[i] = AnalogIn(board.D5)
    vw.vw_send(data, 80)
    time.sleep(1)  # //send every second
    return
Beispiel #26
0
    # Play a little tune
    if winner:
        cpx.play_tone(800, 0.2)
        cpx.play_tone(900, 0.2)
        cpx.play_tone(1400, 0.2)
        cpx.play_tone(1100, 0.2)
    else:
        cpx.play_tone(200, 1)

    # Sit here forever
    while True:
        pass


# Seed the random function with noise
a4 = AnalogIn(board.A4)
a5 = AnalogIn(board.A5)
a6 = AnalogIn(board.A6)
a7 = AnalogIn(board.A7)

seed = a4.value
seed += a5.value
seed += a6.value
seed += a7.value

random.seed(seed)

# Wait a random amount of time
count_time = random.randrange(SHORTEST_DELAY, LONGEST_DELAY + 1)
start_time = time.monotonic()
while time.monotonic() - start_time < count_time:
Beispiel #27
0
# CircuitPlaygroundExpress_LightSensor
# reads the on-board light sensor and graphs the brighness with NeoPixels

import time

import board
import neopixel
from analogio import AnalogIn
from simpleio import map_range

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=0, brightness=.05)
pixels.fill((0, 0, 0))
pixels.show()

analogin = AnalogIn(board.LIGHT)

while True:
    # light value remaped to pixel position
    peak = map_range(analogin.value, 2000, 62000, 0, 9)
    print(analogin.value)
    print(int(peak))

    for i in range(0, 9, 1):
        if i <= peak:
            pixels[i] = (0, 255, 0)
        else:
            pixels[i] = (0, 0, 0)
    pixels.show()

    time.sleep(0.01)
Beispiel #28
0
from adafruit_midi.note_on import NoteOn
from adafruit_midi.note_off import NoteOff
from adafruit_midi.control_change import ControlChange
from adafruit_midi.pitch_bend import PitchBend

#  imports MIDI
midi = adafruit_midi.MIDI(midi_out=usb_midi.ports[1], out_channel=0)

#  setup for LIS3DH accelerometer
i2c = busio.I2C(board.SCL, board.SDA)
lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c)

lis3dh.range = adafruit_lis3dh.RANGE_2_G

#  setup for 3 potentiometers
pitchbend_pot = AnalogIn(board.A1)
mod_pot = AnalogIn(board.A2)
velocity_pot = AnalogIn(board.A3)

#  setup for two switches that will switch modes
mod_select = DigitalInOut(board.D52)
mod_select.direction = Direction.INPUT
mod_select.pull = Pull.UP

strum_select = DigitalInOut(board.D53)
strum_select.direction = Direction.INPUT
strum_select.pull = Pull.UP

#  setup for strummer switches
strumUP = DigitalInOut(board.D22)
strumUP.direction = Direction.INPUT
Beispiel #29
0
# envoi d'une tension via le port serie
import time
import board
from analogio import AnalogIn
U0 = AnalogIn(board.A0)
# sur carte trinket M0 A0 sur patte 1

while True:
    Upotar = U0.value*3.3/65535
    print(Upotar,Upotar)
    # print("coucou")
    time.sleep(0.05)
    
Beispiel #30
0
# SPDX-FileCopyrightText: 2019 Anne Barela for Adafruit Industries
#
# SPDX-License-Identifier: MIT

from time import sleep
from adafruit_ble.uart_server import UARTServer
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.button_packet import ButtonPacket
from adafruit_bluefruit_connect.color_packet import ColorPacket
from board import A0, D13
from analogio import AnalogIn
from digitalio import DigitalInOut, Direction

led = AnalogIn(A0)  # Initialize blue LED light detector

solenoid = DigitalInOut(D13)  # Initialize solenoid
solenoid.direction = Direction.OUTPUT
solenoid.value = False

uart_server = UARTServer()

while True:
    uart_server.start_advertising()  # Advertise when not connected.

    while not uart_server.connected:  # Wait for connection
        pass

    while uart_server.connected:  # Connected
        if uart_server.in_waiting:  # Check BLE commands
            packet = Packet.from_stream(uart_server)
            if isinstance(packet, ButtonPacket):
  speaker.frequency = 494
  speaker.duty_cycle = ON
  time.sleep(.5)

  speaker.frequency = 444
  time.sleep(.5)

  # tone 3
  speaker.frequency = 494
  time.sleep(.5)

  speaker.duty_cycle = OFF

######################### MAIN LOOP ##############################

randomSeedPin = AnalogIn(board.A0)
random.seed(randomSeedPin.value)
randomSeedPin.deinit()

# randomize the starting button
activeButtonId = random.randint(0,4)

i = 0
while True:
  # spin internal neopixel LED around for pretty lightssss
  dot[0] = wheel(i & 255)

  activeButton = buttons[activeButtonId]
  activeButtonLed = buttonLeds[activeButtonId]

  if i < 125: