Capacitive touch sensing with MPR121
This sketch allows you to hook up an MPR121 capactive touch sensing device to Bela, for example the SparkFun Capacitive Touch Sensor Breakout - MPR121. The breakout board gives you 12 electrode connections.
To get this working with Bela you need to connect the breakout board to the I2C terminal on the Bela board. See the Pin guide for details of which pin is which.
The sensor data will then be available for you to use in the array sensorValue[NUM_TOUCH_PINS]
.
#include <cmath>
#include "I2C_MPR121.h"
#define NUM_TOUCH_PINS 12
#undef DEBUG_MPR121
int readInterval = 50;
int threshold = 40;
int sensorValue[NUM_TOUCH_PINS];
float gFrequencies[NUM_TOUCH_PINS] = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25, 587.33, 659.25, 698.25, 783.99};
float gNormFrequencies[NUM_TOUCH_PINS];
float gPhases[NUM_TOUCH_PINS] = {0};
int readCount = 0;
int readIntervalSamples = 0;
void readMPR121(void*);
{
if(!mpr121.
begin(1, 0x5A)) {
rt_printf("Error initialising MPR121\n");
return false;
}
for(int i = 0; i < NUM_TOUCH_PINS; i++) {
gNormFrequencies[i] = 2.0 * M_PI * gFrequencies[i] / context->
audioSampleRate;
}
return true;
}
{
for(
unsigned int n = 0; n < context->
audioFrames; n++) {
if(++readCount >= readIntervalSamples) {
readCount = 0;
}
float sample = 0.0;
for(int i = 0; i < NUM_TOUCH_PINS; i++) {
float amplitude = sensorValue[i] / 400.f;
if(amplitude > 0.5)
amplitude = 0.5;
sample += amplitude * sinf(gPhases[i]);
gPhases[i] += gNormFrequencies[i];
if(gPhases[i] > M_PI)
gPhases[i] -= 2.0f * (float)M_PI;
}
}
}
{ }
void readMPR121(void*)
{
for(int i = 0; i < NUM_TOUCH_PINS; i++) {
sensorValue[i] = -(mpr121.
filteredData(i) - mpr121.
baselineData(i));
sensorValue[i] -= threshold;
if(sensorValue[i] < 0)
sensorValue[i] = 0;
#ifdef DEBUG_MPR121
rt_printf("%d ", sensorValue[i]);
#endif
}
#ifdef DEBUG_MPR121
rt_printf("\n");
#endif
}