#hail mary BLE SPI test import machine import pyb import utime import micropython from micropython import const from machine import Pin spi = machine.SPI(3, baudrate=8000000, polarity=0, phase=0, bits=8, firstbit=machine.SPI.MSB) CS=Pin('D13',Pin.OUT_PP, pull=Pin.PULL_NONE) CS.on() RS=Pin('A8',Pin.OUT_PP, pull=Pin.PULL_NONE) RS.on() _READ_HEADER_MASTER = b'\x0B\x00\x00\x00\x00' _WRITE_HEADER_MASTER = b'\x0A\x00\x00\x00\x00' HCI_READ_PACKET_SIZE = const(128) IR=Pin('E6',Pin.IN, pull=Pin.PULL_DOWN) class CSContext(object): def __init__(self, pin): self._pin = pin def __enter__(self): # Assert CS line self._pin.off() def __exit__(self, exc_type, exc_value, traceback): # Release CS line self._pin.on() #return all(map(lambda x: x is None, [exc_type, exc_value, traceback])) def write(retry=5, header=b'\x10\x03', param=0): """ Write packet to BlueNRG-MS module """ _rw_header_slave = bytearray(len(_WRITE_HEADER_MASTER)) result = None while retry: with CSContext(CS): # Exchange header spi.write_readinto( _WRITE_HEADER_MASTER, _rw_header_slave ) rx_write_bytes = _rw_header_slave[1] rx_read_bytes = ( _rw_header_slave[4] << 8 ) | _rw_header_slave[3] if _rw_header_slave[0] == 0x02 and ( rx_write_bytes > 0 or rx_read_bytes > 0): # SPI is ready if header: # avoid to write more data that size of the buffer if rx_write_bytes >= len(header): result = bytearray(len(header)) spi.write_readinto(header, result) if param: rx_write_bytes -= len(header) # avoid to read more data that size of the # buffer if len(param) > rx_write_bytes: tx_bytes = rx_write_bytes else: tx_bytes = len(param) result = bytearray(tx_bytes) spi.write_readinto(param, result) break else: break else: break else: break else: utime.sleep_us(50) retry -= 1 return result def read(size=HCI_READ_PACKET_SIZE, retry=5): """ Read packet from BlueNRG-MS module """ result = None _rw_header_slave = bytearray(len(_WRITE_HEADER_MASTER)) while retry: with CSContext(CS): # Exchange header spi.write_readinto( _READ_HEADER_MASTER, _rw_header_slave ) rx_read_bytes = ( _rw_header_slave[4] << 8 ) | _rw_header_slave[3] if _rw_header_slave[0] == 0x02 and rx_read_bytes > 0: # SPI is ready # avoid to read more data that size of the buffer if rx_read_bytes > size: rx_read_bytes = size data = b'\xFF' * rx_read_bytes result = bytearray(rx_read_bytes) spi.write_readinto(data, result) break else: utime.sleep_us(50) retry -= 1 # Add a small delay to give time to the BlueNRG to set the IRQ pin low # to avoid a useless SPI read at the end of the transaction utime.sleep_us(150) return result def run(): write() #retry=5, header=b'\x10\x03', param=0) while True: utime.sleep_us(12) if (IR.value() == 1): hi = read(size=HCI_READ_PACKET_SIZE, retry=5) print(hi) break utime.sleep_us(25)