Components · 8 min read

MPR121 Arduino: 12-Key Capacitive Touch Sensor and Fruit Piano

MPR121 Arduino guide: I2C wiring, fruit, foil and conductive paint electrodes, threshold and filter tuning, TTP223 vs ESP32 touch, piano and keyboard code.

With an MPR121 Arduino setup you can read 12 separate touch keys over a single I2C bus. The MPR121 is a 12-channel capacitive touch sensor controller, each channel wired to an electrode: the electrode can be a metal plate, a piece of aluminium foil, a key drawn in conductive paint or even a banana. When your finger approaches the electrode the capacitance changes, the MPR121 measures it and tells the Arduino which key was touched. That lets you build a piano out of fruit, a game controller out of cardboard or a light switch painted on the wall.

In this article we explain how the MPR121 measures, how to wire it to an Arduino Uno, Leonardo and ESP32, which electrode materials work, the threshold and filter settings that confuse people most, and how it compares with the TTP223 and the ESP32's built-in touch pins. After that you'll find complete code for a touch piano, a Makey Makey style USB keyboard and an ESP32 example.

What is the MPR121 and how does it work?

The MPR121 charges each electrode with a constant current for a set time and measures the resulting voltage with a 10-bit ADC. The larger the electrode's capacitance, the lower the voltage. When your finger touches or gets very close to the electrode it adds its own capacitance, and the measured value (filtered data) drops by a few to a few dozen counts. The chip also keeps a slowly updated baseline for each electrode. When the difference between the baseline and the current value exceeds the touch threshold, the channel becomes "touched"; when it falls below the release threshold, it becomes "released". Because the baseline updates slowly, slow changes such as temperature, humidity or a cable being moved don't create false touches.

FeatureMPR121
Channels12 electrodes (ELE0–ELE11) plus 1 virtual proximity channel
InterfaceI2C up to 400 kHz, plus an IRQ output (active low)
Chip supply1.71–3.6 V (modules are usually 3.3 V)
I2C address0x5A, 0x5B, 0x5C or 0x5D (set by the ADD pin)
Measurement10-bit, adjustable charge current (1–63 µA) and time (0.5–32 µs)
Extra featureELE4–ELE11 can be used as GPIO or LED drivers
ConsumptionAbout 29 µA at a 16 ms sample interval, fine for battery projects

MPR121 wiring: Arduino Uno, Leonardo and ESP32

MPR121 pinArduino UnoArduino LeonardoESP32
VCC (3.3V)3.3V3.3V3V3
GNDGNDGNDGND
SDAA4D2 (SDA)GPIO 21
SCLA5D3 (SCL)GPIO 22
IRQD2 (optional)D7 (optional)GPIO 19 (optional)
ADDGND (address 0x5A)GND (address 0x5A)GND (address 0x5A)
0–11ElectrodesElectrodesElectrodes
Most cheap blue MPR121 boards have no regulator or level shifter, and the chip can't take more than 3.6 V. Always power these boards from 3.3 V. Since the Arduino Uno and Leonardo use 5 V logic, a logic level converter on SDA and SCL is the safest option. Boards with an on-board regulator (such as Adafruit's MPR121 breakout) run from 3–5 V and can be connected directly. The ESP32 is already 3.3 V, so no extra parts are needed.

The ADD pin sets the I2C address, so you can put four MPR121 boards on the same bus and get 48 touch keys. On some boards ADD comes tied to GND through a solder trace on the back; to change the address you have to cut that trace. For more on I2C, see the what is I2C article.

ADD connected toI2C addressbegin() call
GND0x5Acap.begin(0x5A)
3.3 V0x5Bcap.begin(0x5B)
SDA0x5Ccap.begin(0x5C)
SCL0x5Dcap.begin(0x5D)

First test: which electrode was touched?

  1. Open the Library Manager in the Arduino IDE, search for Adafruit MPR121 and install it; accept the Adafruit BusIO dependency if asked.
  2. Wire the MPR121 as in the pin table and plug a jumper wire into electrode 0.
  3. Upload the code below and open the Serial Monitor at 9600 baud.
  4. Touch the metal end of the wire; the monitor should print "0 touched" and "0 released" when you pull your finger away.
  5. Don't touch the electrodes while the code starts; the MPR121 records its first readings as the baseline.
