2

I am trying to write a script which will scan I2C interface and check what slaves available. The only way I saw so far is by command i2cdetect -y 1 which will list available I2C slaves. Is there any python library for doing that ?

2 Answers 2

2

Any method of I2C scanning has risks. Look at the man pages for the i2c_detect command.

Here is a simple method using (my) pigpio.

#!/usr/bin/env python

import pigpio

pigpio.exceptions = False # handle errors

pi = pigpio.pi()

for bus in range(2):
   for x in range(0x08, 0x79):
      h = pi.i2c_open(bus, x)
      if h >= 0:
         s = pi.i2c_read_byte(h)
         if s >= 0:
            print("device {} found on bus {}".format(x, bus))
         pi.i2c_close(h)

pi.stop()
1
  • read and even quickwrite methods can lock up the i2c bus, or slow it way down.
    – Schorschi
    May 30, 2017 at 3:01
1

The Adafruit Blinka library implements an i2c scan function.

import board
import busio

i2c = busio.I2C(board.SCL, board.SDA)
print(i2c.scan())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.