grove.py icon indicating copy to clipboard operation
grove.py copied to clipboard

Problem in i2c.py opening multiple i2c busses

Open maubuz opened this issue 2 years ago • 3 comments

This issue was reported by @nikolozka in Issue #12.

The issue is still in the code and I would like to submit a PR for it, however, I'm trying to understand the reasoning behind this.

class Bus:
    instance = None
    MRAA_I2C = 0

    def __init__(self, bus=None):
       ... skipping code ...

       if not Bus.instance:
            Bus.instance = smbus.SMBus(bus)

      ... rest of code ...

Why is instance being used as a class attribute? It effectively makes the Bus class a singleton class. Are there any advantages to doing this that I'm missing?

To reproduce this problem:

  • Connect a Base Hat to the reTerminal.
  • Use an analog sensor such as the Grove Soil Humidity sensor with the ADC of the Base Hat.
  • Create a new I2C bus 4 for the reTerminal (using this example).
  • Connect an I2C sensor such as the AHT20 temperature & humidity sensor to the base hat.
  • Try to read from both sensors.
File "/usr/local/lib/python3.7/dist-packages/grove/grove_temperature_humidity_aht20.py", line 44, in read
    self.bus.write_i2c_block_data(self.address, 0x00, [0xac, 0x33, 0x00])
File "/usr/local/lib/python3.7/dist-packages/smbus2/smbus2.py", line 643, in write_i2c_block_data
    ioctl(self.fd, I2C_SMBUS, msg)
OSError: [Errno 6] No such device or address

maubuz avatar Apr 27 '22 19:04 maubuz

Hello,

Could you please refer to the code here in "beta" branch for i2c.py and try again? https://github.com/Seeed-Studio/grove.py/commit/994c0467fe1e40b94e597536ab7760381b51cf2c#diff-52f36dd5ac4814c063e9adea411aa5764d3c963850457d2a022155f7172ada9c

Also test with this code in "beta" branch: https://github.com/Seeed-Studio/grove.py/blob/beta/grove/i2c.py

Thank you

lakshanthad avatar May 31 '22 11:05 lakshanthad

I know it's been a long time but thanks for the suggestions. I tested the two suggestions and they both work in my case. Any ideas of when that code would be merged with master?

For those interested in getting this package working with multiple i2c buses immediately, as proposed by @nikolozka in #12 , I suggest the following changes in grove/i2c.py:

Modify lines 50 and 51:

if not Bus.instance:
    Bus.instance = smbus.SMBus(bus)

To:

if not self.instance:
    self.instance = smbus.SMBus(bus)

To find where grove/i2c.py is installed, try pip show grove.py.

maubuz avatar Apr 17 '23 02:04 maubuz

PR #66 created. Feel free to reject if upcoming changes make this obsolete.

maubuz avatar Apr 17 '23 03:04 maubuz