Add lots of touch sensors to your next microcontroller project with this easy-to-use 12-channel capacitive touch sensor breakout board, starring the MPR121. This chip can handle up to 12 individual touchpads with plug-and-play STEMMA QT connector and large alligator/croc-clip friendly pads, it's a no-solder solution to capacitive touch sensing.

The MPR121 has support for reading data over I2C, which can be implemented with nearly any microcontroller. You can select one of 2 addresses with the ADDR pin (solder it close for the alternative address), for a total of 24 capacitive touch pads on one I2C 2-wire bus. Using this chip is a lot easier than doing the capacitive sensing with analog inputs: it handles all the filtering for you and can be configured for more/less sensitivity.

This sensor comes as a tiny hard-to-solder chip, so we put it onto a breakout board for you. Since it's a 3V-only chip, we added a 3V regulator and I2C level shifting so it's safe to use with any 3V or 5V microcontroller/processor like Arduino. We even added an LED onto the IRQ line so it will blink when touches are detected, making debugging by sight a bit easier on you.

Comes with a fully assembled board. For contacts, we suggest using copper foil, metallic nylon, or pyralux, then connect up any alligator clip from the conductive material to one of the big pads on the breakout.

To make using it as easy as possible, we’ve put the MPR121 on a breakout PCB  in our Stemma QT form factor with a sprinkle of support circuitry to give you options when testing. You can either use a breadboard or the SparkFun qwiic compatible STEMMA QT connectors, and compatibility with 5V voltage levels as commonly found on Arduinos, as well as 3.3V logic used by many other boards like the Raspberry Pi or our Feathers. QT Cable is not included, but we have a variety in the shop for quick plug-and-play support.

Getting started is a breeze with our Arduino and CircuitPython/Python libraries and tutorials. You'll be up and running in a few minutes, and if you are using another microcontroller, it's easy to port our code.

The little chip in the middle of the PCB is the actual MPR121 sensor that does all the capacitive sensing and filtering. We add all the extra components you need to get started, and you can connect to this board using STEMMA QT / QWIIC connectors. There are a series of 12 chonkpads for touch sensing with your finger or for easily connecting up alligator/croc clips.

STEMMA QT Connector Pins

The STEMMA QT connectors allow you to connectors to dev boards with STEMMA QT connectors or to other things with various associated accessories.

The sensor on the breakout requires 3V power. Since many customers have 5V microcontrollers like Arduino, we tossed a 3.3V regulator on the board. Its ultra-low dropout so you can power it from 3.3V-5V just fine.

  • Vin - this is the power pin. Since the chip uses 3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V micro like Arduino, use 5V
  • GND - common ground for power and logic
  • SCL - I2C clock pin, connect to your microcontrollers I2C clock line. Can use 3V or 5V logic, and has a 10K pullup.
  • SDA - I2C data pin, connect to your microcontrollers I2C data line. Can use 3V or 5V logic, and has a 10K pullup.

Address Jumper

The default I2C address for this chip is 0x5A.

  • addr - This jumper can be bridged to change the I2C address to 0x5B.

You can easily wire this breakout to any microcontroller, we'll be using an Arduino. For another kind of microcontroller, just make sure it has I2C, then port the code - it's pretty simple stuff!

Wiring

Connect the breakout to your Arduino compatible board. An example is shown below connected to an Adafruit Metro.

  • Connect Vin (red wire) to the power supply, 3-5V is fine. Use the same voltage that the microcontroller logic is based off of. For most Arduinos, that is 5V
  • Connect GND (black wire) to common power/data ground
  • Connect the SCL (yellow wire) pin to the I2C clock SCL pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A5, on a Mega it is also known as digital 21 and on a Leonardo/Micro, digital 3
  • Connect the SDA (blue wire) pin to the I2C data SDA pin on your Arduino. On an UNO & '328 based Arduino, this is also known as A4, on a Mega it is also known as digital 20 and on a Leonardo/Micro, digital 2

Download Adafruit_MPR121

To begin reading sensor data, you will need to download the Adafruit_MPR121 library from the Arduino library manager.

Open up the Arduino library manager:

Seach for the Adafruit MPR121 library and install it

We also have a great tutorial on Arduino library installation at:
http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use

Load Demo

Open up File->Examples->Adafruit_MPR121->MPR121test and upload to your Arduino wired up to the sensor

