コード例 #1
0
led = digitalio.DigitalInOut(board.D13)
led.direction = digitalio.Direction.OUTPUT

radio = adafruit_ble.BLERadio()
# the rssi is the signal strength. Play with this until
# you like the distance things are triggering
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)
コード例 #2
0
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, RED_LED, SWITCH
from analogio import AnalogIn
from digitalio import DigitalInOut, Direction

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

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

ble = BLERadio()
# uart_server = UARTServer()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

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

    while not ble.connected:  # Wait for connection
        pass

    while ble.connected:  # Connected
        if ble.in_waiting:  # Check BLE commands
            packet = Packet.from_stream(uart)
            if isinstance(packet, ButtonPacket):
                if packet.button == '1' and packet.pressed:
                    solenoid.value = True  # Activate solenoid for 1 second
                    sleep(1)
コード例 #3
0
# CircuitPython Bluefruit LE Connect Plotter Example

import time
import board
import analogio
import adafruit_thermistor
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

thermistor = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000,
                                            25, 3950)
light = analogio.AnalogIn(board.LIGHT)


def scale(value):
    """Scale the light sensor values from 0-65535 (AnalogIn range)
    to 0-50 (arbitrarily chosen to plot well with temperature)"""
    return value / 65535 * 50


while True:
    # Advertise when not connected.
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass
    ble.stop_advertising()
コード例 #4
0
ファイル: code.py プロジェクト: Fozzy0007/mini-bugs
import neopixel
import adafruit_thermistor


# thermistor = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950)
# temp_c = thermistor.temperature
# temp_f = thermistor.temperature * 9 / 5 + 32
print(dir(board))
sensors = CpbSensorData()
print("Temperature is: %f F" %(sensors.getTemperatureInF()))
print("Light value is: %f " %(sensors.getLightReading()))
print("ButtonA: %f " % (sensors.getButtonA()))


ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.05)
GREEN = 0x002200
CYAN  = 0x002222
RED   = 0x660000


while True:
    print("Advertising '%s'. . ." %ble.name)
    pixels.fill(CYAN)
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass
コード例 #5
0
# Adafruit ADS1115 ADC breakout board
# Riedon SSA-100 current sensor
#
import time
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

fw_ver = "Riedon_BLE_plotter_rev1.py"

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)

# Create the ADS object
# ads = ADS.ADS1015(i2c)
ads = ADS.ADS1115(i2c)

# Create differential channel on Pin 0 and Pin 1
chan = AnalogIn(ads, ADS.P0, ADS.P1)

#   Max ADC counts for ADS1015 = 2047
#                      ADS1115 = 32767
# The ADS1015 and ADS1115 both have the same gain options.
コード例 #6
0
# Basic example for using the BLE Connect UART
# To use, start this program, and start the Adafruit Bluefruit LE Connect app.
# Connect, and then select UART

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

while True:
    print("WAITING...")
    # Advertise when not connected.
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass

    # Connected
    ble.stop_advertising()
    print("CONNECTED")

    # Loop and read packets
    while ble.connected:
        if uart_server.in_waiting:
            raw_bytes = uart_server.read(uart_server.in_waiting)
            text = raw_bytes.decode().strip()
            print("raw bytes =", raw_bytes)
            print("text =", text)
コード例 #7
0
import pulseio
import math
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService



# Defining a new bluetooth low energy service
ble = BLERadio()
# Setting the advertisement name to Park Med
ble.name = "Park Med"

#defining a new UART protocol
#UART is a bluetooth protocol that allows the transmission of short messages
uart_service = UARTService()

#bluetooth stream message global
streamMessage = None

#advertising the bluetooth device with uart_service
advertisement = ProvideServicesAdvertisement(uart_service)



#small red LED
led = digitalio.DigitalInOut(board.D13)
led.direction = digitalio.Direction.OUTPUT

#global duty cycle for the motors
duty = 36695
コード例 #8
0
import board
from adafruit_seesaw.seesaw import Seesaw
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
import neopixel

# Setup I2C
i2c_bus = board.I2C()

# Setup Soil Sensor
ss = Seesaw(i2c_bus, addr=0x36)

# Setup the BLE radio
ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

