ble_demo_central.py
1 """ 2 Demonstration of a Bluefruit BLE Central for Circuit Playground Bluefruit. Connects to the first BLE 3 UART peripheral it finds. Sends Bluefruit ColorPackets, read from three accelerometer axis, to the 4 peripheral. 5 """ 6 7 import time 8 9 import board 10 import busio 11 import digitalio 12 import adafruit_lis3dh 13 import neopixel 14 15 from adafruit_bluefruit_connect.color_packet import ColorPacket 16 17 from adafruit_ble import BLERadio 18 from adafruit_ble.advertising.standard import ProvideServicesAdvertisement 19 from adafruit_ble.services.nordic import UARTService 20 21 22 def scale(value): 23 """Scale an value from (acceleration range) to 0-255 (RGB range)""" 24 value = abs(value) 25 value = max(min(19.6, value), 0) 26 return int(value / 19.6 * 255) 27 28 29 i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) 30 int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) 31 accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) 32 accelerometer.range = adafruit_lis3dh.RANGE_8_G 33 34 neopixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.1) 35 36 ble = BLERadio() 37 38 uart_connection = None 39 # See if any existing connections are providing UARTService. 40 if ble.connected: 41 for connection in ble.connections: 42 if UARTService in connection: 43 uart_connection = connection 44 break 45 46 while True: 47 if not uart_connection: 48 print("Scanning...") 49 for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=5): 50 if UARTService in adv.services: 51 print("found a UARTService advertisement") 52 uart_connection = ble.connect(adv) 53 break 54 # Stop scanning whether or not we are connected. 55 ble.stop_scan() 56 57 while uart_connection and uart_connection.connected: 58 r, g, b = map(scale, accelerometer.acceleration) 59 60 color = (r, g, b) 61 neopixels.fill(color) 62 color_packet = ColorPacket(color) 63 try: 64 uart_connection[UARTService].write(color_packet.to_bytes()) 65 except OSError: 66 try: 67 uart_connection.disconnect() 68 except: # pylint: disable=bare-except 69 pass 70 uart_connection = None 71 time.sleep(0.3)