|
2 | 2 | #
|
3 | 3 | # SPDX-License-Identifier: MIT
|
4 | 4 |
|
5 |
| -"""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() |
| 5 | +# pylint: disable=bare-except, eval-used, unused-import |
10 | 6 |
|
| 7 | +"""CircuitPython I2C Device Address Scan""" |
11 | 8 | import time
|
12 | 9 | import board
|
| 10 | +import busio |
13 | 11 |
|
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 |
| 12 | +# List of potential I2C busses |
| 13 | +ALL_I2C = ("board.I2C()", "board.STEMMA_I2C()", "busio.I2C(board.GP1, board.GP0)") |
17 | 14 |
|
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 |
| 15 | +# Determine which busses are valid |
| 16 | +found_i2c = [] |
| 17 | +for name in ALL_I2C: |
| 18 | + try: |
| 19 | + print("Checking {}...".format(name), end="") |
| 20 | + bus = eval(name) |
| 21 | + bus.unlock() |
| 22 | + found_i2c.append((name, bus)) |
| 23 | + print("ADDED.") |
| 24 | + except: |
| 25 | + print("SKIPPED.") |
22 | 26 |
|
23 |
| -while not i2c.try_lock(): |
24 |
| - pass |
25 |
| - |
26 |
| -try: |
| 27 | +# Scan valid busses |
| 28 | +if len(found_i2c): |
| 29 | + print("-" * 40) |
| 30 | + print("I2C SCAN") |
| 31 | + print("-" * 40) |
27 | 32 | while True:
|
28 |
| - print( |
29 |
| - "I2C addresses found:", |
30 |
| - [hex(device_address) for device_address in i2c.scan()], |
31 |
| - ) |
32 |
| - time.sleep(2) |
| 33 | + for bus_info in found_i2c: |
| 34 | + name = bus_info[0] |
| 35 | + bus = bus_info[1] |
33 | 36 |
|
34 |
| -finally: # unlock the i2c bus when ctrl-c'ing out of the loop |
35 |
| - i2c.unlock() |
| 37 | + while not bus.try_lock(): |
| 38 | + pass |
| 39 | + |
| 40 | + print( |
| 41 | + name, |
| 42 | + "addresses found:", |
| 43 | + [hex(device_address) for device_address in bus.scan()], |
| 44 | + ) |
| 45 | + |
| 46 | + bus.unlock() |
| 47 | + |
| 48 | + time.sleep(2) |
| 49 | +else: |
| 50 | + print("No valid I2C bus found.") |
0 commit comments