C++ (Arduino IDE)
1// MPR121 ilk test: hangi elektrota dokunuldu, hangisi bırakıldı?
2// MPR121 first test: which electrode was touched, which was released?
3#include <Wire.h>
4#include <Adafruit_MPR121.h>
5
6Adafruit_MPR121 cap;
7uint16_t lastTouched = 0;   // Önceki durum (12 bit) / previous state (12 bits)
8
9void setup() {
10  Serial.begin(9600);
11  if (!cap.begin(0x5A)) {   // ADD pini GND'de / ADD pin to GND
12    Serial.println(F("MPR121 bulunamadi / not found"));
13    while (1) delay(10);
14  }
15  Serial.println(F("MPR121 hazir / ready"));
16}
17
18void loop() {
19  uint16_t touched = cap.touched();             // Her bit bir elektrot / one bit per electrode
20  for (uint8_t i = 0; i < 12; i++) {
21    bool now = bitRead(touched, i);
22    bool before = bitRead(lastTouched, i);
23    if (now && !before) { Serial.print(i); Serial.println(F(" dokunuldu / touched")); }
24    if (!now && before) { Serial.print(i); Serial.println(F(" birakildi / released")); }
25  }
26  lastTouched = touched;
27  delay(20);
28}

cap.touched() returns a 12-bit number in which each bit stands for one electrode: if bit 0 is 1, electrode 0 is being touched. The code compares this number with the previous reading; a bit going from 0 to 1 prints a touch event, from 1 to 0 a release event. That way the monitor isn't flooded with the same message while your finger stays on the electrode. If the IRQ pin is wired, you can read it and query I2C only when something has changed, keeping the Arduino less busy.

Fruit, foil and conductive paint as electrodes

In capacitive sensing the electrode doesn't need to be a good conductor; it only has to form a capacitance with your finger. That's why water-filled fruit, pencil lines and conductive paints work too. The bigger the electrode, the higher its base capacitance and the smaller the touch difference becomes in relative terms; very large electrodes need a lower threshold or auto-configuration. Count the wire between the electrode and the MPR121 as part of the electrode: long, bundled wires reduce sensitivity and cause false touches between neighbouring channels, so keep wires under 30 cm and apart from each other.

MaterialHow to connectTip
Banana, apple, orangePush the end of a jumper wire into the fruit or use an alligator clipKeep the fruit from touching each other, turn on auto-configuration
Aluminium foilGlue it to cardboard, tape or staple the wire end to it2–4 cm² per key is enough, lower the threshold for large foil
Conductive paintPaint keys on paper or a wall, bury the wire end in the paintTest only once it is fully dry
Soft pencil (6B–8B)Draw dark, thick lines on paper and tape the wire to the end of the lineGo over the line several times so it is unbroken
Copper tapeStick it behind acrylic or wood and solder the wireDetects even through 3 mm of acrylic, ideal for neat panels
Coins, screws, a glass of waterWrap the wire around it or hold it with an alligator clipFun for desk experiments and science fairs

Threshold and filter settings

The MPR121 has two thresholds: the touch threshold and the release threshold. A touch starts when the difference between the baseline and the current value exceeds the touch threshold and ends when it drops below the release threshold. Keeping the release threshold below the touch threshold creates hysteresis and stops values hovering at the limit from toggling the key on and off. The Adafruit library uses 12 and 6 by default; the typical range for the touch threshold is 5 to 48 (0x05–0x30). The defaults work well with small keys and short wires. Raise the thresholds for keys that trigger by themselves, and lower them for large electrodes that are hard to detect or keys behind plastic. The table below summarises the other important settings.

