# bus_scan.py 

# Raspberry Pi Pico - I2C Bus Scan
# Search for devices on an I2C bus.

#---- electrical connections ---------------------------------------------------
# The Pico has two hardware I2C ports which can each be mapped to a number of
# possible pin pairs.  This example uses pins 6 and 7 for I2C0 SDA
# and SCL.  For alternate choices please see the official pinout diagram.

# Pico                  description
# pin 7/GP5/I2C0 SCL    I2C clock from port 0
# pin 6/GP4/I2C0 SDA    I2C data from port 0
# pin 38/GND            common ground

#-------------------------------------------------------------------------------
# related CircuitPython module documentation:

# busio             https://circuitpython.readthedocs.io/en/latest/shared-bindings/busio/index.html
# time              https://circuitpython.readthedocs.io/en/latest/shared-bindings/time/index.html
# board             https://circuitpython.readthedocs.io/en/latest/shared-bindings/board/index.html

#-------------------------------------------------------------------------------
# load standard Python modules
import time

# load the CircuitPython hardware definition module for pin definitions
import board

# load the CircuitPython I2C support
import busio

#---------------------------------------------------------------
# The device is connected to I2C0 on pins 6 and 7.
i2c = busio.I2C(scl=board.GP5, sda=board.GP4)

#---------------------------------------------------------------
# Scan for devices.
if i2c.try_lock():
    print("Starting I2C scan.")
    devices = i2c.scan()
    i2c.unlock()
    
    print("Found %d I2C device(s)." % (len(devices)))
    for dev in devices:
        print("  I2C address:  %d (0x%x)" % (dev, dev))

else:
    print("Unable to lock I2C interface.")