Thats it! Now open up the serial terminal window at 9600 speed to begin the test.

Make sure you see the "MPR121 found!" text which lets you know that the sensor is wired correctly.

Now touch the 12 pads with your fingertip to activate the touch-detection

For most people, that's all you'll need! Our code keeps track of the 12 'bits' for each touch and has logic to let you know when a contect is touched or released.

If you're feeling more advanced, you can see the 'raw' data from the chip. Basically, what it does it keep track of the capacitance it sees with "counts". There's some baseline count number that depends on the temperature, humidity, PCB, wire length etc. Where's a dramatic change in number, its considered that a person touched or released the wire.

Comment this "return" line to activate that mode:

// comment out this line for detailed data from the sensor!
return;

Then reupload. Open up the serial console again - you'll see way more text

Each reading has 12 columns. One for each sensor, #0 to #11. There's two rows, one for the 'baseline' and one for the current filtered data reading. When the current reading is within about 12 counts of the baseline, that's considered untouched. When the reading is more than 12 counts smaller than the baseline, the chip reports a touch.

Most people don't need raw data too much, but it can be handy if doing intense debugging. It can be helpful if you are tweaking your sensors to get good responsivity.

Library Reference

Since the sensors use I2C, there's no pins to be defined during instantiation. You can just use:

Adafruit_MPR121 cap = Adafruit_MPR121();

When you initialize the sensor, pass in the I2C address. It can range from 0x5A (default) to 0x5D

cap.begin(0x5A)

begin() returns true if the sensor was found on the I2C bus, and false if not.

Touch detection

99% of users will be perfectly happy just querying what sensors are currently touched. You can read all at once with cap.touched(), which returns a 16 bit value. Each of the bottom 12 bits refers to one sensor. So if you want to test if the #4 is touched, you can use

if (cap.touched() & (1 << 4)) { do something }

You can check its not touched with:

if (! (cap.touched() & (1 << 4)) ) { do something }

Raw Data

You can grab the current baseline and filtered data for each sensor with

filteredData(sensornumber);
baselineData(sensornumber);

It returns a 16-bit number which is the number of counts, there's no unit like "mg" or "capacitance". The baseline is initialized to the current ambient readings when the sensor begin() is called - you can always reinitialize by re-calling begin()! The baseline will drift a bit, that's normal! It is trying to compensate for humidity and other environmental changes.

If you need to change the threshholds for touch detection, you can do that with

setThreshholds(uint8_t touch, uint8_t release)

By default, the touch threshhold is 12 counts, and the release is 6 counts. It's reset to these values whenever you call begin() by the way.

It's easy to use the MPR121 sensor with Python or CircuitPython and the Adafruit CircuitPython MPR121 module.  This module allows you to easily write Python code that reads capacitive touch from the sensor.

You can use this sensor with any CircuitPython microcontroller board or with a computer that has GPIO and Python thanks to Adafruit_Blinka, our CircuitPython-for-Python compatibility library.

CircuitPython Microcontroller Wiring

Wire up the board as seen below. Here's an example of wiring a Feather M4 to the sensor with I2C using the STEMMA QT connector on the breakout:

  • Board 3V to sensor VIN (red wire)
  • Board GND to sensor GND (black wire)
  • Board SCL to sensor SCL (yellow wire)
  • Board SDA to sensor SDA (blue wire)

Python Computer Wiring

Since there's dozens of Linux computers/boards you can use, we will show wiring for Raspberry Pi. For other platforms, please visit the guide for CircuitPython on Linux to see whether your platform is supported

Here's the Raspberry Pi wired with I2C:

  • Pi 3V3 to sensor VIN (red wire)
  • Pi GND to sensor GND (black wire)
  • Pi SCL to sensor SCL (yellow wire)
  • Pi SDA to sensor SDA (blue wire)

CircuitPython Installation of MPR121 Library

You'll need to install the Adafruit CircuitPython MPR121 library on your CircuitPython board.

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you'll need to install the necessary libraries to use the hardware. Carefully follow the steps to find and install these libraries from Adafruit's CircuitPython library bundle.  Our CircuitPython starter guide has a great page on how to install the library bundle.

For non-Express boards like the Trinket M0 or Gemma M0, you'll need to manually install the necessary libraries from the bundle:

  • adafruit_mpr121.mpy
  • adafruit_bus_device