# Setup the onboard neopixel
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)
pixel.brightness = 0.1
BLUE = (0, 0, 255)
NAVY = (0, 0, 128)
SHORTBLINK = 0.25
LONGBLINK = 0.5


def NeoPixelPattern():
    pixel.fill(BLUE)
    time.sleep(SHORTBLINK)
    pixel.fill(NAVY)
コード例 #9
0
# SPDX-FileCopyrightText: 2020 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: MIT

# Provide an "eval()" service over BLE UART.

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

while True:
    ble.start_advertising(advertisement)
    print("Waiting to connect")
    while not ble.connected:
        pass
    print("Connected")
    while ble.connected:
        s = uart.readline()
        if s:
            try:
                result = str(eval(s))
            except Exception as e:
                result = repr(e)
            uart.write(result.encode("utf-8"))
コード例 #10
0
ファイル: code.py プロジェクト: lorandcheng/led-games
MIN = 0
MAX = 2**16
THRESHOLD = 3000

## Clue Buttons Stuff ###############################################

buttonA = digitalio.DigitalInOut(board.BUTTON_A)
buttonB = digitalio.DigitalInOut(board.BUTTON_B)

buttonA.pull = digitalio.Pull.UP
buttonB.pull = digitalio.Pull.UP

## BLE Stuff ######################################################
ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

#ble.start_advertising(advertisement)

while True:
    ble.start_advertising(advertisement)
    print("Waiting to connect")
    while not ble.connected:
        pass
    print("Connected")
    while ble.connected:
        #s = input("Eval: ")
        #uart_service.write(s.encode("utf-8"))
        #uart_service.write(b'\n')
        #print(uart_service.readline().decode("utf-8"))
コード例 #11
0
ファイル: ble_attempt.py プロジェクト: JWaym0nd/boa
# import board
# import busio
# import digitalio
# import neopixel

# from adafruit_bluefruit_connect.color_packet import ColorPacket

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()

uart_connection = None
# See if any existing connections are providing UARTService.
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

if ble.connected:
    for connection in ble.connections:
        if UARTService in connection:
            uart_connection = connection
        break

while True:
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass

    if not uart_connection:
        print("Scanning...")
コード例 #12
0
from adafruit_circuitplayground import cp
import time
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)
while True:
    if cp.button_a:
        cp.play_file("horn.wav")
    if cp.button_b:
        cp.play_file("horn.wav")

    R = 0
    G = 0
    B = 0
    x, y, z = cp.acceleration
    tuplaxyz = str(x) + ',' + str(y) + ',' + str(z)
    print(tuplaxyz)
    cp.pixels.fill(((R + abs(int(x))), (G + abs(int(y))), (B + abs(int(z)))))
    uart.write(tuplaxyz.encode('utf-8'))
    time.sleep(0.1)
コード例 #13
0
ファイル: code - Copy.py プロジェクト: JWaym0nd/boa
import time
from adafruit_crickit import crickit
import board
import busio
import adafruit_mprls
# may need to import PWMOut via pulseio or, on CP7, pwmio
# for the motor's duty_cycle: 50% recommended.
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

motor_1 = crickit.dc_motor_1
i2c = busio.I2C(board.D6, board.D5)
mpr = adafruit_mprls.MPRLS(i2c, psi_min=0, psi_max=25)  # 25psi = 172kPa

print("Initial pressure (kPa):", mpr.pressure/10)

while True:

    ble.start_advertising(advertisement)
    while not ble.connected:
        pass
    # ble.stop_advertising()

    while ble.connected:
        kPa = mpr.pressure/10
        uart_server.write("{},\n".format(kPa, ))
コード例 #14
0
# Example-code for displaying text transmitted by using the BLE Connect UART
# To use, start this program, and start the Adafruit Bluefruit LE Connect app.
# Connect, and then select UART

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
import digitalio
import busio
import board
import struct
import os
from pl_uc8156 import PL_UC8156

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

# define the pins we will need
clk = board.SCK  # clock
mosi = board.MOSI  # MOSI
miso = board.MISO  # MISO
cs = digitalio.DigitalInOut(board.D5)  # chip-select
rst = digitalio.DigitalInOut(board.D12)  # reset
busy = digitalio.DigitalInOut(board.D9)  # busy

# create the spi-device
spi = busio.SPI(clock=clk, MOSI=mosi, MISO=miso)

