The examples in this guide are no longer supported. Check out the MPR121 sensor guide for CircuitPython and Python usage:

Example Code

Once the library is installed you can run an example program to test the capacitive touch inputs.  Navigate to the examples folder of the library and run the example by executing:

cd examples
sudo python

Note that the example is run as a root user with the sudo command, this is required to access the hardware on the Pi.

Once the example is running you should see text like the following printed on the screen:

Adafruit MPR121 Capacitive Touch Sensor Test
Press Ctrl-C to quit.

Try pressing some of the capacitive inputs you've connected (or even just touching the solder joints of the inputs!).  You should see a message each time an input is pressed and released, for example:

11 touched!
10 touched!
10 released!
11 released!
10 touched!
11 touched!
10 released!
11 released!

When you're finished, press Ctrl-C to quit the program.

Library Usage

To understand how the library works, let's examine the example code in detail.  Open the file in a text editor and follow along as I explain each important part below.

import sys
import time

import Adafruit_MPR121.MPR121 as MPR121

print 'Adafruit MPR121 Capacitive Touch Sensor Test'

First you'll see the example import modules which it will use and print a message on the screen.  Note the Adafruit_MPR121.MPR121 module which is imported as the shorter MPR121 name.  This module is the MPR121 library that was installed earlier and this line will make it available to our python program.

# Create MPR121 instance.
cap = MPR121.MPR121()

# Initialize communication with MPR121 using default I2C bus of device, and 
# default I2C address (0x5A).  On BeagleBone Black will default to I2C bus 0.
if not cap.begin():
    print 'Error initializing MPR121.  Check your wiring!'

# Alternatively, specify a custom I2C address such as 0x5B (ADDR tied to 3.3V),
# 0x5C (ADDR tied to SDA), or 0x5D (ADDR tied to SCL).

# Also you can specify an optional I2C bus with the bus keyword parameter.

Next an instance of the MPR121 class is created and initialized.  You can see the first line creates the object, and the next lines call the begin() function to initialize the device.  It's very important to make sure you call begin() before you call any other functions on the MPR121 object.

Also notice in the comments that you can customize the I2C address or bus by sending optional parameters to the begin() function.  By default the function will try to pick the right I2C bus for your device but these parameters allow you to specify explicit values.

# Main loop to print a message every time a pin is touched.
print 'Press Ctrl-C to quit.'
last_touched = cap.touched()
while True:
    current_touched = cap.touched()
    # Check each pin's last and current state to see if it was pressed or released.
    for i in range(12):
        # Each pin is represented by a bit in the touched value.  A value of 1
        # means the pin is being touched, and 0 means it is not being touched.
        pin_bit = 1 << i
        # First check if transitioned from not touched to touched.
        if current_touched & pin_bit and not last_touched & pin_bit:
            print '{0} touched!'.format(i)
        # Next check if transitioned from touched to not touched.
        if not current_touched & pin_bit and last_touched & pin_bit:
            print '{0} released!'.format(i)
    # Update last state and wait a short period before repeating.
    last_touched = current_touched

Now the program enters its main loop where it reads each input and checks if it's changed.  

The most important thing to see is the touched() function.  This function returns a 12-bit value where each bit represents one of the 12 inputs on the MPR121 board.  Bit 0 represents input 0, bit 1 represents input 1, etc. all the way up to bit 11 and input 11.  If a bit is 1 then the input is being touched, and if it's 0 then the input is not being touched.  

This loop will compare the previous value for each bit to its current value, so if the value changes a message can be printed.  Detecting if an input is touched is as simple as calling the touched() function and checking the value of a bit!

    # Alternatively, if you only care about checking one or a few pins you can 
    # call the is_touched method with a pin number to directly check that pin.
    # This will be a little slower than the above code for checking a lot of pins.
    #if cap.is_touched(0):
    #    print 'Pin 0 is being touched!'

Further below you can see commented code which describes how to use the is_touched() function.  This function is a little simpler than the touched() function as it only checks if one input is being touched and returns True (input is being touched) or False (input is not being touched).  If you only need to check one or a few inputs this function might be an easier option.

    # If you're curious or want to see debug info for each pin, uncomment the
    # following lines:
    #print '\t\t\t\t\t\t\t\t\t\t\t\t\t 0x{0:0X}'.format(cap.touched())
    #filtered = [cap.filtered_data(i) for i in range(12)]
    #print 'Filt:', '\t'.join(map(str, filtered))
    #base = [cap.baseline_data(i) for i in range(12)]
    #print 'Base:', '\t'.join(map(str, base))

Finally the last commented section shows how you can see interesting debug info for the device.  The filtered_data() and baseline_data() functions each can be called to look up the filtered data and baseline data register values for an input.  Read the MPR121 datasheet to better understand how the chip uses baseline and filtered data to detect touches.

That's all there is to using the MPR121 library!  If you find issues or would like to contribute to the library, feel free to do so at it's home on GitHub.

This guide was first published on Dec 23, 2014. It was last updated on Mar 08, 2024.

This page (Usage) was last updated on Mar 08, 2024.

Text editor powered by tinymce.