1 """SPI Class for FT232H"""
2 from adafruit_blinka.microcontroller.ft232h.pin import Pin
4 # pylint: disable=protected-access
6 """Custom SPI Class for FT232H"""
11 # pylint: disable=import-outside-toplevel
12 from pyftdi.spi import SpiController
14 # pylint: enable=import-outside-toplevel
16 self._spi = SpiController(cs_count=1)
17 self._spi.configure("ftdi://ftdi:ft232h/1")
18 self._port = self._spi.get_port(0)
19 self._port.set_frequency(100000)
22 # Change GPIO controller to SPI
23 Pin.ft232h_gpio = self._spi.get_gpio()
25 # pylint: disable=too-many-arguments,unused-argument
37 """Initialize the Port"""
38 self._port.set_frequency(baudrate)
39 # FTDI device can only support mode 0 and mode 2
40 # due to the limitation of MPSSE engine.
41 # This means CPHA must = 0
42 self._port._cpol = polarity
44 raise ValueError("Only SPI phase 0 is supported by FT232H.")
45 self._port._cpha = phase
47 # pylint: enable=too-many-arguments
51 """Return the current frequency"""
52 return self._port.frequency
54 def write(self, buf, start=0, end=None):
55 """Write data from the buffer to SPI"""
56 end = end if end else len(buf)
57 chunks, rest = divmod(end - start, self._spi.PAYLOAD_MAX_LENGTH)
58 for i in range(chunks):
59 chunk_start = start + i * self._spi.PAYLOAD_MAX_LENGTH
60 chunk_end = chunk_start + self._spi.PAYLOAD_MAX_LENGTH
61 self._port.write(buf[chunk_start:chunk_end])
63 rest_start = start + chunks * self._spi.PAYLOAD_MAX_LENGTH
64 self._port.write(buf[rest_start:end])
66 # pylint: disable=unused-argument
67 def readinto(self, buf, start=0, end=None, write_value=0):
68 """Read data from SPI and into the buffer"""
69 end = end if end else len(buf)
70 buffer_out = [write_value] * (end - start)
71 result = self._port.exchange(buffer_out, end - start, duplex=True)
72 for i, b in enumerate(result):
75 # pylint: enable=unused-argument
77 # pylint: disable=too-many-arguments
79 self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
81 """Perform a half-duplex write from buffer_out and then
82 read data into buffer_in
84 out_end = out_end if out_end else len(buffer_out)
85 in_end = in_end if in_end else len(buffer_in)
86 result = self._port.exchange(
87 buffer_out[out_start:out_end], in_end - in_start, duplex=True
89 for i, b in enumerate(result):
90 buffer_in[in_start + i] = b
92 # pylint: enable=too-many-arguments