fancier more automagic i2c scan

This commit is contained in:
caternuson 2023-11-28 10:23:42 -08:00
parent 8cb888956b
commit 9c592cbeec

View file

@ -3,33 +3,46 @@
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
"""CircuitPython I2C Device Address Scan""" """CircuitPython I2C Device Address Scan"""
# If you run this and it seems to hang, try manually unlocking
# your I2C bus from the REPL with
# >>> import board
# >>> board.I2C().unlock()
import time import time
import board import board
import busio
# To use default I2C bus (most boards) # List of potential I2C busses
i2c = board.I2C() # uses board.SCL and board.SDA ALL_I2C = ("board.I2C()", "board.STEMMA_I2C()", "busio.I2C(board.GP1, board.GP0)")
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
# To create I2C bus on specific pins # Determine which busses are valid
# import busio found_i2c = []
# i2c = busio.I2C(board.SCL1, board.SDA1) # QT Py RP2040 STEMMA connector for name in ALL_I2C:
# i2c = busio.I2C(board.GP1, board.GP0) # Pi Pico RP2040 try:
print("Checking {}...".format(name), end="")
bus = eval(name)
bus.unlock()
found_i2c.append((name, bus))
print("ADDED.")
except:
print("SKIPPED.")
while not i2c.try_lock(): # Scan valid busses
pass if len(found_i2c):
print("-" * 40)
try: print("I2C SCAN")
print("-" * 40)
while True: while True:
print( for bus_info in found_i2c:
"I2C addresses found:", name = bus_info[0]
[hex(device_address) for device_address in i2c.scan()], bus = bus_info[1]
)
time.sleep(2)
finally: # unlock the i2c bus when ctrl-c'ing out of the loop while not bus.try_lock():
i2c.unlock() pass
print(
name,
"addresses found:",
[hex(device_address) for device_address in bus.scan()],
)
bus.unlock()
time.sleep(2)
else:
print("No valid I2C bus found.")