Skip to content

Instantly share code, notes, and snippets.

@Misiu
Forked from kungpfui/scan_for_i2c_devices
Created June 30, 2020 08:31
Show Gist options
  • Save Misiu/ef1a93f3a7566a4997e786f720ae22e6 to your computer and use it in GitHub Desktop.
Save Misiu/ef1a93f3a7566a4997e786f720ae22e6 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment