]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/rp2040/i2c.py
Ran black
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / rp2040 / i2c.py
1 """I2C Class for RP2040"""
2 from machine import I2C as _I2C
3 from machine import Pin
4 from microcontroller.pin import i2cPorts
5
6
7 class I2C:
8     """Custom I2C Class for RP2040"""
9
10     def __init__(self, scl, sda, *, frequency=100000):
11         for portId, portScl, portSda in i2cPorts:
12             try:
13                 if scl == portScl and sda == portSda:
14                     self._i2c = _I2C(
15                         portId, sda=Pin(sda.id), scl=Pin(scl.id), freq=frequency
16                     )
17                     break
18             except RuntimeError:
19                 pass
20         else:
21             raise ValueError(
22                 "No Hardware I2C on (scl,sda)={}\nValid I2C ports: {}".format(
23                     (scl, sda), i2cPorts
24                 )
25             )
26
27     def scan(self):
28         """Perform an I2C Device Scan"""
29         return self._i2c.scan()
30
31     def writeto(self, address, buffer, *, stop=True):
32         "Write data to the address from the buffer"
33         return self._i2c.writeto(address, buffer, stop)
34
35     def readfrom_into(self, address, buffer, *, stop=True):
36         """Read data from an address and into the buffer"""
37         return self._i2c.readfrom_into(address, buffer, stop)
38
39     def writeto_then_readfrom(
40         self,
41         address,
42         buffer_out,
43         buffer_in,
44         *,
45         out_start=0,
46         out_end=None,
47         in_start=0,
48         in_end=None,
49         stop=False,
50     ):
51         """Write data from buffer_out to an address and then
52         read data from an address and into buffer_in
53         """
54         if out_end:
55             self.writeto(address, buffer_out[out_start:out_end], stop=stop)
56         else:
57             self.writeto(address, buffer_out[out_start:], stop=stop)
58
59         if not in_end:
60             in_end = len(buffer_in)
61         read_buffer = memoryview(buffer_in)[in_start:in_end]
62         self.readfrom_into(address, read_buffer, stop=stop)