Created
January 13, 2020 20:16
-
-
Save kungpfui/54784ebc3b3ca72169c1839720b313bf to your computer and use it in GitHub Desktop.
Scan for I2C devices with smbus2 library (like i2cdetect)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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
Thank you!