bluefruitspi_simpletest.py
1 # A simple echo test for the Feather M0 Bluefruit 2 # Sets the name, then echo's all RX'd data with a reversed packet 3 4 import time 5 import busio 6 import board 7 from digitalio import DigitalInOut 8 from adafruit_bluefruitspi import BluefruitSPI 9 10 spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) 11 cs = DigitalInOut(board.D8) 12 irq = DigitalInOut(board.D7) 13 rst = DigitalInOut(board.D4) 14 bluefruit = BluefruitSPI(spi_bus, cs, irq, rst, debug=False) 15 16 # Initialize the device and perform a factory reset 17 print("Initializing the Bluefruit LE SPI Friend module") 18 bluefruit.init() 19 bluefruit.command_check_OK(b"AT+FACTORYRESET", delay=1) 20 21 # Print the response to 'ATI' (info request) as a string 22 print(str(bluefruit.command_check_OK(b"ATI"), "utf-8")) 23 24 # Change advertised name 25 bluefruit.command_check_OK(b"AT+GAPDEVNAME=BlinkaBLE") 26 27 while True: 28 print("Waiting for a connection to Bluefruit LE Connect ...") 29 # Wait for a connection ... 30 dotcount = 0 31 while not bluefruit.connected: 32 print(".", end="") 33 dotcount = (dotcount + 1) % 80 34 if dotcount == 79: 35 print("") 36 time.sleep(0.5) 37 38 # Once connected, check for incoming BLE UART data 39 print("\n *Connected!*") 40 connection_timestamp = time.monotonic() 41 while True: 42 # Check our connection status every 3 seconds 43 if time.monotonic() - connection_timestamp > 3: 44 connection_timestamp = time.monotonic() 45 if not bluefruit.connected: 46 break 47 48 # OK we're still connected, see if we have any data waiting 49 resp = bluefruit.uart_rx() 50 if not resp: 51 continue # nothin' 52 print("Read %d bytes: %s" % (len(resp), resp)) 53 # Now write it! 54 print("Writing reverse...") 55 send = [] 56 for i in range(len(resp), 0, -1): 57 send.append(resp[i - 1]) 58 print(bytes(send)) 59 bluefruit.uart_tx(bytes(send)) 60 61 print("Connection lost.")