Skip to content

Commit 9c592cb

Browse files
committed
fancier more automagic i2c scan
1 parent 8cb8889 commit 9c592cb

1 file changed

Lines changed: 36 additions & 23 deletions

File tree

  • CircuitPython_Essentials/CircuitPython_I2C_Scan

CircuitPython_Essentials/CircuitPython_I2C_Scan/code.py

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,46 @@
33
# SPDX-License-Identifier: MIT
44

55
"""CircuitPython I2C Device Address Scan"""
6-
# If you run this and it seems to hang, try manually unlocking
7-
# your I2C bus from the REPL with
8-
# >>> import board
9-
# >>> board.I2C().unlock()
10-
116
import time
127
import board
8+
import busio
139

14-
# To use default I2C bus (most boards)
15-
i2c = board.I2C() # uses board.SCL and board.SDA
16-
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
17-
18-
# To create I2C bus on specific pins
19-
# import busio
20-
# i2c = busio.I2C(board.SCL1, board.SDA1) # QT Py RP2040 STEMMA connector
21-
# i2c = busio.I2C(board.GP1, board.GP0) # Pi Pico RP2040
10+
# List of potential I2C busses
11+
ALL_I2C = ("board.I2C()", "board.STEMMA_I2C()", "busio.I2C(board.GP1, board.GP0)")
2212

23-
while not i2c.try_lock():
24-
pass
13+
# Determine which busses are valid
14+
found_i2c = []
15+
for name in ALL_I2C:
16+
try:
17+
print("Checking {}...".format(name), end="")
18+
bus = eval(name)
19+
bus.unlock()
20+
found_i2c.append((name, bus))
21+
print("ADDED.")
22+
except:
23+
print("SKIPPED.")
2524

26-
try:
25+
# Scan valid busses
26+
if len(found_i2c):
27+
print("-" * 40)
28+
print("I2C SCAN")
29+
print("-" * 40)
2730
while True:
28-
print(
29-
"I2C addresses found:",
30-
[hex(device_address) for device_address in i2c.scan()],
31-
)
32-
time.sleep(2)
31+
for bus_info in found_i2c:
32+
name = bus_info[0]
33+
bus = bus_info[1]
34+
35+
while not bus.try_lock():
36+
pass
3337

34-
finally: # unlock the i2c bus when ctrl-c'ing out of the loop
35-
i2c.unlock()
38+
print(
39+
name,
40+
"addresses found:",
41+
[hex(device_address) for device_address in bus.scan()],
42+
)
43+
44+
bus.unlock()
45+
46+
time.sleep(2)
47+
else:
48+
print("No valid I2C bus found.")

0 commit comments

Comments
 (0)