示例#1
0
        pass
    while ble.connected:
        #        one_byte = uart_server.read(threshold_value)
        #        uart_server.write(one_byte)
        x, y, z = [
            value / adafruit_lis3dh.STANDARD_GRAVITY
            for value in lis3dh.acceleration
        ]
        print("x = %0.3f G, y = %0.3f G, z = %0.3f G" % (x, y, z))
        x_str = str(x)
        y_str = str(y)
        time.sleep(0.1)
        tilt = threshold(y, yInit)
        print("getTilt = ", tilt)
        tilt_value = tiltIndicator(tilt)
        uart_server.write('Euler angle: {}'.format(sensor.euler))
        packet = Packet.from_stream(uart_server)
        print('Euler angle: {}'.format(sensor.euler))
        #        if isinstance(packet, AccelerometerPacket):
        #            print(packet.x, packet.y, packet.z)
        #            time.sleep(0.1)
        if (isinstance(packet, LocationPacket) & tilt == 1):
            print(packet.latitude, packet.longitude)
            time.sleep(2)
            lat = str(packet.latitude)
            longt = str(packet.longitude)
            alti = str(packet.altitude)
            #            uart_server.write(lat + ',' + longt + alti + '\n')
            getTilt = 0

    while True:
示例#2
0
while True:
    # Advertise when not connected.
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass
    ble.stop_advertising()

    while ble.connected:
        if cp.button_a:
            print("Button A pressed!")
            cp.red_led = False
            cp.pixels.fill(0xFF0000)
            cp.play_tone(1000, 0.5)
            b_a = 100
        else:
            b_a = 0

        if cp.button_b:
            print("Button B pressed!")
            cp.red_led = True
            cp.pixels.fill(0)
            b_b = 100
        else:
            b_b = 0

        time.sleep(0.1)
        print((cp.light, cp.temperature, b_a, b_b))
        uart_server.write("{}, {}, {}, {}\n".format(cp.light, cp.temperature,
                                                    b_a, b_b))
        time.sleep(0.1)
    # Connected
    ble.stop_advertising()
    print("CONNECTED")

    # Loop and read ADC, print and send data over bluetooth
    while ble.connected:
        print("Firmware =", fw_ver)
        #ext = 33
        #
        # set timestamp to accompany sensor data
        now = time.monotonic()
        print("time= ", now)
        # read ADS1115 adc value and voltage
        adc_cnt = chan.value
        adc_volt = chan.voltage
        print('{:5} {:5.3f}'.format(adc_cnt, adc_volt), end='')
        print()
        #uart_server.write("testing/")
        #ads.gain = 2
        print("channel value= ", adc_cnt)
        # calculate SSA-100 current
        i_SSA = (adc_cnt / 32767) * 170.7
        print("current = ", i_SSA)
        print(' ADC count= {:5} voltage = {:5.3f}\n'.format(adc_cnt, adc_volt))
        # send current reading over bluetooth UARTService
        uart_server.write('{:5.1f}\n'.format(i_SSA))
        time.sleep(0.1)

    # Disconnected
    print("DISCONNECTED")
示例#4
0
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)
                    solenoid.value = False

        led_intensity = led.value  # Check blue LED detector intensity
        led_on = led_intensity > 1000
        # Color: red = off, green = on
        color_packet = ColorPacket((255 * int(not led_on), 255 * led_on, 0))
        try:
            uart.write(color_packet.to_bytes())  # Transmit state color
        except OSError:
            pass

        sleep(.2)
示例#5
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
示例#6
0
    # Now we're connected
    print ("Connected");
    pixels.fill(GREEN)

    connections = ble.connections
    device = connections[0]

    while ble.connected:
        if uart.in_waiting:
            # Read the packet
            command = int.from_bytes(uart.read(1), "little")
            length =int.from_bytes(uart.read(1), "little")
            data = uart.read(length)
            tup = (command, length, data)

            # Create the command object
            req = BugCommandFactory.CreateFromTuple(tup)

            # act upon the command object
            if isinstance(req, EchoRequest):
                print("Requested to echo: " + req.getMessage())
                res = EchoResponse(req.getMessage())
                uart.write(res.getDataBytes())
            elif isinstance(req, EchoResponse):
                print("Response: " + req.getMessage())
        pass

    print("Lost connection")
    pixels.fill(RED)
    time.sleep(2)
