]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/busio.py
add I2C bus support for the BeagleBone Black
[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_id
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 board_id == "raspi_3" or board_id == "raspi_2":
20             from adafruit_blinka.microcontroller.raspi_23.i2c import I2C as _I2C
21         if board_id == "beaglebone_black":
22             from adafruit_blinka.microcontroller.raspi_23.i2c import I2C as _I2C
23         else:
24             from machine import I2C as _I2C
25         from microcontroller.pin import i2cPorts
26         for portId, portScl, portSda in i2cPorts:
27             if scl == portScl and sda == portSda:
28                 self._i2c = _I2C(portId, mode=_I2C.MASTER, baudrate=frequency)
29                 break
30         else:
31             raise NotImplementedError("No Hardware I2C on (scl,sda)={}\nValid UART ports".format(
32         (scl, sda), i2cPorts))
33
34     def deinit(self):
35         try:
36             del self._i2c
37         except AttributeError:
38             pass
39
40     def __enter__(self):
41         return self
42
43     def __exit__(self, exc_type, exc_value, traceback):
44         self.deinit()
45
46     def scan(self):
47         return self._i2c.scan()
48
49     def readfrom_into(self, address, buffer, *, start=0, end=None):
50         if start is not 0 or end is not None:
51             if end is None:
52                 end = len(buffer)
53             buffer = memoryview(buffer)[start:end]
54         stop = True  # remove for efficiency later
55         return self._i2c.readfrom_into(address, buffer, stop=stop)
56
57     def writeto(self, address, buffer, *, start=0, end=None, stop=True):
58         if isinstance(buffer, str):
59             buffer = bytes([ord(x) for x in buffer])
60         if start is not 0 or end is not None:
61             if end is None:
62                 return self._i2c.writeto(address, memoryview(buffer)[start:], stop=stop)
63             else:
64                 return self._i2c.writeto(address, memoryview(buffer)[start:end], stop=stop)
65         return self._i2c.writeto(address, buffer, stop=stop)
66
67     def writeto_then_readfrom(self, address, buffer_out, buffer_in, *, out_start=0, out_end=None, in_start=0, in_end=None, stop=False):
68         return self._i2c.writeto_then_readfrom(address, buffer_out, buffer_in,
69                                                out_start=out_start, out_end=out_end,
70                                                in_start=in_start, in_end=in_end, stop=stop)
71
72 class SPI(Lockable):
73     def __init__(self, clock, MOSI=None, MISO=None):
74         self.deinit()
75         if board_id == "raspi_3" or board_id == "raspi_2":
76             from adafruit_blinka.microcontroller.raspi_23.spi import SPI as _SPI
77         elif board_id == "beaglebone_black":
78             from adafruit_blinka.microcontroller.beaglebone_black.spi import SPI as _SPI
79         else:
80             from machine import SPI as _SPI
81         from microcontroller.pin import spiPorts
82         for portId, portSck, portMosi, portMiso in spiPorts:
83             if ((clock == portSck) and                   # Clock is required!
84                 (MOSI == portMosi or MOSI == None) and   # But can do with just output
85                 (MISO == portMiso or MISO == None)):      # Or just input
86                 self._spi = _SPI(portId)
87                 self._pins = (portSck, portMosi, portMiso)
88                 break
89         else:
90             raise NotImplementedError(
91                 "No Hardware SPI on (SCLK, MOSI, MISO)={}\nValid SPI ports:{}".
92                 format((clock, MOSI, MISO), spiPorts))
93
94     def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
95         if board_id == "raspi_3" or board_id == "raspi_2":
96             from adafruit_blinka.microcontroller.raspi_23.spi import SPI as _SPI
97             from adafruit_blinka.microcontroller.raspi_23.pin import Pin
98         elif board_id == "beaglebone_black":
99             from adafruit_blinka.microcontroller.beaglebone_black.spi import SPI as _SPI
100             from adafruit_blinka.microcontroller.beaglebone_black.pin import Pin
101         else:
102             from machine import SPI as _SPI
103             from machine import Pin
104
105         if self._locked:
106             # TODO check if #init ignores MOSI=None rather than unsetting, to save _pinIds attribute
107             self._spi.init(
108                 baudrate=baudrate,
109                 polarity=polarity,
110                 phase=phase,
111                 bits=bits,
112                 firstbit=_SPI.MSB,
113                 sck=Pin(self._pins[0].id),
114                 mosi=Pin(self._pins[1].id),
115                 miso=Pin(self._pins[2].id)
116             )
117         else:
118             raise RuntimeError("First call try_lock()")
119
120     def deinit(self):
121         self._spi = None
122         self._pinIds = None
123
124     def write(self, buf, start=0, end=None):
125         return self._spi.write(buf, start, end)
126
127     def readinto(self, buf, start=0, end=None, write_value=0):
128         return self._spi.readinto(buf, start, end)
129
130     def write_readinto(self, buffer_out, buffer_in,  out_start=0, out_end=None, in_start=0, in_end=None):
131         return self._spi.write_readinto(buffer_out, buffer_in, out_start, out_end, in_start, in_end)
132
133
134 class UART(Lockable):
135     class Parity(Enum):
136         pass
137
138     Parity.ODD = Parity()
139     Parity.EVEN = Parity()
140
141     def __init__(self,
142                  tx,
143                  rx,
144                  baudrate=9600,
145                  bits=8,
146                  parity=None,
147                  stop=1,
148                  timeout=1000,
149                  receiver_buffer_size=64,
150                  flow=None):
151         from machine import UART as _UART
152         from microcontroller.pin import uartPorts
153
154         self.baudrate = baudrate
155
156         if flow is not None:  # default 0
157             raise NotImplementedError(
158                 "Parameter '{}' unsupported on {}".format(
159                     "flow", agnostic.board))
160
161         # translate parity flag for Micropython
162         if parity is UART.Parity.ODD:
163             parity = 1
164         elif parity is UART.Parity.EVEN:
165             parity = 0
166         elif parity is None:
167             pass
168         else:
169             raise ValueError("Invalid parity")
170
171         # check tx and rx have hardware support
172         for portId, portTx, portRx in uartPorts:  #
173             if portTx == tx and portRx == rx:
174                 self._uart = _UART(
175                     portId,
176                     baudrate,
177                     bits=bits,
178                     parity=parity,
179                     stop=stop,
180                     timeout=timeout,
181                     read_buf_len=receiver_buffer_size
182                 )
183                 break
184         else:
185             raise NotImplementedError(
186                 "No Hardware UART on (tx,rx)={}\nValid UART ports".format(
187                     (tx, rx), uartPorts))
188
189     def deinit(self):
190         self._uart = None
191
192     def read(self, nbytes=None):
193         return self._uart.read(nbytes)
194
195     def readinto(self, buf, nbytes=None):
196         return self._uart.readinto(buf, nbytes)
197
198     def readline(self):
199         return self._uart.readline()
200
201     def write(self, buf):
202         return self._uart.write(buf)