Skip to content

Instantly share code, notes, and snippets.

@kungpfui
Created January 13, 2020 20:16
Show Gist options
  • Save kungpfui/54784ebc3b3ca72169c1839720b313bf to your computer and use it in GitHub Desktop.
Save kungpfui/54784ebc3b3ca72169c1839720b313bf to your computer and use it in GitHub Desktop.
Scan for I2C devices with smbus2 library (like i2cdetect)
#!/usr/bin/env python3
from smbus2 import SMBus
def scan(force=False):
devices = []
for addr in range(0x03, 0x77 + 1):
read = SMBus.read_byte, (addr,), {'force':force}
write = SMBus.write_byte, (addr, 0), {'force':force}
for func, args, kwargs in (read, write):
try:
with SMBus(1) as bus:
data = func(bus, *args, **kwargs)
devices.append(addr)
break
except OSError as expt:
if expt.errno == 16:
# just busy, maybe permanent by a kernel driver or just temporary by some user code
pass
return devices
for addr in scan(force=True):
print('{:02X}'.format(addr))
@silver2row
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment