CircuitPython I2C

I2C is a 2-wire protocol for communicating with simple sensors and devices, meaning it uses two connections for transmitting and receiving data. There are many I2C devices available and they're really easy to use with CircuitPython. We have libraries available for many I2C devices in the library bundle. (If you don't see the sensor you're looking for, keep checking back, more are being written all the time!)

In this section, we're going to do is learn how to scan the I2C bus for all connected devices. Then we're going to learn how to interact with an I2C device.

We'll be using the TSL2561, a common, low-cost light sensor. While the exact code we're running is specific to the TSL2561 the overall process is the same for just about any I2C sensor or device.

You'll need the adafruit_tsl2561.mpy library and adafruit_bus_device library folder if you don't already have it in your /lib folder! You can get it from the CircuitPython Library Bundle. If you need help installing the library, check out the CircuitPython Libraries page.

These examples will use the TSL2561 lux sensor Flora and breakout. The first thing you'll want to do is get the sensor connected so your board has I2C to talk to.

Wire It Up

You'll need a couple of things to connect the TSL2561 to your board.

For Gemma M0 and Circuit Playground Express, you can use use alligator clips to connect to the Flora TSL2561 Lux Sensor.

For Trinket M0, Feather M0 Express, Metro M0 Express and ItsyBitsy M0 Express, you'll need a breadboard and jumper wires to connect to the TSL2561 Lux Sensor breakout board.

We've included diagrams show you how to connect the TSL2561 to your board. In these diagrams, the wire colors match the same pins on each board.

  • The black wire connects between the ground pins.
  • The red wire connects between the power pins on the TSL2561 and your board.
  • The yellow wire connects from SCL on the TSL2561 to SCL on your board.
  • The blue wire connects from SDA on the TSL2561 to SDA on your board.

Check out the list below for a diagram of your specific board!

Be aware that the M0 boards do not have I2C pullup resistors built in! All of the Adafruit breakouts do, but if you're building your own board or using a non-Adafruit breakout, you must add 2.2K-10K ohm pullups on both SDA and SCL to the 3.3V.

Circuit Playground Express

 

  • Connect 3.3v on your CPX to 3.3v on your TSL2561.
  • Connect GND on your CPX to GND on your TSL2561.
  • Connect SCL/A4 on your CPX to SCL on your TSL2561.
  • Connect SDL/A5 on your CPX to SDA on your TSL2561.

Trinket M0

 

  • Connect USB on the Trinket to VIN on the TSL2561.
  • Connect Gnd on the Trinket to GND on the TSL2561.
  • Connect D2 on the Trinket to SCL on the TSL2561.
  • Connect D0 on the Trinket to SDA on the TSL2561.

Gemma M0

 

  • Connect 3vo on the Gemma to 3V on the TSL2561.
  • Connect GND on the Gemma to GND on the TSL2561.
  • Connect A1/D2 on the Gemma to SCL on the TSL2561.
  • Connect A2/D0 on the Gemma to SDA on the TSL2561.

Feather M0 Express and Feather M4 Express

 

  • Connect USB on the Feather to VIN on the TSL2561.
  • Connect GND on the Feather to GND on the TSL2561.
  • Connect SCL on the Feather to SCL on the TSL2561.
  • Connect SDA on the Feather to SDA on the TSL2561.

ItsyBitsy M0 Express and ItsyBitsy M4 Express

 

  • Connect USB on the ItsyBitsy to VIN on the TSL2561
  • Connect G on the ItsyBitsy to GND on the TSL2561.
  • Connect SCL on the ItsyBitsy to SCL on the TSL2561.
  • Connect SDA on the ItsyBitsy to SDA on the TSL2561.

Metro M0 Express and Metro M4 Express

 

  • Connect 5V on the Metro to VIN on the TSL2561.
  • Connect GND on the Metro to GND on the TSL2561.
  • Connect SCL on the Metro to SCL on the TSL2561.
  • Connect SDA on the Metro to SDA on the TSL2561.

Find Your Sensor

The first thing you'll want to do after getting the sensor wired up, is make sure it's wired correctly. We're going to do an I2C scan to see if the board is detected, and if it is, print out its I2C address.