示例#7
0
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, ))
        print(kPa)
        # time.sleep(3.0)
        # kPa_tx = uart_server.read()
        # print(kPa_tx)

        if kPa > 96.5266 and kPa <= 172.3600:
            # print((kPa, ))
            motor_1.throttle = 0.0
            # time.sleep(1.0)
        elif 0 < kPa <= 96.5266:
            # print((kPa, ))
            motor_1.throttle = 1.0
            # time.sleep(1.0)
        else:
            # print((kPa, ))
示例#8
0
                if s == 'ok':
                    display_image('/ok.bmp')
                if s == 'cancel':
                    display_image('/cancel.bmp')
                if s == 'bluetooth':
                    display_image('/bluetooth.bmp')
                if s == 'green':
                    group = displayio.Group()
                    group.append(Rect(0, 0, 240, 240, fill=0x00FF00))
                    display.show(group)
                if s == 'red':
                    group = displayio.Group()
                    group.append(Rect(0, 0, 240, 240, fill=0xFF0000))
                    display.show(group)
                if s == 'blue':
                    group = displayio.Group()
                    group.append(Rect(0, 0, 240, 240, fill=0x0000FF))
                    display.show(group)
        # Check the buttons
        if not buttons[0] and _buttons[0]:
            uart.write(b'buttonA\n')
        if not buttons[1] and _buttons[1]:
            uart.write(b'buttonB\n')
        if not buttons[2] and _buttons[2]:
            uart.write(b'buttonC\n')
        if not buttons[3] and _buttons[3]:
            uart.write(b'buttonD\n')
    _buttons = buttons
    if not ble.connected:
        display.show(None)
示例#9
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
示例#10
0
            multstage += 1

    lightcolor = multcolors[multstage]
    contacts_per_light = multipliers[multstage]

    for i in range(10):
        if num_contacts > i * contacts_per_light:
            pixels[i] = multcolors[i]
        else:
            pixels[i] = (0, 0, 0)

    pixels.show()

    # update Bluefruit Connect
    if radio.connected:
        was_connected = True
        uart_server.write(debug_text.encode())
        if uart_server.in_waiting:
            raw_bytes = uart_server.read(uart_server.in_waiting)
            text = raw_bytes.decode().strip()
            print("RX:", text)
            if '143.all' in text:
                outstr = 'all uniques:\n'
                for i, addr in enumerate(sorted(list(unique_contacts))):
                    outstr += ' {}: {}\n'.format(i, addrs_to_hex([addr]))
                uart_server.write(outstr.encode())
    elif was_connected:
        was_connected = False
        radio.start_advertising(advertisement)

    #debug_test+=50
示例#11
0
ble = BLERadio()
ble.name = "yourUniqueName"
uart_server = UARTService()
advertisement = ProvideServicesAdvertisement(uart_server)

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

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

    while ble.connected:
        packet = Packet.from_stream(uart_server)
        if isinstance(packet, ColorPacket):
            if packet.color != None:
                # display packet that came in from computer
                print(packet.color)
                print(packet.to_bytes())
                # set all NeoPixels to the received color
                pixels.fill(packet.color)
                # send the current light value
                brightness = light.value
                message = str(brightness)
                uart_server.write(message)
                print(message)
