2 `bitbangio` - Bitbanged bus protocols
 
   3 ==============================================================
 
   5 See `CircuitPython:bitbangio` in CircuitPython for more details.
 
  10 from adafruit_blinka import Lockable, agnostic
 
  14     def __init__(self, scl, sda, frequency=400000):
 
  15         if agnostic.microcontroller == "stm32":
 
  16             raise NotImplementedError("No software I2C on {}".format(agnostic.board))
 
  17         self.init(scl, sda, frequency)
 
  19     def init(self, scl, sda, frequency):
 
  20         from machine import Pin
 
  21         from machine import I2C as _I2C
 
  23         id = -1  # force bitbanging implementation - in future introspect platform if SDA/SCL matches hardware I2C
 
  24         self._i2c = _I2C(id, Pin(scl.id), Pin(sda.id), freq=frequency)
 
  29         except AttributeError:
 
  35     def __exit__(self, exc_type, exc_value, traceback):
 
  39         return self._i2c.scan()
 
  41     def readfrom_into(self, address, buffer, start=0, end=None):
 
  42         if start is not 0 or end is not None:
 
  45             buffer = memoryview(buffer)[start:end]
 
  46         stop = True  # remove for efficiency later
 
  47         return self._i2c.readfrom_into(address, buffer, stop)
 
  49     def writeto(self, address, buffer, start=0, end=None, stop=True):
 
  50         if start is not 0 or end is not None:
 
  52                 return self._i2c.writeto(address, memoryview(buffer)[start:], stop)
 
  54                 return self._i2c.writeto(address, memoryview(buffer)[start:end], stop)
 
  55         return self._i2c.writeto(address, buffer, stop)
 
  58 # TODO untested, as actually busio.SPI was on tasklist https://github.com/adafruit/Adafruit_Micropython_Blinka/issues/2 :(
 
  60     def __init__(self, clock, MOSI=None, MISO=None):
 
  61         from machine import SPI
 
  63         self._pins = (clock, MOSI, MISO)
 
  65     def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
 
  66         from machine import SPI,Pin
 
  68             # TODO verify if _spi obj 'caches' sck, mosi, miso to avoid storing in _attributeIds (duplicated in busio)
 
  69             # i.e. #init ignores MOSI=None rather than unsetting
 
  76                 sck=Pin(self._pins[0].id),
 
  77                 mosi=Pin(self._pins[1].id),
 
  78                 miso=Pin(self._pins[2].id))
 
  80             raise RuntimeError("First call try_lock()")
 
  83         return self._spi.write(buf)
 
  85     def readinto(self, buf):
 
  86         return self.readinto(buf)
 
  88     def write_readinto(self, buffer_out, buffer_in):
 
  89         return self.write_readinto(buffer_out, buffer_in)