我在 Python I2C 中有一个代码可以与 8 位寄存器地址通信,我正在尝试更新它以与 16 位寄存器地址从机一起工作(在这两种情况下寄存器都是 8 位数据长度)。 我想继续使用 pyftdi 库。
将 pyftdi.i2c 导入为 I2C 从 pyftdi.ftdi 导入 Ftdi 导入时间
device = 'ftdi://ftdi:232h:0:1/1' #'ftdi://ftdi:232h/2'
s = StringIO()
i2c = None
def __init__(self):
# Instantiate an I2C controller
self.i2c = I2cController()
# Configure the first interface (IF/1) of the FTDI device as an I2C master
self.i2c.configure(self.device, frequency=100E3)
# Get a port to an I2C slave device
self.slave = self.i2c.get_port(0x4d)
def set_device_addr(self, addr):
self.slave = self.i2c.get_port(addr)
def i2c_bus_scanner(self):
sys.stdout = self.s
scanner = I2cBusScanner()
scanner.scan(self.device, False)
ports_list = self.s.getvalue().splitlines()
self.i2c = I2cController()
self.i2c.configure(self.device, frequency=100E3)
sys.stdout = sys.__stdout__
return ports_list
def i2c_read(self, addr_hex):
# Read a register from the I2C slave
try:
data_bytearray = self.slave.read_from(addr_hex, 1)
data_hex = data_bytearray.hex()
data_out = str(hex(addr_hex)).split("x")[1] + ',' + data_hex
print("read" + ' ' + data_out)
return data_out
except:
self.ftdi_i2c_error_handler()
return None
def i2c_write(self, addr_hex, data_hex):
try:
# Write a register to the I2C slave
data_bytes = data_hex.to_bytes(1, 'big')
self.slave.write_to(addr_hex, data_bytes)
print("write" + ' ' + str(hex(addr_hex)) + "," + str(data_bytes.hex()))
data_out = str(hex(addr_hex)) + ',' + str(data_hex)
return data_out
except:
self.ftdi_i2c_error_handler()
return None
def ftdi_i2c_error_handler(self):
self.mbox('I2C Error', "NACK from slave", 0)
hi = ''
def mbox(self, title, text, style):
return ctypes.windll.user32.MessageBoxW(0, text, title, style)
def i2c_read_for_dump(self, addr_hex):
# Read a register from the I2C slave
try:
data_bytearray = self.slave.read_from(addr_hex, 1)
data_hex = data_bytearray.hex()
return data_hex
except:
return "Nn"`