SettingRegisterLibrary defaultWhen to change it
Touch and release threshold0x41–0x5A (per channel)12 / 6Raise for false touches, lower if touches are missed
Debounce0x5B (DT and DR)0 (off)Ask for 1–3 consecutive samples in noisy setups
Charge current (CDC)0x5C (CONFIG1)16 µAFor large electrodes or when auto-configuration is off
Charge time, second filter and sample interval0x5D (CONFIG2: CDT, SFI, ESI)0.5 µs, 4 samples, 1 msRaise SFI for smoother values, ESI for lower consumption
Baseline tracking filters0x2B–0x35 (MHD, NHD, NCL, FDL)Set by the libraryIf the baseline adapts too fast or too slowly
Auto-configuration0x7B–0x7FOff (enabled via a begin parameter)Turn on for irregular electrodes such as fruit, foil or paint
C++ (Arduino IDE)
1// MPR121 eşik ve filtre ayarı: 0. elektrotun ham ve taban değerini Seri Çizici'de izle
2// MPR121 threshold and filter tuning: watch electrode 0's filtered and baseline data in the Serial Plotter
3#include <Wire.h>
4#include <Adafruit_MPR121.h>
5
6const uint8_t TOUCH_T = 12;     // Dokunma eşiği / touch threshold
7const uint8_t RELEASE_T = 6;    // Bırakma eşiği, dokunmadan küçük olmalı / release threshold, below touch
8const uint8_t CH = 0;           // İzlenen elektrot / electrode to watch
9
10Adafruit_MPR121 cap;
11
12void setup() {
13  Serial.begin(115200);
14  // Son parametre true: otomatik yapılandırma, her elektrota uygun şarj akımı ve süresi
15  // Last parameter true: auto-configuration, picks charge current and time per electrode
16  if (!cap.begin(0x5A, &Wire, TOUCH_T, RELEASE_T, true)) {
17    Serial.println(F("MPR121 bulunamadi / not found"));
18    while (1) delay(10);
19  }
20  cap.writeRegister(MPR121_DEBOUNCE, 0x22);  // Dokunma ve bırakma için 2 ardışık örnek / 2 samples for touch and release
21  cap.writeRegister(MPR121_CONFIG2, 0x31);   // CDT 0,5 µs, SFI 10 örnek, ESI 2 ms / CDT 0.5 us, SFI 10 samples, ESI 2 ms
22}
23
24void loop() {
25  int filtered = cap.filteredData(CH);   // Anlık filtreli değer / current filtered value
26  int baseline = cap.baselineData(CH);   // Yavaş izlenen taban / slowly tracked baseline
27  Serial.print(F("filtered:"));
28  Serial.print(filtered);
29  Serial.print(F(" baseline:"));
30  Serial.print(baseline);
31  Serial.print(F(" delta:"));
32  Serial.println(baseline - filtered);   // Dokununca büyür / grows when touched
33  delay(50);
34}

After uploading, open the Serial Plotter from the Tools menu in the Arduino IDE. The baseline line stays almost flat, while the filtered line drops when you touch and delta jumps up. Note how many counts delta wanders when you're not touching (noise) and how high it goes when you touch; put the touch threshold between those two values and the release threshold at about half of it. Writing 0x31 to CONFIG2 makes the second filter average 10 samples and measures each electrode every 2 ms; the response time is roughly SFI × ESI, so 20 ms. The final true parameter in begin() turns on auto-configuration: the MPR121 picks a suitable charge current and time for each electrode by itself, which is the biggest help with electrodes of different sizes such as fruit. Because the library's writeRegister() stops and restarts the chip automatically while writing registers, you can safely change these settings after begin().

TTP223 vs MPR121 vs ESP32 touch

TTP223 single-channel touch sensor module
A TTP223 is enough for one key, while the MPR121 shines in multi-key projects
FeatureTTP223MPR121ESP32 built-in touch
Channels112 (48 with four modules)10 (T0–T9)
InterfaceDigital output (HIGH / LOW)I2CInside the chip, touchRead()
Supply2–5.5 VChip 1.71–3.6 VThe ESP32's 3.3 V
TuningMode selected with solder jumpersPer-channel threshold, debounce and filtersThreshold in software, raw value readable
Raw valueNoneFiltered value and baselineYes, drops when touched on the classic ESP32
Fruit and foilWeakVery good, auto-configurationFair, sensitive to noise
Best useA single touch buttonPiano, Makey Makey, multi-key panelWi-Fi projects with few keys

