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