]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/busio.py
begin i2c
[Adafruit_Blinka-hackapet.git] / src / busio.py
1 """
2 `busio` - Bus protocol support like I2C and SPI
3 =================================================
4
5 See `CircuitPython:busio` in CircuitPython for more details.
6
7 * Author(s): cefn
8 """
9
10 from adafruit_blinka import Enum, Lockable, agnostic
11 from adafruit_blinka.agnostic import board as boardId
12
13 class I2C(Lockable):
14     def __init__(self, scl, sda, frequency=400000):
15         self.init(scl, sda, frequency)
16
17     def init(self, scl, sda, frequency):
18         self.deinit()
19         if boardId == "raspi_3" or boardId == "raspi_2":
20             from adafruit_blinka.microcontroller.raspi_23.i2c import I2C as _I2C
21         else:
22             from machine import I2C as _I2C
23         from microcontroller.pin import i2cPorts
24         for portId, portScl, portSda in i2cPorts:
25             if scl == portScl and sda == portSda:
26                 self._i2c = I2C(portId, mode=_I2C.MASTER, baudrate=frequency)
27                 break
28         else:
29             raise NotImplementedError("No Hardware I2C on (scl,sda)={}\nValid UART ports".format(
30         (scl, sda), i2cPorts))
31
32     def deinit(self):
33         try:
34             del self._i2c
35         except AttributeError:
36             pass
37
38     def __enter__(self):
39         return self
40
41     def __exit__(self, exc_type, exc_value, traceback):
42         self.deinit()
43
44     def scan(self):
45         return self._i2c.scan()
46
47     def readfrom_into(self, address, buffer, start=0, end=None):
48         if start is not 0 or end is not None:
49             if end is None:
50                 end = len(buffer)
51             buffer = memoryview(buffer)[start:end]
52         stop = True  # remove for efficiency later
53         return self._i2c.readfrom_into(address, buffer, stop)
54
55     def writeto(self, address, buffer, start=0, end=None, stop=True):
56         if start is not 0 or end is not None:
57             if end is None:
58                 return self._i2c.writeto(address, memoryview(buffer)[start:], stop)
59             else:
60                 return self._i2c.writeto(address, memoryview(buffer)[start:end], stop)
61         return self._i2c.writeto(address, buffer, stop)
62
63
64 class SPI(Lockable):
65     def __init__(self, clock, MOSI=None, MISO=None):
66         from microcontroller.pin import spiPorts
67         for portId, portSck, portMosi, portMiso in spiPorts:
68             if clock == portSck and MOSI == portMosi and MISO == portMiso:
69                 self._spi = SPI(portId)
70                 self._pins = (portSck, portMosi, portMiso)
71                 break
72         else:
73             raise NotImplementedError(
74                 "No Hardware SPI on (clock, MOSI, MISO)={}\nValid SPI ports:{}".
75                 format((clock, MOSI, MISO), spiPorts))
76
77     def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
78         if self._locked:
79             from machine import Pin
80             # TODO check if #init ignores MOSI=None rather than unsetting, to save _pinIds attribute
81             self._spi.init(
82                 baudrate=baudrate,
83                 polarity=polarity,
84                 phase=phase,
85                 bits=bits,
86                 firstbit=SPI.MSB,
87                 sck=Pin(self._pins[0].id),
88                 mosi=Pin(self._pins[1].id),
89                 miso=Pin(self._pins[2].id)
90             )
91         else:
92             raise RuntimeError("First call try_lock()")
93
94     def deinit(self):
95         self._spi = None
96         self._pinIds = None
97
98     def write(self, buf):
99         return self._spi.write(buf)
100
101     def readinto(self, buf):
102         return self.readinto(buf)
103
104     def write_readinto(self, buffer_out, buffer_in):
105         return self.write_readinto(buffer_out, buffer_in)
106
107
108 class UART(Lockable):
109     class Parity(Enum):
110         pass
111
112     Parity.ODD = Parity()
113     Parity.EVEN = Parity()
114
115     def __init__(self,
116                  tx,
117                  rx,
118                  baudrate=9600,
119                  bits=8,
120                  parity=None,
121                  stop=1,
122                  timeout=1000,
123                  receiver_buffer_size=64,
124                  flow=None):
125         from machine import UART as _UART
126         from microcontroller.pin import uartPorts
127
128         self.baudrate = baudrate
129
130         if flow is not None:  # default 0
131             raise NotImplementedError(
132                 "Parameter '{}' unsupported on {}".format(
133                     "flow", agnostic.board))
134
135         # translate parity flag for Micropython
136         if parity is UART.Parity.ODD:
137             parity = 1
138         elif parity is UART.Parity.EVEN:
139             parity = 0
140         elif parity is None:
141             pass
142         else:
143             raise ValueError("Invalid parity")
144
145         # check tx and rx have hardware support
146         for portId, portTx, portRx in uartPorts:  #
147             if portTx == tx and portRx == rx:
148                 self._uart = _UART(
149                     portId,
150                     baudrate,
151                     bits=bits,
152                     parity=parity,
153                     stop=stop,
154                     timeout=timeout,
155                     read_buf_len=receiver_buffer_size
156                 )
157                 break
158         else:
159             raise NotImplementedError(
160                 "No Hardware UART on (tx,rx)={}\nValid UART ports".format(
161                     (tx, rx), uartPorts))
162
163     def deinit(self):
164         self._uart = None
165
166     def read(self, nbytes=None):
167         return self._uart.read(nbytes)
168
169     def readinto(self, buf, nbytes=None):
170         return self._uart.readinto(buf, nbytes)
171
172     def readline(self):
173         return self._uart.readline()
174
175     def write(self, buf):
176         return self._uart.write(buf)