Last active
June 28, 2022 22:09
-
-
Save BOSSoNe0013/b693dff2ecd117adf85af666fae106ad to your computer and use it in GitHub Desktop.
Simple i2cdetect clone written in Python 3 with smbus library
This file contains hidden or 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
import sys | |
import smbus | |
first = 0x03 | |
last = 0x77 | |
def i2cdetect(bus_id=0): | |
bus = smbus.SMBus(bus_id) | |
print('Bus: I2C-{}'.format(bus_id)) | |
print(" 0 1 2 3 4 5 6 7 8 9 a b c d e f") | |
for i in range(0, 128, 16): | |
print(' {0:02x}: '.format(i), end='') | |
for j in range(0, 16): | |
address: int = i + j | |
res = None | |
if address < first or address > last: | |
print(" ", end='') | |
continue | |
try: | |
if (0x30 <= address <= 0x37) or (0x50 <= address <= 0x5f): | |
res = bus.read_byte(address) | |
else: | |
res = bus.write_quick(address) | |
except OSError as error: | |
pass | |
finally: | |
if res is not None: | |
print('{0:02x} '.format(address), end='') | |
else: | |
print('-- ', end='') | |
pass | |
print('') | |
print('') | |
if __name__ == "__main__": | |
bus_start = 0 | |
bus_count = 1 | |
argc = len(sys.argv) | |
if argc == 2: | |
bus_start = int(sys.argv[1]) | |
bus_count = bus_start + 1 | |
elif argc == 3: | |
bus_start = int(sys.argv[1]) | |
bus_count = bus_start + int(sys.argv[2]) | |
for bid in range(bus_start, bus_count): | |
i2cdetect(bid) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output of this code does not match the output of i2cdetect -y 1, as this code does not detect the attached device at 0x40 whereas i2cdetect -y 1 does detect it. The device is a WaveShare 16 channel servo driver HAT, with factory default address 0x40. What is this code missing hat i2cdetect has?