Hi Everyone,
I am new to programming and Arduino. I am using Adafruit MPR121 Capacitive Touch Sensor. What I want to do is to count the number of touches for each touchpad.
For example, when I touch the touchpad 0 once, then it says touched once. I touch it twice, and it says touched twice and so forth. When I touch the touchpad 6, it says touched once. However, the code I have for now is counting the number of touches for all, not counting for the individual touchpad.
Instead of writing for each pad separately, how to write a loop to make it easier?
Here is my code:
#include <Wire.h>
#include "Adafruit_MPR121.h"
#ifndef _BV
#define _BV(bit) (1 << (bit))
#endif
uint16_t lasttouched = 0;
uint16_t currtouched = 0;
Adafruit_MPR121 cap = Adafruit_MPR121();
uint8_t touchThreshold = 100;
uint8_t releaseThreshold = 40;
int TouchCounter = 0; // counter for the number of touches
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
Serial.begin(9600);
while (!Serial) { // needed to keep leonardo/micro from starting too fast!
delay(10);
}
Serial.println("Adafruit MPR121 Capacitive Touch sensor test");
// Default address is 0x5A, if tied to 3.3V its 0x5B
// If tied to SDA its 0x5C and if SCL then 0x5D
if (!cap.begin(0x5A)) {
Serial.println("MPR121 not found, check wiring?");
while (1);
}
Serial.println("MPR121 found!");
}
void loop() {
currtouched = cap.touched();
for (uint8_t i=0; i<12; i++) {
if ((currtouched & _BV(i)) && !(lasttouched & _BV(i))) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
if (!(currtouched & _BV(i)) && (lasttouched & _BV(i))) {
TouchCounter++;
if (TouchCounter == 1) {
Serial.print(i); Serial.println(" Touched Once");
delay(50);}
if (TouchCounter ==2) {
Serial.print(i); Serial.println(" Touched Twice");
delay(50);}
if (TouchCounter >2) {
Serial.print(i); Serial.println(" Playing");
delay(50);}
}
}
}
// reset our state
lasttouched = currtouched;
return;
// debugging info, what
Serial.print("\t\t\t\t\t\t\t\t\t\t\t\t\t 0x"); Serial.println(cap.touched(), HEX);
Serial.print("Filt: ");
for (uint8_t i=0; i<12; i++) {
Serial.print(cap.filteredData(i)); Serial.print("\t");
}
Serial.println();
Serial.print("Base: ");
for (uint8_t i=0; i<12; i++) {
Serial.print(cap.baselineData(i)); Serial.print("\t");
}
Serial.println();
// put a delay so it isn't overwhelming
delay(100);
}
I have attached the image of the current result. It is not counting individual touchpad separately.
Thank you very much.