If you want a single touch button, the TTP223 is the cheapest and easiest choice, since it gives a digital output without any code. If you're using an ESP32 and a few keys are enough, the chip's built-in touch pins do the job without extra parts; note, though, that on the classic ESP32 the value drops when touched while on the ESP32-S2 and S3 it rises, so the threshold logic depends on your board. For more than ten keys, irregular electrodes or a board without touch pins such as the Arduino Uno, the MPR121 is the most flexible option.

Project 1: an MPR121 touch piano

Twelve electrodes match one full octave: the 12 notes from C to B including sharps. Connect a piece of fruit, a foil strip or a key drawn on cardboard to each electrode, and wire the passive buzzer's positive lead to D8 and its negative lead to GND. The code plays the lowest touched key and only updates the sound when the key changes, so tone() isn't restarted constantly and the note sounds clean. Change the note frequencies to move the keys up an octave, or play real piano samples with a DFPlayer Mini. For a simpler buzzer version, have a look at the Arduino piano article.

C++ (Arduino IDE)
1// MPR121 dokunmatik piyano: 12 elektrot = bir oktav (Do4 - Si4), buzzer D8'de
2// MPR121 touch piano: 12 electrodes = one octave (C4 - B4), buzzer on D8
3#include <Wire.h>
4#include <Adafruit_MPR121.h>
5
6const uint8_t BUZZER = 8;
7// Do, Do#, Re, Re#, Mi, Fa, Fa#, Sol, Sol#, La, La#, Si (Hz)
8const uint16_t NOTES[12] = {262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494};
9
10Adafruit_MPR121 cap;
11int playing = -1;   // Çalan elektrot, -1 = sessiz / electrode playing, -1 = silent
12
13void setup() {
14  pinMode(BUZZER, OUTPUT);
15  if (!cap.begin(0x5A, &Wire, 12, 6, true)) { // Meyveler için otomatik yapılandırma / auto-config for fruit
16    while (1) { tone(BUZZER, 100, 200); delay(1000); } // Modül yok: kesik ses / no module: beeping
17  }
18}
19
20void loop() {
21  uint16_t touched = cap.touched();
22  int key = -1;
23  for (int i = 0; i < 12; i++) {
24    if (bitRead(touched, i)) { key = i; break; } // En pes tuş öncelikli / lowest key wins
25  }
26  if (key != playing) {           // Yalnızca değişince sesi güncelle / update only on change
27    if (key >= 0) tone(BUZZER, NOTES[key]);
28    else noTone(BUZZER);
29    playing = key;
30  }
31  delay(10);
32}

Project 2: a Makey Makey style keyboard (Arduino Leonardo)

The Makey Makey is a well-known education board that lets you play computer games with keys made of bananas or dough. You can build the same idea with an Arduino Leonardo and an MPR121: the Leonardo's ATmega32U4 chip presents itself to the computer as a USB keyboard, and the MPR121 turns a touched electrode into a key press. The original Makey Makey measures resistance, so the user has to hold a ground wire; the MPR121 works capacitively, so that isn't needed, simply touching the electrode is enough. In the code below the first four electrodes become the arrow keys, the fifth is space and the sixth is Enter; perfect for simple browser games and Scratch projects. On the Leonardo the I2C pins differ from the Uno: SDA is on D2 and SCL on D3. For details on the keyboard library, see the Arduino Leonardo keyboard article.

