Touch piano on an Arduino Uno
Twelve foil keys on an MPR121 touch controller play an octave from middle C on a piezo; the lowest key held wins. The whole build, an Arduino Uno and 2 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $33. On Mokxi they're free.
Step by step, with the wiring and the common mistakes: Arduino MPR121: 12-Key Capacitive Touch Piano
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Touch piano: twelve foil keys on an MPR121 and a piezo.
//
// SDA, SCL the MPR121 (address 0x5A), VIN and GND from the rails
// pin 8 the piezo; its other leg to ground
//
// Each electrode is a key, an octave of semitones from middle C. The
// MPR121 does the touch sensing itself and hands back twelve bits; the
// sketch plays the lowest key held, and stops when no key is.
//
// The note frequencies are the equal-tempered ones rounded to the hertz,
// from 262 for C4 to 494 for B4.
#include <Wire.h>
#include "Adafruit_MPR121.h"
const int PIEZO = 8;
const unsigned int NOTES[12] = {262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494};
const char *NAMES[12] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};
Adafruit_MPR121 cap = Adafruit_MPR121();
int playing = -1;
void setup() {
Serial.begin(115200);
Serial.println("Mokxi Arduino Uno: touch piano");
if (!cap.begin(0x5A)) {
Serial.println("no MPR121: check SDA, SCL and power");
while (1) delay(10);
}
Serial.println("ready: touch a key");
}
void loop() {
uint16_t touched = cap.touched();
int key = -1;
for (int i = 0; i < 12; i++) {
if (touched & (1 << i)) {
key = i;
break;
}
}
if (key != playing) {
playing = key;
if (key < 0) {
noTone(PIEZO);
Serial.println("quiet");
} else {
tone(PIEZO, NOTES[key]);
Serial.print("key ");
Serial.print(key);
Serial.print(": ");
Serial.print(NAMES[key]);
Serial.print("4, ");
Serial.print(NOTES[key]);
Serial.println(" Hz");
}
}
delay(10);
}
Parts list
4 parts, plus the jumper wires. They retail for about $33; on Mokxi they're free.
How it is wired
5 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Arduino Uno R3 pin SCL; Capacitive touch, MPR121 pin SCL
- Arduino Uno R3 pin SDA; Capacitive touch, MPR121 pin SDA
- Arduino Uno R3 pin 8; Piezo speaker pin 1
- Arduino Uno R3 pin 5V; Capacitive touch, MPR121 pin VIN
- Ground: Arduino Uno R3 pin GND; Capacitive touch, MPR121 pin GND; Piezo speaker pin 2
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.