示例#12
0
class Room:
    def __init__(self, use_debug=False):
        self.use_debug = use_debug
        self.subscription_ids = {}
        self.subscription_messages_on_reconnect = []
        self.ble = BLERadio()
        self.uart_server = UARTService()
        self.advertisement = ProvideServicesAdvertisement(self.uart_server)
        self.chunk_size = 20  # adafruit_ble can only write in 20 byte chunks
        self.recv_msg_cache = ""
    
    def debug(self, msg):
        if self.use_debug:
            print(msg)

    def cleanup(self):
        self.uart_server.write('~:\n'.encode("utf-8"))

    def claim(self, claim_str):
        # Cleanup claim = cleanup all previous claims
        self.uart_server.write('N:{}\n'.format(claim_str).encode("utf-8"))
    
    def when(self, query_strings, callback):
        x = str(random.randint(0, 9999))
        subscription_id = '0'*(4-len(x)) + x  # like 0568
        self.subscription_ids[subscription_id] = callback
        # S:0568:$ $ value is $x::$ $ $x is open
        x = 'S:{}:{}\n'.format(subscription_id, '::'.join(query_strings)).encode("utf-8")
        self.subscription_messages_on_reconnect.append(x)
    
    def parse_results(self, val):
        self.debug("parsing results: {}".format(val))
        result_vals = val[1:-1].split("},{")
        results = []
        for result_val in result_vals:
            result = {}
            rvs = result_val.split(",")
            for rv in rvs:
                kv = rv.strip().split(":")
                result[kv[0].replace('"', '').replace("'", '')] = kv[1].strip()
            results.append(result)
        return results
    
    def check_read_msg_cache_and_callbacks(self):
        lines = self.recv_msg_cache.split("\n")
        self.debug("lines: {}".format(lines))
        if len(lines) > 1:
            # trim off the last line (either '' if \n is the last char or a partial string)
            # because it is not part of a string that ends in a \n
            full_lines = lines[:-1]
            for line_msg in full_lines:
                self.debug("Proccesing new sub update: {}".format(line_msg))
                # 1234[{x:"5",y:"1"},{"x":1,"y":2}]
                sub_id = line_msg[:4] # first four characters of message are sub id
                val = line_msg[4:]
                if sub_id not in self.subscription_ids:
                    print("Unknown sub id {}".format(sub_id))
                    continue
                callback = self.subscription_ids[sub_id]
                callback(self.parse_results(val))
            self.recv_msg_cache = lines[-1]

    def listen_and_update_subscriptions(self):
        # self.debug("listening~~~~~")
        if self.uart_server.in_waiting:
            read_msg = self.uart_server.read(self.uart_server.in_waiting)
            self.recv_msg_cache += read_msg.decode("utf-8")
            self.check_read_msg_cache_and_callbacks()
            self.debug("sub update: {}".format(self.recv_msg_cache))

    def connected(self):
        if not self.ble.connected:
            # Advertise when not connected.
            print("BLE not connected, advertising...")
            self.ble.start_advertising(self.advertisement)
            while not self.ble.connected:
                pass
            self.ble.stop_advertising()
            print("BLE now connected")
            time.sleep(1.0)  # Give BLE connector time setup before sending data
            for sub_msg in self.subscription_messages_on_reconnect:
                self.debug("Sending sub message: {}".format(sub_msg))
                self.uart_server.write(sub_msg)
        self.listen_and_update_subscriptions()
        return True
示例#13
0
文件: code.py 项目: 5BDL/PatsA.S.S.
    #        uart_addresses = uart_client.scan(scanner)
    while not ble.connected:
        pass
    while ble.connected:
        #        one_byte = uart_server.read(threshold_value)
        #        uart_server.write(one_byte)
        x, y, z = [
            value / adafruit_lis3dh.STANDARD_GRAVITY
            for value in lis3dh.acceleration
        ]
        print("x = %0.3f G, y = %0.3f G, z = %0.3f G" % (x, y, z))
        x_str = str(x)
        y_str = str(y)
        time.sleep(0.1)
        tilt = threshold(y, yInit)
        print("getTilt = ", tilt)
        tilt_value = tiltIndicator(tilt)
        uart_server.write(x_str + ',' + y_str + ',' + tilt_value + '\n')
        packet = Packet.from_stream(uart_server)
        #        if isinstance(packet, AccelerometerPacket):
        #            print(packet.x, packet.y, packet.z)
        #            time.sleep(0.1)
        if (isinstance(packet, LocationPacket) & tilt == 1):
            print(packet.latitude, packet.longitude)
            time.sleep(2)
            lat = str(packet.latitude)
            longt = str(packet.longitude)
            alti = str(packet.altitude)
            #            uart_server.write(lat + ',' + longt + alti + '\n')
            getTilt = 0
