I2c python

From Federal Burro of Information
Revision as of 04:46, 7 August 2022 by David (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

I'm not sure why but i2c with python is a huge pain in the ass.

There are many libs:


i2cscan3.py

#!/usr/bin/env python3

import smbus
import errno

if __name__ == "__main__":
    bus_number = 1  # 1 indicates /dev/i2c-1
    bus = smbus.SMBus(bus_number)
    device_count = 0

    for device in range(3, 128):
        try:
            bus.write_byte(device, 0)
            print("Found {0}".format(hex(device)))
            device_count = device_count + 1
        except IOError as e:
            if e.errno != errno.EREMOTEIO:
                print("Error: {0} on address {1}".format(e, hex(address)))
        except Exception as e: # exception if read_byte fails
            print("Error unk: {0} on address {1}".format(e, hex(address)))

    bus.close()
    bus = None
    print("Found {0} device(s)".format(device_count))