# give them all to our driver
display = PL_UC8156(spi=spi, cs_pin=cs, rst_pin=rst, busy_pin=busy)
コード例 #15
0
# common configuration
SERVICE_NAME = "My UART"  # 8 chars max

# setup UART
uart = busio.UART(board.TX, board.RX)

# setup bluetooth
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.color_packet import ColorPacket
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
ble.name = "UART With BLE"
uart_service = UARTService()
advertisement = ProvideServicesAdvertisement(uart_service)
advertisement.short_name = SERVICE_NAME
# advertisement.complete_name = "UART BLE" # no more than 8 to not go into extended adv ?

was_connected = False
while True:
    # Advertise BLE when not connected.
    if not ble.connected:
        was_connected = False

        if not ble.advertising:
            print(f'Start advertising as "{SERVICE_NAME}"')
            ble.start_advertising(advertisement, interval=0.5, timeout=5)

        # dismiss uart buffer when not connected
コード例 #16
0
# BLE stuff
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.color_packet import ColorPacket

#---| User Config |--------------------------------------------------
BLE_NAME = "Candy Heart"
MESSAGE_DELIMITER = ","
MESSAGE_COLOR = 0xFF0000
#---| User Config |--------------------------------------------------

# Setup BLE radio and service
ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)
ble._adapter.name = BLE_NAME  #pylint: disable=protected-access

# Create the display
display = board.DISPLAY

# Load the candy heart BMP
bitmap, palette = adafruit_imageload.load("/images/heart_bw.bmp",
                                          bitmap=displayio.Bitmap,
                                          palette=displayio.Palette)

heart = displayio.TileGrid(bitmap, pixel_shader=palette)

# Set up message text
LINE1_MAX = 9
コード例 #17
0
class Ble():
    def __init__(self, onConnectionStateChanged, onAdvertising=None, onWrite=None):
        self._ble = BLERadio()
        self._uart_server = UARTService()
        self._onAdvertising = onAdvertising
        self._onWrite = onWrite
        self._advertisement = ProvideServicesAdvertisement(self._uart_server)
        self._isAdvertising = False
        self._onAdvertising = onAdvertising
        self._onWrite = onWrite
        self.__oldConnectionState = False
        self._onConnectionStateChanged = onConnectionStateChanged
        self._enabled = False

    def write(self, data):
        if self._ble.connected:
            self._uart_server.write(data)
            if self._onWrite:
                self._onWrite(data)

    def startAdvertising(self):
        if not self._ble.connected:
            self.stopAdvertising()
        self._ble.start_advertising(self._advertisement)
        display("Start Phone App and connect")
        display("Started Advertising to BLE devices")
        if self._onAdvertising:
            self._onAdvertising()
        self._isAdvertising = True

    def stopAdvertising(self):
        # if self._ble.connected:
        display("Stopped Advertising")
        self._ble.stop_advertising()
        self._isAdvertising = False

    def read(self):

        if self._ble.connected != self.__oldConnectionState:
            self._onConnectionStateChanged()

        self.__oldConnectionState = self._ble.connected

    def enable(self):
        self.startAdvertising()
        self._enabled = True

    def disable(self):
        self.stopAdvertising()
        self._enabled = False

    def toggle(self):
        if self._enabled:
            self.disable()
        else:
            self.enable()

    @property
    def isAdvertising(self):
        return self._isAdvertising

    @property
    def connected(self):
        return self._ble.connected

    @property
    def enabled(self):
        return self._enabled
from adafruit_bluefruit_connect.packet import Packet
from jisforjt_cutebot_clue import cutebot, clue


# Used to create random neopixel colors
import random

# Only the packet classes that are imported will be known to Packet.
from adafruit_bluefruit_connect.button_packet import ButtonPacket


######################################################
#   Variables
######################################################
ble = BLERadio()                                            # Turn on Bluetooth
uart_server = UARTService()                                 # Turn on UART
advertisement = ProvideServicesAdvertisement(uart_server)   # Set up notice for other devices that Clue has a Bluetooth UART connection

maxSpeed = 35

clue.sea_level_pressure = 1020                              # Set sea level pressure for Clue's Altitude sensor.

