An I2C scanner example for CircuitPython is provided in the CircuitPython Essentials guide. Here's the code:

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

"""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 board

# To use default I2C bus (most boards)
i2c = board.I2C()  # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller

# To create I2C bus on specific pins
# import busio
# i2c = busio.I2C(board.SCL1, board.SDA1)  # QT Py RP2040 STEMMA connector
# i2c = busio.I2C(board.GP1, board.GP0)    # Pi Pico RP2040

while not i2c.try_lock():
    pass

try:
    while True:
        print(
            "I2C addresses found:",
            [hex(device_address) for device_address in i2c.scan()],
        )
        time.sleep(2)

finally:  # unlock the i2c bus when ctrl-c'ing out of the loop
    i2c.unlock()

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

Specify Alternate I2C Bus

The example sketch above uses the default board.I2C() bus. To run the I2C scan on a different bus the bus will need to be created using busio and the correct pins. There is some commented out code that can be used as a general reference:

# import busio
# i2c = busio.I2C(board.SCL1, board.SDA1)  # QT Py RP2040 STEMMA connector
# i2c = busio.I2C(board.GP1, board.GP0)    # Pi Pico RP2040

Normal Behavior

If all goes well, you should get a list of addresses for each device found. In the example below, an Adafruit BMP280 breakout is attached to a QT Py M0.

The BMP280's I2C address of 0x77 shows up as expected.

Missing Device or Pull Ups

If the device is disconnect and/or the pull up resistors are missing, the results will look like this:

This is a neat feature of CircuitPython. It actually checks for the presence of the pull up resistors and shows an error message if they are not detected.

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

This page (CircuitPython) was last updated on Jun 07, 2023.

Text editor powered by tinymce.