Before continuing, make sure your board's lib folder has the adafruit_mpr121.mpy and adafruit_bus_device files and folders copied over.

Next connect to the board's serial REPL so you are at the CircuitPython >>> prompt.

Python Installation of MPR121 Library

You'll need to install the Adafruit_Blinka library that provides the CircuitPython support in Python. This may also require enabling I2C on your platform and verifying you are running Python 3. Since each platform is a little different, and Linux changes often, please visit the CircuitPython on Linux guide to get your computer ready!

Once that's done, from your command line run the following command:

  • sudo pip3 install adafruit-circuitpython-mpr121

If your default Python is version 3 you may need to run 'pip' instead. Just make sure you aren't trying to use CircuitPython on Python 2.x, it isn't supported!

CircuitPython & Python Usage

To demonstrate the usage of the sensor, we'll initialize it and read capacitive touch from the board's Python REPL.

If you're using an I2C connection, run the following code to import the necessary modules and initialize the I2C connection with the sensor:

import time
import board
import busio
import adafruit_mpr121
i2c = busio.I2C(board.SCL, board.SDA)
mpr121 = adafruit_mpr121.MPR121(i2c)

Now you're ready to read capacitive touch from the sensor. Use the following syntax to check a specific pin.

  • mpr121[i].value - Return True if the specified pin is being touched, otherwise returns False.

Use a value 0 to 11 for [i] and it will return a boolean True or False value depending on if the input is currently being touched or not.

For example, to print when pin 0 is touched, run the following code, and then touch pin 0:

while True:
    if mpr121[0].value:
        print("Pin 0 touched!")

If you don't see any messages when you touch the inputs, you might need to ground yourself to the board by touching the GND pin on the board with one finger and then touching the input pads with another finger.  

Also make sure nothing is touching the pins when you first run the code, or else it might confuse the MPR121's touch detection (unmount the board's file system from your operating system, then press the board's reset button to reset the script and run it again with nothing touching the pins). The pins are calibrated on start-up, and will not react properly if you're touching the pins when the board starts up.

To print when any pin is touched, run the following code and then touch any capacitive touch pin:

while True:
    for i in range(12):
        if mpr121[i].value:
            print('Input {} touched!'.format(i))

The example doesn't show its usage, but if you want to check all of the inputs at once you can use touched_pins. This function returns a 12 member tuple of the current state for each of the 12 pins. True is touched and False is not touched. For example, to test if pin 0 and 11 are being touched with one call you could run code like:

# Use touched_pins to get current state of all pins.
touched = mpr121.touched_pins
# Test if 0 and 11 are touched.
if touched[0] and touched[11]:
    print('Input 0 and 11 touched!')

That's all there is to using the MPR121 module with CircuitPython!

Full Example Code

# SPDX-FileCopyrightText: 2017 Tony DiCola for Adafruit Industries
# SPDX-License-Identifier: MIT

# Simple test of the MPR121 capacitive touch sensor library.
# Will print out a message when any of the 12 capacitive touch inputs of the
# board are touched.  Open the serial REPL after running to see the output.
# Author: Tony DiCola
import time
import board
import busio

# Import MPR121 module.
import adafruit_mpr121

# Create I2C bus.
i2c = busio.I2C(board.SCL, board.SDA)

# Create MPR121 object.
mpr121 = adafruit_mpr121.MPR121(i2c)

# Note you can optionally change the address of the device:
# mpr121 = adafruit_mpr121.MPR121(i2c, address=0x91)

# Loop forever testing each input and printing when they're touched.
while True:
    # Loop through all 12 inputs (0-11).
    for i in range(12):
        # Call is_touched and pass it then number of the input.  If it's touched
        # it will return True, otherwise it will return False.
        if mpr121[i].value:
            print("Input {} touched!".format(i))
    time.sleep(0.25)  # Small delay to keep from spamming output messages.

One great use for the MPR121 is as a capacitive touch keyboard, where pressing a touch input causes a key to be pressed on a Raspberry Pi. This is kind of like a MaKey MaKey, but built right into the Pi using just the MPR121 and some special software.  You could for example configure the MPR121 to act as a giant gamepad that controls games on the Raspberry Pi!

Wiring

To use the MPR121 as a virtual keyboard you'll first want to make sure you've followed the earlier pages in this guide to connect the MPR121 to the Raspberry Pi and install the software.