######################################################
#   Main Code
######################################################
while True:
    print("WAITING for BlueFruit device...")
    
    # Advertise when not connected.
    ble.start_advertising(advertisement)                # Tell other devices that Clue has a Bluetooth UART connection.
    while not ble.connected:                            # Check to see if another device has connected with the Clue via Bluetooth.
コード例 #19
0
# SPDX-License-Identifier: MIT

# Basic example for using the BLE Connect UART
# To use, start this program, and start the Adafruit Bluefruit LE Connect app.
# Connect, and then select UART. Any text received FROM the connected device
# will be displayed. Periodically, text is sent TO the connected device.

import time
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

SEND_RATE = 10  # how often in seconds to send text

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

count = 0
while True:
    print("WAITING...")
    # Advertise when not connected.
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass

    # Connected
    ble.stop_advertising()
    print("CONNECTED")

    # Loop and read packets
コード例 #20
0
'''

#导入相关模块
import time
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

#构建蓝牙对象
ble = BLERadio()

#定义广播名称
ble.name='01Studio'

#构建UART服务
Uart_Service = UARTService()

#广播添加UART服务
advertisement = ProvideServicesAdvertisement(Uart_Service)

while True:

    #发起广播
    ble.start_advertising(advertisement)

    #等待连接
    while not ble.connected:
        pass

    #连接蔡成功
    while ble.connected:
コード例 #21
0
        
animations.add_cycle_complete_receiver(random_animation_color)


# After we complete three pulse cycles, return to main animations list
def pulse_finished(anim):
    global current_display
    current_display = animations

pulse.add_cycle_complete_receiver(pulse_finished)
pulse.notify_cycles = 3


# Bluetooth
ble = BLERadio()
uart_service = UARTService()
advertisement = ProvideServicesAdvertisement(uart_service)

# Set charge_mode to True to turn off the LED Animations and Bluetooth
#  e.g. when charging the battery
charge_mode = False

# Checks the ItsyBitsy's switch button
def check_switch():
    global charge_mode
    switch.update()
    if switch.fell:  #Switch changed state
        charge_mode = not charge_mode
        # if display has just been turned off, clear all LEDs, disconnect, stop advertising
        if charge_mode:
            pixels.fill((0,0,0))
コード例 #22
0
import time
import board
import analogio
# import adafruit_thermistor
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_circuitplayground import cp

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

# thermistor = adafruit_thermistor.Thermistor(board.TEMPERATURE,
#                                             10000, 10000, 25, 3950)
# light = analogio.AnalogIn(board.LIGHT)


def scale(value):
    """Scale the light sensor values from 0-65535 (AnalogIn range)
    to 0-50 (arbitrarily chosen to plot well with temperature)"""
    return value / 65535 * 50


while True:
    # Advertise when not connected.
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass
    ble.stop_advertising()
コード例 #23
0
# Basic example for using the BLE Connect UART
# To use, start this program, and start the Adafruit Bluefruit LE Connect app.
# Connect, and then select UART
import time
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

fw_ver = "Riedon_BLE_UARTrev1.py"

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)

# Create the ADS object
# ads = ADS.ADS1015(i2c)
ads = ADS.ADS1115(i2c)

# Create differential channel on Pin 0 and Pin 1
chan = AnalogIn(ads, ADS.P0, ADS.P1)

# Create a sinlge ended channel on Pin 0
#   Max counts for ADS1015 = 2047
#                  ADS1115 = 32767
コード例 #24
0
ファイル: test_juggle_accel.py プロジェクト: dburhanna/test
import board
import time
import math

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.button_packet import ButtonPacket
from adafruit_circuitplayground import cp

ble = BLERadio()
ble.name = "JuggleCounter"
uart = UARTService()

advertisement = ProvideServicesAdvertisement(uart)

while True:
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass

    # Now we're connected

    while ble.connected:
        if uart.in_waiting:
            recvd = uart.read(32)
            if recvd is not None:
                # convert bytearray to string
コード例 #25
0
"""
Used with ble_uart_echo_client.py. Receives characters from the UARTService and transmits them back.
"""

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

while True:
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass
    while ble.connected:
        # Returns b'' if nothing was read.
        one_byte = uart.read(1)
        if one_byte:
            print(one_byte)
            uart.write(one_byte)
コード例 #26
0
ファイル: code.py プロジェクト: ECE492CHDS1/CHDS
# onboard blue LED
blue_led = DigitalInOut(board.BLUE_LED)
blue_led.direction = Direction.OUTPUT

# setup for BLE
ble = BLERadio()
ble.name = "CoDi"
if ble.connected:
    for c in ble.connections:
        c.disconnect()

advertisement = ProvideServicesAdvertisement()

# add device info service and UART service for BLE to advertise
device_info_service = DeviceInfoService(manufacturer="CoDi Co.")
uart_service = UARTService()
advertisement.services.append(device_info_service)
advertisement.services.append(uart_service)


# function for haptic motor vibration
# num: # of times to vibrate
# duration: duration of vibration
# delay: time between vibrations
def vibrate(num, duration, delay):
    # 16 is the vibration effect being used for the haptic motor
    drv.sequence[0] = adafruit_drv2605.Effect(16)
    for _ in range(0, num):
        drv.play()  # start vibration
        time.sleep(duration)
        drv.stop()  # stop vibration
コード例 #27
0
import board
import neopixel

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.color_packet import ColorPacket

ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)

while True:
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass

    # Now we're connected

    while ble.connected:
        if uart.in_waiting:
            packet = Packet.from_stream(uart)
            if isinstance(packet, ColorPacket):
                # Change the NeoPixel color.
                pixel.fill(packet.color)

    # If we got here, we lost the connection. Go up to the top and start
コード例 #28
0
from digitalio import DigitalInOut, Direction, Pull

import adafruit_imageload
import adafruit_bme680
import adafruit_lsm9ds1
from adafruit_apds9960 import apds9960
from adafruit_display_shapes.rect import Rect
import displayio
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from _bleio import BluetoothError

# Initialize Bluetooth globals
ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

# Turn on the LCD backlight and enable the display
display = board.DISPLAY
# Override brightness to save power
display.auto_brightness = False
display.brightness = 0.2

print('Hello!')


def display_image(filename):
    img, img_palette = adafruit_imageload.load(filename,
                                               bitmap=displayio.Bitmap,
                                               palette=displayio.Palette)
コード例 #29
0
# Print out the color data from ColorPackets.
# To use, start this program, and start the Adafruit Bluefruit LE Connect app.
# Connect, and then select colors on the Controller->Color Picker screen.

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_bluefruit_connect.packet import Packet
# Only the packet classes that are imported will be known to Packet.
from adafruit_bluefruit_connect.color_packet import ColorPacket

ble = BLERadio()
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

while True:
    # Advertise when not connected.
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass

    while ble.connected:
        packet = Packet.from_stream(uart_server)
        if isinstance(packet, ColorPacket):
            print(packet.color)
コード例 #30
0
class Aquarium:
    def __init__(self):
        # Set up watchdog timer
        self.watchdog = microcontroller.watchdog
        self.watchdog.deinit()
        self.watchdog.timeout = WATCHDOG_TIMEOUT
        self.watchdog.mode = WATCHDOG_MODE

        # Set up heartbeat output (i.e red LED)
        self._heartbeat = digitalio.DigitalInOut(HEARTBEAT_PIN)
        self._heartbeat.direction = digitalio.Direction.OUTPUT
        self._heartbeat_duration = HEARTBEAT_DURATION

        # Set up I2C bus
        i2c = busio.I2C(board.SCL, board.SDA)
        # Set up SPI bus
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

        # Set up real time clock as source for time.time() or time.localtime() calls.
        print("Initialising real time clock.\n\n\n\n")
        clock = PCF8523(i2c)
        rtc.set_time_source(clock)

        print("Initialising display.\n\n\n\n")
        self.display = Display(self, DISPLAY_TIMEOUT, i2c, spi)

        print("Initialising lights.\n\n\n\n")
        self.lights = Lights(LIGHTS_ON_TIME, LIGHTS_OFF_TIME, LIGHTS_ENABLE_PIN, LIGHTS_DISABLE_PIN)

        print("Initialising feeder.\n\n\n\n")
        self.feeder = Feeder(FEEDING_TIMES, PORTIONS_PER_MEAL, FEEDER_MOTOR, FEEDER_STEPS_PER_ROTATION,
                             FEEDER_STEP_DELAY, FEEDER_STEP_STYLE, i2c)

        print("Initialising temperature sensors.\n\n\n\n")
        ow_bus = OneWireBus(OW_PIN)
        self.water_sensor = TemperatureSensor(ow_bus, WATER_SN, WATER_OFFSET)
        self.air_sensor = TemperatureSensor(ow_bus, AIR_SN, AIR_OFFSET)

        # Set up SD card
        print("Setting up logging.\n\n\n\n")
        cs = digitalio.DigitalInOut(SD_CS)
        sdcard = SDCard(spi, cs)
        vfs = storage.VfsFat(sdcard)
        storage.mount(vfs, "/sd")
        self._log_data = LOG_DATA
        self._log_interval = time_tuple_to_secs(LOG_INTERVAL)
        self._last_log = None

        print("Initialising Bluetooth.\n\n\n\n")
        self._ble = BLERadio()
        self._ble._adapter.name = BLE_NAME
        self._ble_uart = UARTService()
        self._ble_ad = ProvideServicesAdvertisement(self._ble_uart)

    def heartbeat(self):
        self.watchdog.feed()
        self._heartbeat.value = True
        time.sleep(self._heartbeat_duration)
        self._heartbeat.value = False

    def update_temps(self):
        self.water_temp = self.water_sensor.temperature
        self.air_temp = self.air_sensor.temperature

    def update_log(self):
        if not self._log_data:
            return

        if self._last_log:
            last_log_secs = time_struct_to_secs(self._last_log)
            current_secs = time_struct_to_secs(self._now)
            if current_secs - last_log_secs < self._log_interval:
                return

        print("Updating log:")
        datestamp, timestamp, log_line = self._get_status_strings()
        filename = datestamp + ".log"
        print(filename)
        print(log_line)
        with open("/sd/scales_logs/" + filename, mode="at", buffering=1) as logfile:
            logfile.write(log_line + "\n")
        self._last_log = self._now
        self._last_log = self._now
        print("Done.\n")

    def blelele(self):
        if not self._ble.connected:
            # Not connected, so make sure we're advertising for connections.
            try:
                self._ble.start_advertising(self._ble_ad)
            except BluetoothError:
                # Already advertising. Probably.
                pass
            return

        if self._ble_uart.in_waiting:
            # There's a command waiting.
            ble_command = self._ble_uart.readline()
            if ble_command:
                # First echo command, then respond.
                self._ble_uart.write(ble_command + b'\n')
                self._ble_respond(ble_command)

    def run_once(self):
        self.heartbeat()
        self._now = time.localtime()
        self.lights.update()
        self.feeder.update()
        self.update_temps()
        self.display.update()
        self.update_log()
        self.blelele()
        time.sleep(1)

    def run(self):
        while True:
            self.run_once()

    def _ble_respond(self, ble_command):
        if ble_command == b"v?":
            response = bytes(f"{BLE_NAME} v{__version__}\n", 'ascii')
        elif ble_command == b"s?":
            _, _, response = self._get_status_strings()
            response = bytes(response, 'ascii')
        elif ble_command == b"f?":
            response = f"{self.feeder.feeding_times}, {self.feeder.portions_per_meal}"
            response = bytes(response, 'ascii')
        elif ble_command == b"ff":
            self.feeder.feed()
            response = bytes("Fed 1 portion.", 'ascii')
        elif len(ble_command) > 2 and ble_command[:2] == b"fp":
            portions = int(str(ble_command[2:], 'ascii'))
            self.feeder.portions_per_meal = portions
            response = bytes(f"Set portions per meal to {portions}.", 'ascii')
        else:
            command = str(ble_command, 'ascii')
            response = bytes("ERROR: Invalid command '{}'\n".format(command), 'ascii')

        self._ble_uart.write(response)

    def _get_status_strings(self):
        datestamp = "{:04d}-{:02d}-{:02d}".format(self._now.tm_year, self._now.tm_mon, self._now.tm_mday)
        timestamp = datestamp + "T{:02d}:{:02d}:{:02d}".format(self._now.tm_hour, self._now.tm_min, self._now.tm_sec)
        status = "{}, {:d}, {:7.4f}, {:7.4f}".format(timestamp, self.lights.is_enabled, self.water_temp, self.air_temp)
        return datestamp, timestamp, status