C++ (Arduino IDE)
1// Makey Makey benzeri: Arduino Leonardo + MPR121, dokunulan elektrot klavye tuşu olur
2// Makey Makey style: Arduino Leonardo + MPR121, each touched electrode becomes a keyboard key
3#include <Wire.h>
4#include <Adafruit_MPR121.h>
5#include <Keyboard.h>
6
7// Elektrot 0-5: yön tuşları, boşluk, Enter / electrodes 0-5: arrows, space, Enter
8const uint8_t KEYS[6] = {KEY_UP_ARROW, KEY_DOWN_ARROW, KEY_LEFT_ARROW, KEY_RIGHT_ARROW, ' ', KEY_RETURN};
9
10Adafruit_MPR121 cap;
11uint16_t lastTouched = 0;
12
13void setup() {
14  delay(2000);                    // Bilgisayar USB'yi tanısın / let the computer enumerate USB
15  if (!cap.begin(0x5A, &Wire, 12, 6, true)) while (1) delay(10);
16  Keyboard.begin();
17}
18
19void loop() {
20  uint16_t touched = cap.touched();
21  for (uint8_t i = 0; i < 6; i++) {
22    bool now = bitRead(touched, i);
23    bool before = bitRead(lastTouched, i);
24    if (now && !before) Keyboard.press(KEYS[i]);    // Dokununca bas / press on touch
25    if (!now && before) Keyboard.release(KEYS[i]);  // Bırakınca bırak / release on release
26  }
27  lastTouched = touched;
28  delay(10);
29}

MPR121 and built-in touch on the ESP32

Since the ESP32 runs at 3.3 V, it connects straight to the MPR121 board: SDA goes to GPIO 21 and SCL to GPIO 22. The code below reads the MPR121's 12 channels and the ESP32's T0 touch pin (GPIO 4) at the same time and prints them, so you can compare both methods with the same finger. On the classic ESP32, touchRead() usually reads around 60–80 untouched and drops below 20 when touched; since these numbers vary with the board and wire length, set ESP_TOUCH_LIMIT based on your own readings. With this setup the ESP32's Wi-Fi lets the touch keys handle smart home tasks, for example switching on a lamp with one key and sending a notification with another.

C++ (Arduino IDE)
1// ESP32: MPR121 (I2C, GPIO 21/22) ile dahili dokunmatik pin T0 (GPIO 4) yan yana
2// ESP32: MPR121 (I2C, GPIO 21/22) next to the built-in touch pin T0 (GPIO 4)
3#include <Wire.h>
4#include <Adafruit_MPR121.h>
5
6Adafruit_MPR121 cap;
7const uint16_t ESP_TOUCH_LIMIT = 30;   // ESP32'de dokununca değer düşer / on ESP32 the value drops when touched
8
9void setup() {
10  Serial.begin(115200);
11  Wire.begin(21, 22);                  // SDA, SCL
12  if (!cap.begin(0x5A, &Wire)) {
13    Serial.println("MPR121 bulunamadi / not found");
14    while (1) delay(10);
15  }
16}
17
18void loop() {
19  uint16_t touched = cap.touched();
20  uint16_t espRaw = touchRead(T0);     // ESP32 dahili dokunmatik / ESP32 built-in touch
21  Serial.print("MPR121: ");
22  for (int i = 11; i >= 0; i--) Serial.print(bitRead(touched, i)); // 11 ... 0
23  Serial.printf("   ESP32 T0: %u %s\n", espRaw, espRaw < ESP_TOUCH_LIMIT ? "(dokunuldu / touched)" : "");
24  delay(100);
25}

Common problems and fixes

SymptomLikely causeFix
"MPR121 not found" is printedSDA and SCL swapped, wrong address or no powerCheck the wiring, find the address with an I2C scanner, measure 3.3 V at VCC
Some keys look touched right after start-upAn electrode was touched at start-up and the baseline was recorded wrongReset the board without touching the electrodes
Keys trigger by themselvesThreshold too low, wires long and close togetherRaise the thresholds, shorten and separate the wires, add debounce
Touching the fruit isn't detectedLarge electrode, unsuitable charge settingsTurn on auto-configuration in begin(), lower the touch threshold
Touching one key triggers its neighbourWires or electrodes too close togetherLeave at least 5 mm between electrodes, route wires apart
The Leonardo types the wrong charactersDifferent keyboard layoutPick a matching layout such as Keyboard.begin(KeyboardLayout_en_US); arrows, space and Enter are the same on every layout
Board gets warm or stops working5 V was applied to a 3.3 V boardPower the board from 3.3 V, replace it if necessary
Always do your first test with short wires and small pieces of foil, learn how the values look in the Serial Plotter, and only then move on to fruit and long wires. Seeing the delta value from the calibration code once with your own eyes gets you there much faster than guessing thresholds.

