nonNoise / PyMCP2221A

MCP2221 & MCP2221A work in Python.
MIT License
36 stars 21 forks source link

GPIO_Init using wrong offsets #22

Open jdhnp opened 6 months ago

jdhnp commented 6 months ago

I think the GPIO_Init function is using the wrong offsets to read the initial BIT, DIR, and MODE values. This can cause garbage GPIO info to be read, which is then set back to the MCP chip in subsequent calls to GPIO_Write, which can then cause exceptions in the HID library.

def GPIO_Init(self):
  ...
  self.GPIO_0_BIT = (rbuf[22 + 1] >> 4) & 0x01      # 1:Hi 0:LOW
  self.GPIO_0_DIR = (rbuf[22 + 1] >> 3) & 0x01      # 0:OutPut 1:Input
  self.GPIO_0_MODE = rbuf[22 + 1] & 0x07  # GPIO MODE = 0x00
  ...

Should be:

def GPIO_Init(self):
  ...
  self.GPIO_0_BIT = (rbuf[22] >> 4) & 0x01      # 1:Hi 0:LOW
  self.GPIO_0_DIR = (rbuf[22] >> 3) & 0x01      # 0:OutPut 1:Input
  self.GPIO_0_MODE = rbuf[22] & 0x07  # GPIO MODE = 0x00
  ...

This issue is masked by always calling the Reset() command and re-creating a new HID device which is in all of the example code:

mcp2221 = PyMCP2221A.PyMCP2221A()
mcp2221.Reset()
mcp2221 = PyMCP2221A.PyMCP2221A()

You can duplicate the issue by opening the device without a Reset, setup and toggle GPIO pins, then open a new instance and try to setup and toggle GPIO. Maybe there are additional reasons for calling Reset(), but in my case I can now remove the Reset() and GPIO and I2C seem to be working just fine.