示例#14
0
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
                data_string = ''.join([chr(b) for b in recvd])
                print(data_string, end="")
                uart.write(data_string)
            if "Juggle" in data_string:
                uart.write("enter target")
                recvd = None
                while not uart.in_waiting:
                    print("getting target value")
                    time.sleep(1)
                recvd = uart.read(32)
                juggle_target = ''.join([chr(b) for b in recvd])
                print(juggle_target, end="")
                uart.write(juggle_target)

                uart.write("Counting juggles...")
                count = 0
                while count < int(juggle_target):
示例#15
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)
示例#16
0
文件: code.py 项目: ECE492CHDS1/CHDS
    print("Connected")

    # for connection in ble.connections:
    #     if connection.connected:
    #         if not connection.paired:
    #             #  pairs to phone
    #             connection.pair(bond=True)
    #             print("Paired")

    while ble.connected:
        if uart_service.in_waiting:
            line = uart_service.readline()
            command = line.strip().decode('utf-8')
            print("Command: " + command)

            if command == 'alert':
                pixel.fill(color.CYAN)
                pixel.show()
                vibrate(1, 0.5, 0)

            pixel.fill(color.BLUE)
            pixel.show()

            uart_service.write(line)

    # if BLE becomes disconnected then blue LED turns off
    # and BLE begins advertising again to reconnect
    blue_led.value = False
    print("Disconnected")
    print()
示例#17
0
            if pwm_on:
                led.duty_cycle = int((100 - pct) * 65535 / 100)

        if not pwm_on:
            if (time.monotonic() - pwm_indicate_time >
                    PWM_INDICATE_BLINK_INTERVAL):
                pwm_indicate_time = time.monotonic()
                blink_pct = 0
                pwm_indicate_count += 1
                if pwm_indicate_count < PWM_INDICATE_BLINKS * 2:
                    if pwm_indicate_count % 2 == 1:
                        blink_pct = 100
                    led.duty_cycle = int((100 - blink_pct) * 65535 / 100)
                else:
                    pwm_on = True
                    led.duty_cycle = int((100 - pct) * 65535 / 100)

        if pi_gen_on and time.monotonic() - last_pi_send > PI_SEND_INTERVAL:
            text = "DIGIT = {}\r\n".format(next(pi_digits))
            uart_service.write(text.encode())
            last_pi_send = time.monotonic()

        button.update()
        if button.fell:
            pi_gen_on = not pi_gen_on
            pwm_on = False

            pwm_indicate_time = time.monotonic()
            pwm_indicate_count = 0
            led.duty_cycle = 65535
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
        if uart.in_waiting:
            uart.reset_input_buffer()

    else:
        if not was_connected:
            was_connected = True
            print("Connected")
            ble.stop_advertising()

        # pass-through uart data when connected
        if nbytes := uart.in_waiting:
            # data = uart.read(nbytes)
            data = uart.readline()
            if data:
                print("Broadcasting", data)
                uart_service.write(data)

    time.sleep(0.1)
示例#19
0
            print("Down")
            message = "Down"
            while y.value in range(MAX - THRESHOLD, MAX):
                pass
        elif buttonJ.value == 0:
            print("J")
            message = "J"
            while buttonJ.value == 0:
                pass
        elif buttonA.value == 0:
            print("A")
            message = "A"
            while buttonA.value == 0:
                pass

        elif buttonB.value == 0:
            print("B")
            message = "B"
            while buttonB.value == 0:
                pass
        else:
            message = "None"

        if message != "None":
            uart.write((message + "\n").encode("utf-8"))
    '''
  ble.start_advertising(advertisement)
  while not ble.connected:
  	pass
  '''
示例#20
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
    last_send = time.monotonic()
    while ble.connected:
        # INCOMING (RX) check for incoming text
        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("RX:", text)
        # OUTGOING (TX) periodically send text
        if time.monotonic() - last_send > SEND_RATE:
            text = "COUNT = {}\r\n".format(count)
            print("TX:", text.strip())
            uart_server.write(text.encode())
            count += 1
            last_send = time.monotonic()

    # Disconnected
    print("DISCONNECTED")
