2 `bitbangio` - Bitbanged bus protocols
3 ==============================================================
5 See `CircuitPython:bitbangio` in CircuitPython for more details.
10 from adafruit_blinka import Lockable, agnostic
11 import adafruit_platformdetect.constants.boards as ap_board
15 def __init__(self, scl, sda, frequency=400000):
16 # TODO: This one is a bit questionable:
17 if agnostic.board_id == ap_board.PYBOARD:
18 raise NotImplementedError("No software I2C on {}".format(agnostic.board_id))
19 self.init(scl, sda, frequency)
21 def init(self, scl, sda, frequency):
22 from machine import Pin
23 from machine import I2C as _I2C
28 ) # force bitbanging implementation - in future introspect platform if SDA/SCL matches hardware I2C
29 self._i2c = _I2C(id, Pin(scl.id), Pin(sda.id), freq=frequency)
34 except AttributeError:
40 def __exit__(self, exc_type, exc_value, traceback):
44 return self._i2c.scan()
46 def readfrom_into(self, address, buffer, start=0, end=None):
47 if start is not 0 or end is not None:
50 buffer = memoryview(buffer)[start:end]
51 stop = True # remove for efficiency later
52 return self._i2c.readfrom_into(address, buffer, stop)
54 def writeto(self, address, buffer, start=0, end=None, stop=True):
55 if start is not 0 or end is not None:
57 return self._i2c.writeto(address, memoryview(buffer)[start:], stop)
59 return self._i2c.writeto(address, memoryview(buffer)[start:end], stop)
60 return self._i2c.writeto(address, buffer, stop)
63 # TODO untested, as actually busio.SPI was on tasklist https://github.com/adafruit/Adafruit_Micropython_Blinka/issues/2 :(
65 def __init__(self, clock, MOSI=None, MISO=None):
66 from machine import SPI
69 self._pins = (clock, MOSI, MISO)
71 def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
72 from machine import SPI, Pin
75 # TODO verify if _spi obj 'caches' sck, mosi, miso to avoid storing in _attributeIds (duplicated in busio)
76 # i.e. #init ignores MOSI=None rather than unsetting
83 sck=Pin(self._pins[0].id),
84 mosi=Pin(self._pins[1].id),
85 miso=Pin(self._pins[2].id),
88 raise RuntimeError("First call try_lock()")
91 return self._spi.write(buf)
93 def readinto(self, buf):
94 return self.readinto(buf)
96 def write_readinto(self, buffer_out, buffer_in):
97 return self.write_readinto(buffer_out, buffer_in)