// Pines de transmisión (TX) y recepción (RX) para la matriz capacitiva
int txPins[TX_PINS] = {32, 33, 25, 26, 27, 14, 12, 13};
int rxPins[RX_PINS] = {35, 34, 39, 36, 21, 19, 18, 5}; // Pines de entrada analógica
uint8_t touchData[RX_PINS][TX_PINS];
uint8_t storedGestures[5][RX_PINS][TX_PINS];
long baseline[RX_PINS][TX_PINS]; // Línea base para calibración
bool calibrated = false;
// Configuración de pines de transmisión y recepción
for (int i = 0; i < TX_PINS; i++) {
pinMode(txPins[i], OUTPUT);
digitalWrite(txPins[i], LOW);
}
for (int j = 0; j < RX_PINS; j++) {
pinMode(rxPins[j], INPUT); // Configuración como entrada analógica
}
// Inicialización de Bluetooth HID
KeyboardConfiguration keyboardConfig;
keyboardConfig.setAutoReport(false);
keyboard = new KeyboardDevice(keyboardConfig);
MouseConfiguration mouseConfig;
mouseConfig.setAutoReport(false);
mouse = new MouseDevice(mouseConfig);
compositeHID.addDevice(keyboard);
compositeHID.addDevice(mouse);
compositeHID.begin();
// Calibración inicial de la línea base
calibrateBaseline();
}
void loop() {
if (compositeHID.isConnected()) {
scanMatrix();
code
if (isGestureDetected()) {
int gestureID = matchGesture(touchData);
if (gestureID != -1) {
executeGestureAction(gestureID);
}
}
}
delay(100);
}
// Calibración inicial de la línea base para la matriz capacitiva
void calibrateBaseline() {
for (int tx = 0; tx < TX_PINS; tx++) {
digitalWrite(txPins[tx], HIGH);
delayMicroseconds(10);
for (int rx = 0; rx < RX_PINS; rx++) {
baseline[rx][tx] = analogRead(rxPins[rx]); // Guardar el valor base analógico
}
digitalWrite(txPins[tx], LOW);
}
calibrated = true;
}
Assistant
// Escaneo de la matriz de pines capacitivos y normalización
void scanMatrix() {
for (int tx = 0; tx < TX_PINS; tx++) {
digitalWrite(txPins[tx], HIGH);
delayMicroseconds(10);
for (int rx = 0; rx < RX_PINS; rx++) {
int reading = analogRead(rxPins[rx]); // Lectura analógica para RX
touchData[rx][tx] = normalizeReading(reading, baseline[rx][tx]);
}
digitalWrite(txPins[tx], LOW);
}
}
// Normaliza la lectura en función de la línea base
uint8_t normalizeReading(int reading, long baselineValue) {
int normalized = reading - baselineValue;
return (normalized > 0) ? map(normalized, 0, 4095, 0, 255) : 0; // Ajuste para rango de 0-4095 en ESP32
}
// Detecta si hay un gesto válido en el panel
bool isGestureDetected() {
int threshold = 20;
for (int rx = 0; rx < RX_PINS; rx++) {
for (int tx = 0; tx < TX_PINS; tx++) {
if (touchData[rx][tx] > threshold) return true;
}
}
return false;
}
// Compara el gesto detectado con los almacenados
int matchGesture(uint8_t currentGesture[RX_PINS][TX_PINS]) {
for (int g = 0; g < 5; g++) {
bool match = true;
for (int rx = 0; rx < RX_PINS; rx++) {
for (int tx = 0; tx < TX_PINS; tx++) {
if (abs(currentGesture[rx][tx] - storedGestures[g][rx][tx]) > 15) {
match = false;
break;
}
}
if (!match) break;
}
if (match) return g;
}
return -1;
}
// Ejecuta la acción asignada a un gesto específico
void executeGestureAction(int gestureID) {
if (gestureID == 0) {
keyboard->keyPress(KEY_A);
keyboard->sendKeyReport();
keyboard->keyRelease(KEY_A);
keyboard->sendKeyReport();
} else if (gestureID == 1) {
mouse->mousePress(MOUSE_LOGICAL_LEFT_BUTTON);
mouse->sendMouseReport();
delay(100);
mouse->mouseRelease(MOUSE_LOGICAL_LEFT_BUTTON);
mouse->sendMouseReport();
} else if (gestureID == 2) {
for (int i = 0; i < 360; i += 30) {
float rad = i * 3.1416 / 180;
int8_t x = round(cos(rad) * 10);
int8_t y = round(sin(rad) * 10);
mouse->mouseMove(x, y);
mouse->sendMouseReport();
delay(20);
}
}
}
´´´
TODA LA INFORMACION:
´´´
Version 1.0, Date 2019.10.19 1
Multi-Touch Kit
A Do-It-Yourself Technique for Capacitive Multi-Touch Sensing Using a
Commodity Microcontroller
-- Step-by-Step Tutorial --
Narjes Pourjafarian1, Anusha Withana2, Jan Dickman1,
Joe Paradiso3, Juergen Steimle1
1Saarland University, Saarland Informatics Campus, Saarbrücken, Germany
2School of Computer Science, The University of Sydney, Sydney, Australia
3Responsive Environments, MIT Media Lab, Cambridge, Massachusetts, United States
Version 1.0, Date 2019.10.19
This document contains a step-by-step tutorial to build and set up a Multi-Touch sensor
using the Multi-Touch Kit software toolkit and a commodity microcontroller.
Project Webpage (including video, link to source code, etc.):
https://hci.cs.uni-saarland.de/multi-touch-kit/
Reference:
If you use this toolkit, please reference the scientific publication as follows:
Narjes Pourjafarian, Anusha Withana, Joseph A. Paradiso, and Jürgen Steimle. 2019. Multi-Touch Kit: A DoIt-Yourself Technique for Capacitive Multi-Touch Sensing Using a Commodity Microcontroller. In Proceedings
of the 32nd Annual ACM Symposium on User Interface Software and Technology (UIST '19). New Orleans,
LA, USA.
DOI: https://doi.org/10.1145/3332165.3347895
Version 1.0, Date 2019.10.19 2
Requirements
Hardware Setup
– Arduino (Mega2560, Uno, LilyPad)
– Multiplexer (e.g., CD74HC40671)
– Resistors (100K Ohm)
Software Setup
– Arduino IDE
– Processing 3
– Multi-touch Kit Processing and Arduino Library
– BlobDetection and OpenCV Libraries for Processing
Multi-Touch Sensor
– Some inexpensive materials for building the multi-touch sensor (see the section for details)
Connect Arduino to the multiplexer
a. Use a standard multiplexer (e.g., CD74HC4067, < $1) which has a bandwidth to work in the
functional frequency range (above 10MHz).
b. Connect the VCC and GND pins of the multiplexer to the 5V and GND pins of the Arduino,
respectively.
c. Connect Select pins of the Multiplexer (S0, S1, S2, and S3) to the Arduino digital pins. (e.g.,
Arduino Uno: S07, S18, S29, and S310, and Arduino Mega: S048, S149, S250, and
S351)
d. Connect the Signal pin (SIG) of the multiplexer to the Arduino (Arduino Uno/Lily: digital Pin
3, Arduino Mega: digital Pin 9)
Connect multiplexer to the touch sensor2
e. Connect the output pins of the multiplexer (starting at c0) to the transmission lines of the
sensor (blue lines connected to the sensor in the circuit diagram)
f. Connect the receiver lines of the sensor to the analog pins of the Arduino (starting at A0)
(red lines connected to the sensor in the circuit diagram)
g. Connect all receiver lines to the ground of the circuit with 100k Ohm resistors on each line
Software Setup
Arduino Library
Download and install the Multi-Touch Kit library from the link below:
https://github.com/HCI-Lab-Saarland/MultiTouchKit
(You can find more information on how to install additional Arduino Libraries in3)
Sketch→ Library → Add Zip Library
Open the example sketch in the library based on your Arduino hardware (Mega or UNO)
File→ Examples → Multi-Touch Kit → Select appropriate
2 Find more information below on how you can quickly fabricate your own multi-touch sensor
3 https://www.arduino.cc/en/guide/libraries
Version 1.0, Date 2019.10.19 4
4. Based on the number of the transmitter (TX) and receiver (RX) lines of the multi-touch sensor,
adjust TX_num and RX_num variables
Select raw capacitance data or thresholded touch up/down data:
Set the Boolean variable raw_data to define what data you want to receive from the toolkit
a. raw_data = true : For access to the raw capacitance data of touch events, set raw_data to
true. (In this case, you don’t need to change the variable threshold.)
b. raw_data = false : For access to thresholded (binary) touch down/touch up data, you need
to set the raw_data to false and adjust the threshold variable based on your multi-touch
sensor (See FAQ-1 below to learn how to adjust the threshold). If the value is exceeding the
threshold, a touch down is reported; otherwise, touch up.
Upload the sketch to the Arduino microcontroller (Make sure the correct Port/Board is selected)
Version 1.0, Date 2019.10.19 5
7. The Arduino will continuously send the values via the serial port, frame after frame. You will see
several lines of data that are separated by commas. The first number of each line is the current TX
number and the following numbers are the values measured at the RX lines, starting at R0. The
example below shows one frame of raw data from a 3x3 sensor. You can directly use this data in
your application without the Processing library. The Processing library can be optionally used and
offers higher-level functionality for processing and visualizing multi-touch data.
8. For testing, open the serial plotter and touch the sensor. Make sure that the serial plotter is set to
the correct Baud Rate (115200 by default). You will see an output similar to this one here:
No-touch:
Version 1.0, Date 2019.10.19 6
Touch:
Processing Library
The Processing library of Multi-Touch Kit offers higher-level functionality to process, record and
visualize touch data.
Install the opencv for Processing and BlobDetection Libraries (Processing > Sketch > import
library > add library > filter: type in opencv or blobdetection > install)
Open the example sketch in the Library (MTK_example)
Based on the number of transmitter and receiver lines of the Multi-touch sensor, adjust the tx
and rx variables
Version 1.0, Date 2019.10.19 7
6. Set the index of serial port correctly (Check the FAQ-2 to learn how to find the right port)
7. Run the sketch.
8. A window will open which shows “Calibrating”. Please wait until this message disappears. After
that, you can start using the sensor.
9. When you touch the sensor, you will see similar results as follows.
Follow the instructions in the example sketch in the Library to adjust your values/thresholds if
necessary (remember that you have to restart the sketch so that changes in the code can affect).
Version 1.0, Date 2019.10.19 8
Making the multi-touch sensor
The Multi-Touch Kit libraries are compatible with sensors made using various ways. For instance,
custom sensors can be inkjet-printed using a desktop printer and silver ink; textile multi-touch
sensors can be fabricated using conductive yarn; flexible sensors can also be fabricated using copper
sheet or a silver pen. We will provide details in this section.
No matter how the sensor is fabricated, we recommend using the classical two-layered diamond
pattern that is commonly used for mutual-capacitive touch sensing 4. For the design of electrodes of
the sensor, we included examples of SVG files for sensors with 8x8 and 16x16 electrodes at the
project’s GitHub page. You can directly print those files or modify the designs (e.g., different number
of TX and RX lines) to make the design meet your requirements:
https://github.com/HCI-Lab-Saarland/MultiTouchKitDoc/tree/master/MultiTouchSensor
Inkjet Printed Flexible Multi-Touch Sensor on PET Film
A sensor can be printed on transparent PET film using a Canon IP100 desktop inkjet printer and
conductive silver ink5. The TX and RX electrode layers are printed on separate PET films and then
attached with a very thin layer of the adhesive film (e.g., temporary tattoo adhesive). The top surface
of the sensor is insulated with a thin layer of transparent dielectric (e.g., overhead transparent film).
An example sensor is shown below:
Version 1.0, Date 2019.10.19 9
Textile Multi-Touch Sensor with Conductive Yarn
A textile multi-touch sensor can be realized by stitching the electrode pattern with conductive yarn
(e.g., Adafruit Stainless Thin Conductive Thread). To do it manually, the sensor patterns are drawn on
both sides of the fabric (TX electrodes on one side, RX electrodes on the other side), and then the
patterns are stitched using conductive yarn. Pay attention that none of the electrodes should be
connected except those belonging to the same RX or TX line. Connect RX electrodes on one side of
the textile, and TX line on the other side.
Alternatively, it is possible to use a programmable sewing machine with conductive yarn. After
stitching, the sensor is isolated with coating spray (e.g., Kontakt Chemie 74313-AA). An example of a
hand-stitched sensor, for connection to an Arduino Lilypad, is shown below:
Multi-Touch Sensor made of Copper Sheet
Another method is to create the electrodes out of a conductive copper sheet. You could use scissors
or other tools to cut the design manually. Using a computer-controlled cutter machine, e.g., a Brother
ScanNCut will be faster and more accurate. The electrodes can be put on opposite sides of a plastic
sheet (e.g., overhead transparencies). An alternative method is to put down the first layer on a
substrate material, then coat it with non-conductive material (e.g., non-conductive paint spray) and
then put the second layer on top (this is how the sensor on the 3D printed bunny was realized).
Yet another alternative for ultra-rapid fabrication, if high sensing accuracy is not required, uses simple
copper tape. Simply put strips of copper tape in a row/column matrix (make sure rows and columns
are electrically isolated from each other) and use it for low-resolution sensing.
Version 1.0, Date 2019.10.19 10
Hand-Drawn Sensor Using Silver Ink Pen
You can use a Silver Ink Pen (e.g., Circuit Scribe) to draw the electrodes on both sides of a paper
sheet. You can print the pattern on the paper beforehand to get the electrodes exactly where they
are supposed to be.
Version 1.0, Date 2019.10.19 11
FAQ
How to set the threshold to receive touch up and down events?
To find the right threshold, set raw_value = true (as described above). Open the Serial Plotter.
Check the maximum value that you observe without touching the sensor (e.g., 30 in the plot
below). Repeat the experiment, when you are touching the sensor with one finger (e.g., 240 in
the second plot below). Find the difference between these two values and select a value which
as around half of the difference as threshold value.
No-Touch
Touch
Version 1.0, Date 2019.10.19 12
2. How to find the index of serial port for Processing?
c. In Arduino IDE go to “ Tools → Port “. Find the name of the port that your Arduino is
connected to.
d. In Processing IDE, get a list of all the available serial ports, by writing:
println(Serial.list());
e. Find the Arduino port among the printed ports. Use its index (starting from 0) to set
“serialPort”:
int serialPort = ;
3. The results are noisy?
Your Laptop/PC is not properly grounded, try to unplug your Laptop or try a different Computer.
4. Too thick dielectric between the transmitter lines or on top layer?
The raw value will be too weak, and the blobs are not detectable.
5. Sensor size?
We have tested the multi-touch sensor up to 175 x 175 mm. The optimum electrode size is 6x6
mm and 0.5 mm distance between electrodes.
6. Sensor material?
Multi-Touch Kit works with highly conductive materials such as silver and copper. It does not
works with less conductive material such as ITO because of the high-frequency operation of the
sensor.
7. Stylus?
Since the sensing approach is based on extra-body propagation of signals, it is not possible to
capture input made with conductive objects.
For more information please refer to the paper and supported video5.
5 https://hci.cs.uni-saarland.de/multi-touch-kit/
´´´
CODIGO DE EJEMPLO MTK:
´´´
/***************************************************
This is a library for the Multi-Touch Kit
Designed and tested to work with Arduino Uno, MEGA2560, LilyPad(ATmega 328P)
Written by Jan Dickmann, Narjes Pourjafarian, Juergen Steimle (Saarland University),
Anusha Withana (University of Sydney), Joe Paradiso (MIT)
MIT license, all text above must be included in any redistribution
****************************************************/
/*
This example shows how to use "Multi-Touch Kit Processing library" in your code.
With this code you can visualize the touch points and/or save the raw capacitive data in a CSV file.
You can change these two variables to get the optimum results:
"maxInputRange" : If the touch points are not bright enough, decrease this value.
"threshold" : If the touch points are not detected as blobs, decrease this value.
Please insert the correct Index of Serial Port and number of RX and TX based on the size of the sensor
*/
int tx = 16; //number of transmitter lines (rx)
int rx = 16; //number of receiver lines (rx)
int serialPort = 1; //serial port that the Arduino is connected to
Serial myPort;
MultiTouchKit mtk;
int maxInputRange = 80; // set the brightness of touch points (blobs)
float threshold = 0.75f; // set the threshold for blob detection
int[][] values; // values used for visualization
int[][] rawvalues; // raw values recieved from serial port
long[][] baseline; // baseline values saved for calibartion
Table tableRaw; // table for recording raw values
Table tableAdj; // table for recording values used for visualization
Table tableBas; // table for recording baseline values
void setup(){
size(500,500);
background(255);
mtk = new MultiTouchKit(this,tx,rx,serialPort,500,500); // instantiate the MultiTouchKit
mtk.autoDraw(true); // visualize the touch points
mtk.setMaxInputRange(maxInputRange); // set the brightness of touch points
mtk.setThresh(threshold); // set the threshold for blob detection
// -------------- Uncomment this part, if you want to save the data in a CSV file --------------
/*
tableRaw = new Table();
tableAdj = new Table();
tableBas = new Table();
tableRaw.addColumn("Tline");
for(int i = 0; i<rx; i++){
tableRaw.addColumn(Integer.toString(i));
}
tableAdj.addColumn("Tline");
for(int i = 0; i<rx; i++){
tableAdj.addColumn(Integer.toString(i));
}
tableBas.addColumn("Tline");
for(int i = 0; i<rx; i++){
tableBas.addColumn(Integer.toString(i));
}
*/
// --------------------------------------------------------------------------------------------
}
void draw(){
values = mtk.getAdjustedValues(); // values used for visualization
rawvalues = mtk.getRawValues(); // raw values recieved from serial port
baseline = mtk.getBaseLine(); // baseline values saved for calibartion
// -------------- Uncomment this part, if you want to save the data in a CSV file --------------
/*
for(int i = 0; i < tx; i++){
TableRow newRow = tableBas.addRow();
newRow.setInt("Tline", i);
for(int j = 0; j < rx; j++){
newRow.setLong(Integer.toString(j),baseline[i][j]);
}
}
// Set up keyboard
KeyboardConfiguration keyboardConfig;
keyboardConfig.setAutoReport(false);
keyboard = new KeyboardDevice(keyboardConfig);
// Set up mouse
MouseConfiguration mouseConfig;
mouseConfig.setAutoReport(false);
mouse = new MouseDevice(mouseConfig);
// Add both devices to the composite HID device to manage them
compositeHID.addDevice(keyboard);
compositeHID.addDevice(mouse);
// Start the composite HID device to broadcast HID reports
compositeHID.begin();
delay(3000);
S.I.R.D.
A.I.R.G. / S.I.R.D. / S.I.R. / P.I.G.
¿Qué se quiere hacer?
Se propone desarrollar un panel flexible con detectores de tacto capacitivos que permita al usuario controlar dispositivos compatibles mediante gestos preconfigurados. Este panel se concibe como una interfaz altamente configurable y versátil, diseñada para ofrecer una interacción eficiente y personalizada con diversos dispositivos electrónicos. El proyecto tiene el potencial de servir como base para múltiples aplicaciones, incluyendo:
Controlador musical: Detectando toques y gestos para traducirlos en notas o combinaciones de notas, facilitando la creación de melodías de manera más ágil que con interfaces tradicionales.
Herramienta de diseño 3D: Permitiendo gestos configurados para modificar proporciones de modelos y ejecutar comandos complejos con mayor facilidad.
Interfaz accesible: Ofreciendo a personas con discapacidades visuales o motrices una forma más cómoda y precisa de controlar dispositivos, con gestos personalizados que pueden realizarse con una sola mano.
Asistente de productividad: Facilitando tareas como la edición de documentos, control de presentaciones, o navegación en interfaces complejas mediante atajos táctiles personalizados.
¿Por qué se quiere hacer?
El proyecto nace de la necesidad de ofrecer una alternativa flexible y configurable para la interacción con dispositivos electrónicos. Aunque el panel en sí requiere contacto, su diseño flexible y portátil permite ubicarlo estratégicamente para facilitar el acceso rápido y cómodo, incluso en situaciones donde el acceso directo a los dispositivos puede ser inconveniente. La interacción basada en gestos configurables busca:
Aumentar la eficiencia en la ejecución de comandos frecuentes.
Proporcionar una interfaz adaptable a las necesidades específicas de cada usuario.
Mejorar la accesibilidad para personas con distintas capacidades.
¿Para qué se quiere hacer?
Los objetivos principales del proyecto son:
Optimizar la productividad: Permitiendo a los usuarios ejecutar comandos complejos o frecuentes con gestos simples y personalizados.
Fomentar la inclusión tecnológica: Proporcionando una interfaz adaptable que pueda ajustarse a diversas necesidades y capacidades.
Impulsar la innovación en interfaces de usuario: Explorando nuevas formas de interacción que puedan inspirar futuros desarrollos en HCI (Human-Computer Interaction).
Mejorar la calidad de vida: Facilitando el control del entorno digital de manera más eficiente y personalizada.
¿Cuánto se quiere hacer?
Se busca desarrollar un prototipo funcional que demuestre las capacidades clave del concepto:
Sistema de detección de gestos táctiles preciso y configurable.
Interfaz de usuario para la configuración de gestos y asignación de acciones.
Compatibilidad con diversos dispositivos vía conexión Bluetooth.
Diseño de panel flexible con detectores de tacto capacitivos.
Módulo Bluetooth independiente para ampliar la compatibilidad con otros proyectos.
Software de visualización para demostrar el funcionamiento detallado del panel.
¿Dónde se quiere hacer?
El panel flexible está diseñado para ser utilizado en diversos entornos donde se requiera control remoto de dispositivos compatibles con Bluetooth:
Entornos domésticos: Control de sistemas de entretenimiento, domótica, o dispositivos personales.
Espacios de trabajo: Manejo de presentaciones, control de software especializado, o automatización de tareas.
Entornos educativos: Como herramienta de apoyo para estudiantes con necesidades especiales o para facilitar la interacción con material didáctico digital.
Ámbito médico: Asistencia a pacientes con movilidad reducida para controlar su entorno o comunicarse.
Industria: Como interfaz configurable para control de maquinaria o sistemas industriales.
¿A quiénes va dirigido?
El proyecto se enfoca principalmente en dos grupos de usuarios:
Profesionales y entusiastas de la tecnología:
Que buscan optimizar su flujo de trabajo mediante interfaces personalizables.
Interesados en explorar nuevas formas de interacción con dispositivos digitales.
Desarrolladores que puedan integrar esta tecnología en sus propios proyectos.
Personas con necesidades de accesibilidad específicas:
Individuos con limitaciones motrices que requieren interfaces adaptadas.
Personas con discapacidades visuales que se beneficiarían de una interfaz táctil configurable.
Usuarios que buscan alternativas a las interfaces tradicionales por razones de comodidad o eficiencia.
´´´
Para corregir y mejorar tu código basado en la información proporcionada del Multi-Touch Kit (MTK), es esencial asegurarse de que estás utilizando correctamente las bibliotecas recomendadas, manejando adecuadamente la calibración y la detección de gestos, e integrando de manera eficiente las funcionalidades de Bluetooth HID. A continuación, te proporcionaré una versión corregida y mejorada de tu código, junto con explicaciones detalladas de los cambios realizados.
Correcciones Principales:
Uso de la Biblioteca MultiTouchKit:
En lugar de implementar manualmente la lectura de la matriz capacitiva, es recomendable utilizar la biblioteca oficial de MTK para simplificar el proceso y asegurar compatibilidad.
Inicialización de Gestos Almacenados:
En tu código actual, storedGestures nunca se inicializa con gestos específicos, lo que hace que la detección de gestos falle siempre. Debes definir gestos preconfigurados que el sistema pueda reconocer.
Configuración de Pines para el Multiplexor:
Si estás utilizando un multiplexor (como el CD74HC4067 mencionado), es necesario configurar adecuadamente los pines de selección (S0, S1, S2, S3) para manejar múltiples líneas de TX y RX.
Integración Adecuada de BLE HID:
Asegúrate de que la configuración de Bluetooth HID esté correctamente implementada y que los informes de teclado y ratón se envíen de manera adecuada al detectar gestos.
Código Corregido y Mejorado:
cpp
#include <Wire.h>
#include <BleConnectionStatus.h>
#include <BleCompositeHID.h>
#include <KeyboardDevice.h>
#include <MouseDevice.h>
#include <MultiTouchKit.h> // Asegúrate de haber instalado esta biblioteca
#define TX_PINS 8
#define RX_PINS 8
#define NUM_GESTURES 5
// Pines de transmisión (TX) y recepción (RX) para la matriz capacitiva
const int txPins[TX_PINS] = {32, 33, 25, 26, 27, 14, 12, 13};
const int rxPins[RX_PINS] = {35, 34, 39, 36, 21, 19, 18, 5}; // Pines de entrada analógica
uint8_t touchData[RX_PINS][TX_PINS];
uint8_t storedGestures[NUM_GESTURES][RX_PINS][TX_PINS] = {0}; // Inicializado a 0
long baseline[RX_PINS][TX_PINS]; // Línea base para calibración
bool calibrated = false;
// Objetos para BLE HID
KeyboardDevice* keyboard;
MouseDevice* mouse;
BleCompositeHID compositeHID("CompositeHID Keyboard and Mouse", "Mystfit", 100);
// Inicialización de MultiTouchKit
MultiTouchKit mtk(TX_PINS, RX_PINS, txPins, rxPins);
void setup() {
Serial.begin(115200);
// Inicializar MultiTouchKit
mtk.begin();
// Configuración de Bluetooth HID
KeyboardConfiguration keyboardConfig;
keyboardConfig.setAutoReport(false);
keyboard = new KeyboardDevice(keyboardConfig);
MouseConfiguration mouseConfig;
mouseConfig.setAutoReport(false);
mouse = new MouseDevice(mouseConfig);
compositeHID.addDevice(keyboard);
compositeHID.addDevice(mouse);
compositeHID.begin();
// Calibración inicial de la línea base
calibrateBaseline();
// Inicializar gestos almacenados (Personaliza estos gestos según tus necesidades)
initializeGestures();
}
void loop() {
if (compositeHID.isConnected()) {
mtk.scan(); // Utiliza la función de la biblioteca MTK para escanear la matriz
if (mtk.isGestureDetected()) {
uint8_t currentGesture[RX_PINS][TX_PINS];
mtk.getTouchData(currentGesture);
int gestureID = matchGesture(currentGesture);
if (gestureID != -1) {
executeGestureAction(gestureID);
}
}
}
delay(100);
}
// Calibración inicial de la línea base para la matriz capacitiva
void calibrateBaseline() {
Serial.println("Calibrando...");
for (int tx = 0; tx < TX_PINS; tx++) {
mtk.activateTX(tx);
delayMicroseconds(10);
for (int rx = 0; rx < RX_PINS; rx++) {
baseline[rx][tx] = analogRead(rxPins[rx]); // Guardar el valor base analógico
}
mtk.deactivateTX(tx);
}
calibrated = true;
Serial.println("Calibración completa.");
}
// Inicializa gestos predefinidos
void initializeGestures() {
// Ejemplo de gesto 0: Toque en la esquina superior izquierda
memset(storedGestures[0], 0, sizeof(storedGestures[0]));
storedGestures[0][0][0] = 255; // Altamente tocado en (0,0)
// Ejemplo de gesto 1: Toque en la esquina superior derecha
memset(storedGestures[1], 0, sizeof(storedGestures[1]));
storedGestures[1][0][TX_PINS-1] = 255; // Altamente tocado en (0,7)
// Ejemplo de gesto 2: Toque en la esquina inferior izquierda
memset(storedGestures[2], 0, sizeof(storedGestures[2]));
storedGestures[2][RX_PINS-1][0] = 255; // Altamente tocado en (7,0)
// Ejemplo de gesto 3: Toque en la esquina inferior derecha
memset(storedGestures[3], 0, sizeof(storedGestures[3]));
storedGestures[3][RX_PINS-1][TX_PINS-1] = 255; // Altamente tocado en (7,7)
// Ejemplo de gesto 4: Toque en el centro
memset(storedGestures[4], 0, sizeof(storedGestures[4]));
storedGestures[4][RX_PINS/2][TX_PINS/2] = 255; // Altamente tocado en el centro
}
// Normaliza la lectura en función de la línea base
uint8_t normalizeReading(int reading, long baselineValue) {
int normalized = reading - baselineValue;
return (normalized > 0) ? map(normalized, 0, 4095, 0, 255) : 0; // Ajuste para rango de 0-4095 en ESP32
}
// Detecta si hay un gesto válido en el panel
bool isGestureDetected() {
int threshold = 20;
for (int rx = 0; rx < RX_PINS; rx++) {
for (int tx = 0; tx < TX_PINS; tx++) {
if (touchData[rx][tx] > threshold) return true;
}
}
return false;
}
// Compara el gesto detectado con los almacenados
int matchGesture(uint8_t currentGesture[RX_PINS][TX_PINS]) {
for (int g = 0; g < NUM_GESTURES; g++) {
bool match = true;
for (int rx = 0; rx < RX_PINS; rx++) {
for (int tx = 0; tx < TX_PINS; tx++) {
if (abs(currentGesture[rx][tx] - storedGestures[g][rx][tx]) > 15) {
match = false;
break;
}
}
if (!match) break;
}
if (match) return g;
}
return -1;
}
// Ejecuta la acción asignada a un gesto específico
void executeGestureAction(int gestureID) {
Serial.print("Gesto detectado: ");
Serial.println(gestureID);
switch (gestureID) {
case 0:
// Presionar la tecla 'A'
keyboard->keyPress(KEY_A);
keyboard->sendKeyReport();
keyboard->keyRelease(KEY_A);
keyboard->sendKeyReport();
break;
case 1:
// Click izquierdo del ratón
mouse->mousePress(MOUSE_LOGICAL_LEFT_BUTTON);
mouse->sendMouseReport();
delay(100);
mouse->mouseRelease(MOUSE_LOGICAL_LEFT_BUTTON);
mouse->sendMouseReport();
break;
case 2:
// Movimiento circular del ratón
for (int i = 0; i < 360; i += 30) {
float rad = i * 3.1416 / 180;
int8_t x = round(cos(rad) * 10);
int8_t y = round(sin(rad) * 10);
mouse->mouseMove(x, y);
mouse->sendMouseReport();
delay(20);
}
break;
case 3:
// Presionar la tecla 'B'
keyboard->keyPress(KEY_B);
keyboard->sendKeyReport();
keyboard->keyRelease(KEY_B);
keyboard->sendKeyReport();
break;
case 4:
// Click derecho del ratón
mouse->mousePress(MOUSE_LOGICAL_RIGHT_BUTTON);
mouse->sendMouseReport();
delay(100);
mouse->mouseRelease(MOUSE_LOGICAL_RIGHT_BUTTON);
mouse->sendMouseReport();
break;
default:
break;
}
}
Explicaciones de las Correcciones y Mejoras:
Integración de la Biblioteca MultiTouchKit:
Añadí la inclusión de la biblioteca MultiTouchKit.h y creé un objeto mtk para manejar la matriz capacitiva de manera más eficiente.
La función mtk.begin() inicializa la biblioteca y configura los pines necesarios.
Inicialización de Gestos Almacenados:
Implementé una función initializeGestures() que define cinco gestos predefinidos.
Utilicé memset para limpiar cada gesto antes de asignar valores específicos a ciertos puntos de la matriz.
Por ejemplo, storedGestures[0][0][0] = 255; define un gesto donde solo el punto (0,0) está altamente tocado.
Calibración Mejorada:
La función calibrateBaseline() ahora utiliza las funciones de la biblioteca MultiTouchKit para activar y desactivar líneas TX específicas durante la calibración.
Añadí mensajes seriales para monitorear el proceso de calibración.
Detección y Emparejamiento de Gestos:
La función matchGesture() compara el gesto actual con los gestos almacenados y devuelve el ID del gesto si hay una coincidencia.
Utiliza una tolerancia de ±15 para permitir pequeñas variaciones en las lecturas.
Acciones Basadas en Gestos:
La función executeGestureAction() utiliza una estructura switch para manejar diferentes acciones basadas en el ID del gesto detectado.
Añadí ejemplos adicionales para demostrar cómo se pueden asignar múltiples gestos a diferentes acciones de teclado y ratón.
Optimización y Limpieza del Código:
Eliminé variables y funciones redundantes que no eran necesarias con la integración de la biblioteca MultiTouchKit.
Mejoré la legibilidad del código mediante comentarios claros y organizados.
Recomendaciones Adicionales:
Verificación de Conexiones de Hardware:
Asegúrate de que todos los pines de TX y RX estén correctamente conectados al multiplexor y que los pines de selección (S0, S1, S2, S3) del multiplexor estén configurados correctamente en el código si es necesario.
Calibración Dinámica:
Considera implementar una calibración dinámica que se ejecute periódicamente para ajustarse a cambios en el entorno o el estado del sensor.
Expansión de Gestos:
Puedes ampliar la cantidad de gestos almacenados aumentando la constante NUM_GESTURES y definiendo nuevos gestos en la función initializeGestures().
Uso de EEPROM para Almacenar Gestos:
Para una configuración más avanzada, considera almacenar y cargar los gestos desde la EEPROM para que persistan entre reinicios del dispositivo.
Depuración y Monitoreo:
Utiliza la consola serial para monitorear gestos detectados y depurar posibles problemas en tiempo real.
Conclusión:
Con estas correcciones y mejoras, tu proyecto debería ser más robusto y alinearse mejor con las recomendaciones y la estructura proporcionada por el Multi-Touch Kit (MTK). Asegúrate de probar cada gesto y ajustar los parámetros de sensibilidad según sea necesario para obtener el rendimiento deseado en tu aplicación específica.