With one small board, the MPR121 turns a desk, a poster or a fruit bowl into an interactive interface, which is why it's a favourite for school projects and science fairs. In the BlueGrays app you can find step-by-step circuit diagrams and code for projects such as using a buzzer, setting buzzer frequency, a simple piano with a buzzer and buttons, an Arduino programmer's keyboard and LED control with an ESP32 button, and make touch versions of them by swapping their buttons for MPR121 electrodes.

Frequently asked questions

What voltage does the MPR121 run on?

The MPR121 chip runs from 1.71 to 3.6 V, so most modules are powered from 3.3 V. Boards with a regulator and level shifter can connect directly to 5 V Arduinos, but on cheap blue boards 5 V damages the chip.

How many touch keys can you make with the MPR121?

One MPR121 reads 12 electrodes. By tying the ADD pin to GND, 3.3 V, SDA or SCL you get four different addresses (0x5A–0x5D), so four modules on the same I2C bus give you 48 touch keys.

How do you make a fruit piano with an MPR121?

Push a jumper wire into each piece of fruit and connect the wires to the MPR121's electrode pins. The Arduino plays a note on a buzzer depending on which electrode is touched. Since fruit makes large, irregular electrodes, turning on auto-configuration in begin() clearly improves detection.

How do you set MPR121 thresholds?

Use setThresholds(touch, release); the Adafruit library defaults to 12 and 6. To find the best value, watch the difference between baseline and current value in the Serial Plotter, put the touch threshold between the noise and the touch value, and the release threshold at half of that.

TTP223 or MPR121?

For a single touch button the TTP223 is cheaper and needs no code. For multi-key projects, irregular electrodes such as fruit or foil, and whenever you need adjustable thresholds, the MPR121 is far more flexible.

Do I need an MPR121 with an ESP32?

The ESP32's 10 built-in touch pins are enough for projects with a few keys. If you need more than ten keys, large or irregular electrodes, or more stable readings, connecting an MPR121 to the ESP32's I2C pins gives better results.

See all projects
Using a Buzzer
AR-13Beginner

Using a Buzzer

Ever wondered how a doorbell or an alarm makes its sound? The Arduino makes a small buzzer beep at short intervals: beep, pause, beep, pause.

4.7(93)
183
Frequency Setting with Buzzer
AR-14Intermediate

Frequency Setting with Buzzer

You control the sound of a buzzer with four buttons: one starts the sound, one silences it, and the other two make it higher or lower.

4.6(69)
125
LED Control with a Push Button (Push)
AR-9Beginner

LED Control with a Push Button (Push)

Just like a doorbell: the light stays on as long as you press, and goes off when you let go.

4.8(120)
288
ESP32 LED Control with Push Button (Push)
ES-2Beginner

ESP32 LED Control with Push Button (Push)

The LED lights up when the button is pressed and turns off when released. Shows how the ESP32's digital input pin and internal pull-up resistor are used. The INPUT_PULLUP mode eliminates the need for an external resistor.

4.6(36)
57
Simple Piano with Buzzer and Button
AR-26Advanced
Premium

Simple Piano with Buzzer and Button

Build your own little piano with eight buttons. Each button is one note, from low to high: do, re, mi, fa, sol, la, ti and high do.

4.9(68)
90
Arduino Developer Keyboard
AR-65Intermediate
Premium

Arduino Developer Keyboard

If you are tired of typing the same lines over and over while coding, this little keypad becomes your shortcut keyboard.

4.7(40)
52
Python Developer Keyboard
AR-66Intermediate
Premium

Python Developer Keyboard

If you are tired of typing the same patterns over and over while coding, this little keyboard is made for you.

4.6(35)
45
Turkish National Anthem with Buzzer
AR-15Intermediate

Turkish National Anthem with Buzzer

Press the button and a small buzzer starts playing the Turkish National Anthem, note by note.

4.8(117)
278