1 """SPI Class for FT232H"""
2 from adafruit_blinka.microcontroller.ft232h.pin import Pin
3 from adafruit_blinka.microcontroller.ft232h.url import get_ftdi_url
5 # pylint: disable=protected-access
7 """Custom SPI Class for FT232H"""
12 # pylint: disable=import-outside-toplevel
13 from pyftdi.spi import SpiController
15 # pylint: enable=import-outside-toplevel
17 self._spi = SpiController(cs_count=1)
18 self._spi.configure(get_ftdi_url())
19 self._port = self._spi.get_port(0)
20 self._port.set_frequency(100000)
23 # Change GPIO controller to SPI
24 Pin.ft232h_gpio = self._spi.get_gpio()
26 # pylint: disable=too-many-arguments,unused-argument
38 """Initialize the Port"""
39 self._port.set_frequency(baudrate)
40 # FTDI device can only support mode 0 and mode 2
41 # due to the limitation of MPSSE engine.
42 # This means CPHA must = 0
43 self._port._cpol = polarity
45 raise ValueError("Only SPI phase 0 is supported by FT232H.")
46 self._port._cpha = phase
48 # pylint: enable=too-many-arguments
52 """Return the current frequency"""
53 return self._port.frequency
55 def write(self, buf, start=0, end=None):
56 """Write data from the buffer to SPI"""
57 end = end if end else len(buf)
58 chunks, rest = divmod(end - start, self._spi.PAYLOAD_MAX_LENGTH)
59 for i in range(chunks):
60 chunk_start = start + i * self._spi.PAYLOAD_MAX_LENGTH
61 chunk_end = chunk_start + self._spi.PAYLOAD_MAX_LENGTH
62 self._port.write(buf[chunk_start:chunk_end])
64 rest_start = start + chunks * self._spi.PAYLOAD_MAX_LENGTH
65 self._port.write(buf[rest_start:end])
67 # pylint: disable=unused-argument
68 def readinto(self, buf, start=0, end=None, write_value=0):
69 """Read data from SPI and into the buffer"""
70 end = end if end else len(buf)
71 buffer_out = [write_value] * (end - start)
72 result = self._port.exchange(buffer_out, end - start, duplex=True)
73 for i, b in enumerate(result):
76 # pylint: enable=unused-argument
78 # pylint: disable=too-many-arguments
80 self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
82 """Perform a half-duplex write from buffer_out and then
83 read data into buffer_in
85 out_end = out_end if out_end else len(buffer_out)
86 in_end = in_end if in_end else len(buffer_in)
87 result = self._port.exchange(
88 buffer_out[out_start:out_end], in_end - in_start, duplex=True
90 for i, b in enumerate(result):
91 buffer_in[in_start + i] = b
93 # pylint: enable=too-many-arguments