Dependencies

Now open a terminal on the Raspberry Pi using SSH and execute the following commands to install a few dependencies required by the virtual keyboard script:

sudo apt-get update
sudo apt-get install libudev-dev
sudo pip3 install python-uinput
sudo pip3 install adafruit-circuitpython-mpr121

Configuration

After the dependencies are installed navigate to the MPR121 library examples folder again.  Open the pi_keyboard.py script in a text editor such as nano by executing:

nano pi_keyboard.py

Now scroll down to the key configuration near the top of the file:

KEY_MAPPING = {                                                                                                                                                                                                                                                                
    0: uinput.KEY_UP,                                                                                                                                                                                                                                                          
    1: uinput.KEY_DOWN,                                                                                                                                                                                                                                                        
    2: uinput.KEY_LEFT,                                                                                                                                                                                                                                                        
    3: uinput.KEY_RIGHT,                                                                                                                                                                                                                                                       
    4: uinput.KEY_B,                                                                                                                                                                                                                                                           
    5: uinput.KEY_A,                                                                                                                                                                                                                                                           
    6: uinput.KEY_ENTER,                                                                                                                                                                                                                                                       
    7: uinput.KEY_SPACE,                                                                                                                                                                                                                                                       
}

The KEY_MAPPING variable is a dictionary that maps an input number on the MPR121 to a keyboard button that will be sent when the input is pressed.

For example the code above configures input 0 to the UP key, input 1 to the DOWN key, input 2 to the LEFT key, etc.

Adjust the inputs and key codes depending on your needs.  Most of the key codes are self explanatory (i.e. the key code for the letter Q is uinput.KEY_Q), but if you are unsure of an input you can find the name of a keycode in the Linux input header here.  Take the key name and add uinput. to the front of it to get the key code that should be in the configuration above.

If you need to add more inputs you can add them as new lines after input 7 above.  Be careful to make sure each new line ends in a comma so the python dictionary is defined correctly.

After you've configured your key mapping save the file by pressing Ctrl-O and Enter, then quit by pressing Ctrl-X.

Usage

Now run the program by executing:

sudo python3 pi_keyboard.py

After a moment you should see a message displayed that tells you to press Ctrl-C to quit the program.  If you press inputs to the MPR121 they should send the keys you've configured to the Raspberry Pi!

Note that you won't see any output from the program when keys are pressed, unless you first enable logging by un-commenting the following line:

# Uncomment to enable debug message logging (might slow down key detection).                                                                                                                                                                                                   
logging.basicConfig(level=logging.DEBUG)

Quit the program by pressing Ctrl-C.

Launch In Background

Running the program by itself is great, but you probably want to run the program in the background while a game or other application runs and takes input from the MPR121 key presses.  To do this you can launch the program into the background by executing at the terminal:

sudo python keyboard.py &

You should see a response such as:

[1] 2251

This tells you the program is launched in the background and is currently running under the process ID 2251.  Try to remember the process ID as it will help you shut down the program later (but don't worry, I'll show you how to shut down the program even if you forget the ID).

Now run a game or other program that relies on keyboard input. Try pressing inputs on the MPR121 and you should see them register as keyboard presses!

Stop Background Process

To stop the background process you'll need to tell Linux to kill the python keyboard.py process that was launched in the background earlier.  If you remember the process ID number you can skip below to the kill command.  However if you forgot the process ID number you can find it by executing a command like this to search all running processes for the keyboard.py script:

ps aux | grep keyboard.py

You should see a list of processes such as:

root      2251  0.5  0.3   5136  1488 pts/0    S    09:13   0:00 sudo python keyboard.py
root      2252 13.2  1.4  18700  5524 pts/0    Sl   09:13   0:00 python keyboard.py
pi        2294  0.0  0.2   4096   804 pts/0    S+   09:13   0:00 grep --color=auto keyboard.py

The first line with sudo python keyboard.py is the background process that was launched earlier.  You can kill this process by running:

sudo kill 2251

If you run the ps command above again you should now see the Python keyboard.py processes have terminated.

That's all there is to using the MPR121 virtual keyboard on a Raspberry Pi.  Have fun using the capacitive touch buttons to control your own games and programs!

This guide was first published on Dec 30, 2020. It was last updated on Mar 18, 2024.