An simple I2C scanner example for CircuitPython is provided in the CircuitPython Essentials guide. Here is a "fancier" version:

# SPDX-FileCopyrightText: 2017 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT

# pylint: disable=broad-except, eval-used, unused-import

"""CircuitPython I2C Device Address Scan"""
import time
import board
import busio

# List of potential I2C busses
ALL_I2C = ("board.I2C()", "board.STEMMA_I2C()", "busio.I2C(board.GP1, board.GP0)")

# Determine which busses are valid
found_i2c = []
for name in ALL_I2C:
    try:
        print("Checking {}...".format(name), end="")
        bus = eval(name)
        bus.unlock()
        found_i2c.append((name, bus))
        print("ADDED.")
    except Exception as e:
        print("SKIPPED:", e)

# Scan valid busses
if len(found_i2c):
    print("-" * 40)
    print("I2C SCAN")
    print("-" * 40)
    while True:
        for bus_info in found_i2c:
            name = bus_info[0]
            bus = bus_info[1]

            while not bus.try_lock():
                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.")

Use the Welcome to CircuitPython guide to learn how to load and run this on your board.

I2C Bus Selection

The I2C scanner code above tries to automatically detect the presence of the most commonly used I2C buses. It then runs an I2C scan on each valid bus found. Therefore, the code should work as is, without any need to modify it, on most boards.

Here is example output for a QT Py RP2040 with two I2C devices attached - one to the STEMMA QT port and the other to the SCL/SDA header pins. These are two different I2C busses on the QT Py RP20404. So it scans both:

Checking board.I2C()...ADDED.
Checking board.STEMMA_I2C()...ADDED.
Checking busio.I2C(board.GP1, board.GP0)...SKIPPED.
----------------------------------------
I2C SCAN
----------------------------------------
board.I2C() addresses found: ['0x76']
board.STEMMA_I2C() addresses found: ['0x23']
board.I2C() addresses found: ['0x76']
board.STEMMA_I2C() addresses found: ['0x23']
board.I2C() addresses found: ['0x76']
board.STEMMA_I2C() addresses found: ['0x23']

This guide was first published on Sep 16, 2021. It was last updated on Jul 20, 2024.

This page (CircuitPython) was last updated on Jul 20, 2024.

Text editor powered by tinymce.