示例#21
0
while True:
    # When not connected via BLERadio
    ble.start_advertising(advertisement)
    while not ble.connected:
        Stemp = ss.get_temp(
        )  # read soil temperature from the temperature sensor
        Smoist = ss.moisture_read(
        )  # read soil moisture level through capacitive touch pad

        # share data via serial
        print(("temp: " + str(Stemp) + "  moisture: " + str(Smoist)))
        time.sleep(1)
    ble.stop_advertising()

    # When connected via BLERadio
    while ble.connected:
        Stemp = ss.get_temp(
        )  # read soil temperature from the temperature sensor
        Smoist = ss.moisture_read(
        )  # read soil moisture level through capacitive touch pad

        # share data via serial, and BLERadio (UART & Plotter)
        x = Stemp
        y = Smoist
        print("Broadcasting via BLEradio")
        print(("soil temp: " + str(x) + "  soil moisture: " + str(y)))
        uart_server.write("{},{}\n".format("soil temp: " + str(Stemp),
                                           " soil moisture: " + str(Smoist)))
        NeoPixelPattern()
        time.sleep(1)
示例#22
0
        now = time.monotonic()
        print("time= ",now)
        # read ADS1115 adc value and voltage
        adc_cnt = chan.value
        adc_volt = chan.voltage
        print('{:5} {:5.3f}'.format(adc_cnt, adc_volt), end='')
        #for gain in gains[1:]:
        #    ads.gain = gain
        #    print("ads.gain= ", ads.gain)
        #    print(' | {:5} {:5.3f}'.format(chan.value, chan.voltage), end='')
        #print()
        #uart_server.write("testing/")
        #ads.gain = 2
        print("adc count= ", adc_cnt)
        # calcuate current thru SSA-100
        i_SSA = (adc_cnt/32767) * 170.7
        print ("SSA-100 current = ", i_SSA)
        print(' count= {:5} voltage = {:5.3f}\n'.format(adc_cnt, adc_volt))
        #uart_server.write('{},{}\n'.format(chan.value, small))
        #uart_server.write(b'55uuhh\n')
        time.sleep(1.0)
        # send adc count and voltage
        uart_server.write('ADC count={:5} value={:5.3f} volts\n'.format(adc_cnt, adc_volt))
        time.sleep(0.1)
        # send elapsed time and current
        uart_server.write('elapsed time={:5.0f} value={:5.1f} amps\n'.format(now, i_SSA))
        time.sleep(0.5)

    # Disconnected
    print("DISCONNECTED")
# 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"))
示例#24
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)
示例#25
0
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:

        # 读取128个字节数据,如果没数据,则返回 b''
        one_byte = Uart_Service.read(128)

        #收到信息,REPL打印并回发
        if one_byte:
            print(one_byte)
            Uart_Service.write(one_byte)
示例#26
0
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()

    while ble.connected:
        print((scale(light.value), thermistor.temperature))
        uart_server.write('{},{}\n'.format(scale(light.value),
                                           thermistor.temperature))
        time.sleep(0.1)
示例#27
0
 ble.start_advertising(advertisement)  # Start advertising.
 was_connected = False
 last_send = time.monotonic()
 while not was_connected or ble.connected:
     if rainbow:
         pixels.fill((0,155,155))
     if ble.connected:  # If BLE is connected...
         if not was_connected:
             print('connected')
             ble.stop_advertising()
             was_connected = True
             #flag = 0
         if touch_A2.value and time.monotonic() - last_send > SEND_RATE:
             print(touch_A2.value)
             print("A2 touched")
             uart_server.write('Checked-in!')
             #touch_A1.deinit()
             #touch_A1 = touchio.TouchIn(board.A1)
             last_send = time.monotonic()
             pixels.fill((255,0,255))
             rainbow = False
             print(last_send)
             time.sleep(0.1)
         #print("Outside loop")
     #uart_server.write('Checked-in!')
                 #flag = 1
         # receive
         if uart_server.in_waiting:
             print("Inside uart_server")
                 # note that the reading won't stop until buffer's full
             pkt = uart_server.read(20) # adjust buffer size as needed