1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
 
   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
 
  11     """Custom I2C Class for RP2040"""
 
  13     def __init__(self, scl, sda, *, frequency=100000):
 
  14         for portId, portScl, portSda in i2cPorts:
 
  16                 if scl == portScl and sda == portSda:
 
  18                         portId, sda=Pin(sda.id), scl=Pin(scl.id), freq=frequency
 
  25                 "No Hardware I2C on (scl,sda)={}\nValid I2C ports: {}".format(
 
  31         """Perform an I2C Device Scan"""
 
  32         return self._i2c.scan()
 
  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)
 
  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)
 
  42     def writeto_then_readfrom(
 
  54         """Write data from buffer_out to an address and then
 
  55         read data from an address and into buffer_in
 
  58             self.writeto(address, buffer_out[out_start:out_end], stop=stop)
 
  60             self.writeto(address, buffer_out[out_start:], stop=stop)
 
  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)