Copy and paste the code into code.py using your favorite editor, and save the file.

# CircuitPython demo - I2C scan

import time

import board
import busio

i2c = busio.I2C(board.SCL, board.SDA)

while not i2c.try_lock():
    pass

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

First we create the i2c object and provide the I2C pins, board.SCL and board.SDA.

To be able to scan it, we need to lock the I2C down so the only thing accessing it is the code. So next we include a loop that waits until I2C is locked and then continues on to the scan function.

Last, we have the loop that runs the actual scan, i2c_scan(). Because I2C typically refers to addresses in hex form, we've included this bit of code that formats the results into hex format: [hex(device_address) for device_address in i2c.scan()].

Open the serial console to see the results! The code prints out an array of addresses. We've connected the TSL2561 which has a 7-bit I2C address of 0x39. The result for this sensor is I2C addresses found: ['0x39']. If no addresses are returned, refer back to the wiring diagrams to make sure you've wired up your sensor correctly.

I2C Sensor Data

Now we know for certain that our sensor is connected and ready to go. Let's find out how to get the data from our sensor!

Copy and paste the code into code.py using your favorite editor, and save the file.

# CircuitPython Demo - I2C sensor

import time

import adafruit_tsl2561
import board
import busio

i2c = busio.I2C(board.SCL, board.SDA)

# Lock the I2C device before we try to scan
while not i2c.try_lock():
    pass
# Print the addresses found once
print("I2C addresses found:", [hex(device_address)
                               for device_address in i2c.scan()])

# Unlock I2C now that we're done scanning.
i2c.unlock()

# Create library object on our I2C port
tsl2561 = adafruit_tsl2561.TSL2561(i2c)

# Use the object to print the sensor readings
while True:
    print("Lux:", tsl2561.lux)
    time.sleep(1.0)

This code begins the same way as the scan code. We've included the scan code so you have verification that your sensor is wired up correctly and is detected. It prints the address once. After the scan, we unlock I2C with i2c_unlock() so we can use the sensor for data.

We create our sensor object using the sensor library. We call it tsl2561 and provide it the i2c object.

Then we have a simple loop that prints out the lux reading using the sensor object we created. We add a time.sleep(1.0), so it only prints once per second. Connect to the serial console to see the results. Try shining a light on it to see the results change!

Where's my I2C?

On the SAMD21, we have the flexibility of using a wide range of pins for I2C. Some chips, like the ESP8266 can use any pins for I2C, using bitbangio. There's some other chips that may have fixed I2C pin.  

The good news is you can use many but not all pins. Given the large number of SAMD boards we have, its impossible to guarantee anything other than the labeled 'SDA' and 'SCL'. So, if you want some other setup, or multiple I2C interfaces, how will you find those pins? Easy! We've written a handy script.

All you need to do is copy this file to your board, rename it code.py, connect to the serial console and check out the output! The results print out a nice handy list of SCL and SDA pin pairs that you can use.

These are the results from an ItsyBitsy M0 Express. Your output may vary and it might be very long. For more details about I2C and SERCOMs, check out our detailed guide here.

import board
import busio
from microcontroller import Pin

def is_hardware_I2C(scl, sda):
    try:
        p = busio.I2C(scl, sda)
        p.deinit()
        return True
    except ValueError:
        return False
    except RuntimeError:
        return True


def get_unique_pins():
    exclude = ['NEOPIXEL', 'APA102_MOSI', 'APA102_SCK']
    pins = [pin for pin in [
        getattr(board, p) for p in dir(board) if p not in exclude]
            if isinstance(pin, Pin)]
    unique = []
    for p in pins:
        if p not in unique:
            unique.append(p)
    return unique


for scl_pin in get_unique_pins():
    for sda_pin in get_unique_pins():
        if scl_pin is sda_pin:
            continue
        else:
            if is_hardware_I2C(scl_pin, sda_pin):
                print("SCL pin:", scl_pin, "\t SDA pin:", sda_pin)
            else:
                pass
This guide was first published on Oct 12, 2017. It was last updated on Sep 20, 2018. This page (CircuitPython I2C) was last updated on Jul 13, 2018.