Let's talk to an I2C sensor!

The Pico has two I2C ports. Remember that you can attach multiple sensors to a single port as long as each has a unique I2C address. So you don't need to use two just because you have two sensors.

We'll use the MSA301 sensor which can read acceleration. Here we show wiring via the header pins. But if you wanted to use the STEMMA QT connector, you could by using one of the pigtail breakout cables.

Trying to use an I2C port with nothing attached can cause the system to hang.
I2C0 is the default port used by board.I2C() and SCL/SDA pins.

Install MSA301 Library

To install the MSA301 library, run the following:

sudo pip3 install adafruit-circuitpython-msa301

Note that this step is the same as shown in the main MSA301 guide. You would do the same general process for any other sensor with a CircuitPython library.

Example Code

And then we can run the example from the library. Download it from here:

save it as msa301_simpletest.py and run it with:

python3 msa301_simpletest.py

Pick up the board and spin it around. You should see the values change:

Live Plot Example

This one is a little fancier and requires matplotlib to be installed on the host PC as well. This is the example shown running in the guide thumbnail image.

Here's the code:

import board
import busio
import adafruit_msa301

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from collections import deque
import time

i2c = busio.I2C(board.SCL1, board.SDA1)

msa = adafruit_msa301.MSA301(i2c)


x_time = [x * REFRESH_RATE for x in range(HIST_SIZE)]

y_data = [deque([None] * HIST_SIZE, maxlen=HIST_SIZE) for _ in range(3)]

fig, ax = plt.subplots(1, 1)
fig.canvas.manager.set_window_title("MSA301 Acceleration")

ax.grid(True, linestyle=':')
ax.set_xlim(min(x_time), max(x_time))
ax.set_ylim(-15, 15)

lines = []
for data in y_data:
    line, = ax.plot(x_time, data)

lines[0].set_color('#d1ff7a'); lines[0].set_linewidth(3)
lines[1].set_color('#7af6ff'); lines[1].set_linewidth(3)
lines[2].set_color('#ff36fc'); lines[2].set_linewidth(3)

def animate(foo):
    for i, a in enumerate(msa.acceleration):

ani = animation.FuncAnimation(fig, animate, interval=REFRESH_RATE)

This guide was first published on May 01, 2021. It was last updated on Sep 06, 2023.

This page (I2C) was last updated on Apr 26, 2021.

Text editor powered by tinymce.