]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/rp2040/i2c.py
Merge branch 'master' into master
[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     # pylint: disable=unused-argument
32     def writeto(self, address, buffer, *, stop=True):
33         "Write data to the address from the buffer"
34         return self._i2c.writeto(address, buffer)
35
36     def readfrom_into(self, address, buffer, *, stop=True):
37         """Read data from an address and into the buffer"""
38         return self._i2c.readfrom_into(address, buffer)
39
40     def writeto_then_readfrom(
41         self,
42         address,
43         buffer_out,
44         buffer_in,
45         *,
46         out_start=0,
47         out_end=None,
48         in_start=0,
49         in_end=None,
50         stop=False
51     ):
52         """Write data from buffer_out to an address and then
53         read data from an address and into buffer_in
54         """
55         self._i2c.writeto_then_readfrom(
56             address,
57             buffer_out,
58             buffer_in,
59             out_start=out_start,
60             out_end=out_end,
61             in_start=in_start,
62             in_end=in_end,
63         )
64
65     # pylint: enable=unused-argument