1 """SPI Class for Binho Nova"""
2 from adafruit_blinka.microcontroller.nova import Connection
6 """Custom SPI Class for Binho Nova"""
9 PAYLOAD_MAX_LENGTH = 64
11 def __init__(self, clock):
12 self._nova = Connection.getInstance()
13 self._nova.setNumericalBase(10)
14 self._nova.setOperationMode(0, "SPI")
15 self._nova.setClockSPI(0, clock)
16 self._nova.setModeSPI(0, 0)
17 self._nova.setIOpinMode(0, "DOUT")
18 self._nova.setIOpinMode(1, "DOUT")
19 self._nova.beginSPI(0)
21 # Cpol and Cpha set by mode
28 # pylint: disable=too-many-arguments,unused-argument
40 """Initialize the Port"""
41 # print("baudrate: " + str(baudrate))
42 # print("mode: " + str((polarity<<1) | (phase)))
43 self._nova.setClockSPI(0, baudrate)
44 self._nova.setModeSPI(0, (polarity << 1) | (phase))
46 # pylint: enable=too-many-arguments,unused-argument
49 def get_received_data(lineOutput):
50 """Return any received data"""
51 return lineOutput.split("RXD ")[1]
55 """Return the current frequency"""
56 return self._nova.getClockSPI(0).split("CLK ")[1]
58 def write(self, buf, start=0, end=None):
59 """Write data from the buffer to SPI"""
60 end = end if end else len(buf)
61 chunks, rest = divmod(end - start, self.PAYLOAD_MAX_LENGTH)
62 for i in range(chunks):
63 chunk_start = start + i * self.PAYLOAD_MAX_LENGTH
64 chunk_end = chunk_start + self.PAYLOAD_MAX_LENGTH
65 buffer_data = buf[chunk_start:chunk_end]
66 self._nova.clearBuffer(0)
67 self._nova.writeToBuffer(0, 0, buffer_data)
68 self._nova.transferBufferSPI(0, chunk_end - chunk_start + 1)
70 buffer_data = buf[-1 * rest :]
71 self._nova.clearBuffer(0)
72 self._nova.writeToBuffer(0, 0, buffer_data)
73 self._nova.transferBufferSPI(0, rest)
75 def readinto(self, buf, start=0, end=None, write_value=0):
76 """Read data from SPI and into the buffer"""
77 end = end if end else len(buf)
78 for i in range(start, end):
80 self.get_received_data(self._nova.transferSPI(0, write_value))
83 # pylint: disable=too-many-arguments
85 self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
87 """Perform a half-duplex write from buffer_out and then
88 read data into buffer_in
90 out_end = out_end if out_end else len(buffer_out)
91 in_end = in_end if in_end else len(buffer_in)
92 readlen = in_end - in_start
93 writelen = out_end - out_start
94 if readlen > writelen:
95 # resize out and pad with 0's
96 tmp = bytearray(buffer_out)
97 tmp.extend([0] * (readlen - len(buffer_out)))
100 for data_out in buffer_out:
101 data_in = int(self.get_received_data(self._nova.transferSPI(0, data_out)))
103 buffer_in[in_start + i] = data_in
106 # pylint: enable=too-many-arguments