#include <Preferences.h>
// Constants
constexpr byte MAX_GESTOS = 20; // Máximo número de gestos almacenables
constexpr byte MAX_SECUENCIA = 10; // Máximo tamaño de secuencia para cada gesto
constexpr byte MAX_ACCIONES = 5; // Máximo número de acciones por gesto
constexpr byte BUFFER_SIZE = 50; // Tamaño del buffer para secuencias táctiles
constexpr unsigned long INACTIVITY_TIMEOUT = 500; // Tiempo de inactividad para limpiar el buffer (ms)
constexpr byte LED_BLINK_DURATION = 100; // Duración del parpadeo del LED en ms
constexpr byte LED_BLINK_DURATION_DETECTED = 200; // Duración del parpadeo del LED al detectar un gesto (ms)
// Definiciones de Pines
const byte touchPins[] = {4, 12, 13, 14, 15, 27, 32, 33}; // Pines táctiles
constexpr byte NUM_PINS = sizeof(touchPins) / sizeof(touchPins[0]); // Número de pines táctiles
constexpr byte LED_PIN = 2; // Pin del LED indicativo
// Claves para Preferencias
const char* PREF_NAMESPACE = "touchConfig"; // Nombre del espacio de preferencias
const char* GESTO_COUNT_KEY = "gesto_count"; // Clave para almacenar el conteo de gestos
// Estructuras
struct Action {
byte tipo; // Tipo de acción
unsigned long delayAntes; // Retardo antes de ejecutar la acción (ms)
byte tarea; // Tarea asociada a la acción
};
struct Gesto {
byte id; // Identificador único del gesto
byte secuencia[MAX_SECUENCIA]; // Secuencia de pines que conforman el gesto
byte length; // Longitud de la secuencia
Action acciones[MAX_ACCIONES]; // Array de acciones asociadas al gesto
byte accionCount; // Número de acciones asociadas
};
// Variables Globales
Preferences prefs; // Objeto para manejar preferencias
Gesto gestos[MAX_GESTOS]; // Array para almacenar gestos
byte gestoCount = 0; // Conteo actual de gestos almacenados
byte storedThresholds[NUM_PINS]; // Umbrales almacenados para cada pin táctil
bool pinDetected[NUM_PINS] = {false}; // Estado de detección para cada pin
bool execution = true; // Bandera para controlar la ejecución del loop
int previousValues[NUM_PINS]; // Valores anteriores de cada pin táctil
byte touchBuffer[BUFFER_SIZE]; // Buffer para almacenar secuencias táctiles
byte currentBufferSize = 0; // Tamaño actual del buffer
unsigned long lastTouchTime = 0; // Último tiempo registrado de toque
// Prototipos de Funciones
void loadThresholds();
void loadGestos();
void saveGesto(const Gesto& gesto);
void saveGestoCount();
void handleCommand(const String& command);
void addGesto(const String& command);
bool isValidPin(int pin);
byte getDefaultThreshold(byte index);
void addToBuffer(byte pin); // Función para gestionar el buffer táctil
void clearBuffer(); // Función para limpiar el buffer táctil
void detectGestures(); // Función para detectar gestos en el buffer táctil
void performAction(const Action& accion, const Gesto& gesto); // Ejecutar acción basada en tipo
// Prototipos de Funciones de Depuración (Debug)
void D_Log(const String& message); // Función de depuración para loguear mensajes y parpadear el LED
void D_PrintPinValues(); // Función de depuración para imprimir valores de pines
void D_PrintGestos(); // Función de depuración para imprimir gestos almacenados
void D_Action0(const Gesto& gesto); // Función de depuración para acción tipo 0
// Configuración Inicial
void setup() {
Serial.begin(115200); // Inicializar comunicación serial
pinMode(LED_PIN, OUTPUT); // Configurar pin del LED como salida
prefs.begin(PREF_NAMESPACE, false); // Iniciar preferencias en modo lectura/escritura
loadThresholds(); // Cargar umbrales desde preferencias
loadGestos(); // Cargar gestos desde preferencias
prefs.end(); // Finalizar acceso a preferencias
D_Log("Setup completo"); // Loguear mensaje de configuración completa
}
// Bucle Principal
void loop() {
// Manejo de Comandos Serial
if (Serial.available()) {
String command = Serial.readStringUntil('\n'); // Leer comando hasta nueva línea
command.trim(); // Eliminar espacios en blanco
handleCommand(command); // Manejar el comando recibido
}
// Limpiar Buffer por Inactividad
unsigned long currentTime = millis();
if (currentBufferSize > 0 && (currentTime - lastTouchTime > INACTIVITY_TIMEOUT)) {
D_Log("Limpiando buffer por inactividad"); // Loguear limpieza de buffer
clearBuffer(); // Limpiar buffer táctil
}
if (!execution) return; // Si ejecución está detenida, salir del loop
// Lectura de Pines Táctiles
for (byte i = 0; i < NUM_PINS; i++) {
int currentValue = touchRead(touchPins[i]); // Leer valor táctil actual
if (currentValue != previousValues[i]) { // Si el valor ha cambiado
if (currentValue < storedThresholds[i] && !pinDetected[i]) {
D_Log("Pin " + String(touchPins[i]) + " modificado por debajo del umbral"); // Loguear cambio
pinDetected[i] = true; // Marcar pin como detectado
addToBuffer(touchPins[i]); // Añadir pin al buffer
detectGestures(); // Detectar gestos
} else if (currentValue >= storedThresholds[i] && pinDetected[i]) {
pinDetected[i] = false; // Resetear detección del pin
}
previousValues[i] = currentValue; // Actualizar valor anterior
}
}
}
// Función para Cargar Umbrales desde Preferencias
void loadThresholds() {
for (byte i = 0; i < NUM_PINS; i++) {
String key = "threshold" + String(i); // Clave para el umbral
if (prefs.isKey(key.c_str())) {
storedThresholds[i] = static_cast<byte>(prefs.getUInt(key.c_str(), 60)); // Obtener umbral almacenado
} else {
storedThresholds[i] = getDefaultThreshold(i); // Usar umbral por defecto
prefs.putUInt(key.c_str(), storedThresholds[i]); // Guardar umbral por defecto en preferencias
}
previousValues[i] = touchRead(touchPins[i]); // Leer valor táctil inicial
}
}
// Función para Obtener Umbral por Defecto
byte getDefaultThreshold(byte index) {
constexpr byte DEFAULT_THRESHOLDS[NUM_PINS] = {60, 50, 55, 60, 55, 65, 65, 50}; // Umbrales por defecto
return (index < NUM_PINS) ? DEFAULT_THRESHOLDS[index] : 60; // Retornar umbral correspondiente
}
// Función para Cargar Gestos desde Preferencias
void loadGestos() {
gestoCount = static_cast<byte>(prefs.getUInt(GESTO_COUNT_KEY, 0)); // Obtener conteo de gestos
for (byte i = 0; i < gestoCount && i < MAX_GESTOS; i++) {
String key = "gesto_" + String(i); // Clave para cada gesto
if (prefs.isKey(key.c_str())) {
String value = prefs.getString(key.c_str(), ""); // Obtener secuencia y acciones del gesto
gestos[i].id = i; // Asignar ID del gesto
gestos[i].length = 0; // Inicializar longitud de secuencia
gestos[i].accionCount = 0; // Inicializar conteo de acciones
int separatorIndex = value.indexOf('|'); // Encontrar separador entre secuencia y acciones
if (separatorIndex != -1) {
String secuenciaStr = value.substring(0, separatorIndex); // Extraer secuencia
String accionesStr = value.substring(separatorIndex + 1); // Extraer acciones
// Procesar secuencia de pines
int idx = 0;
while (idx < secuenciaStr.length()) {
int commaIndex = secuenciaStr.indexOf(',', idx); // Encontrar coma como separador
if (commaIndex == -1) commaIndex = secuenciaStr.length(); // Si no hay coma, fin de cadena
String pinStr = secuenciaStr.substring(idx, commaIndex); // Extraer pin como string
int pin = pinStr.toInt(); // Convertir pin a entero
if (gestos[i].length < MAX_SECUENCIA) {
gestos[i].secuencia[gestos[i].length++] = pin; // Añadir pin a la secuencia
}
idx = commaIndex + 1; // Avanzar al siguiente pin
}
// Procesar acciones
idx = 0;
while (idx < accionesStr.length() && gestos[i].accionCount < MAX_ACCIONES) {
if (accionesStr.startsWith("accion", idx)) {
// Separar la acción
idx += 6; // Mover índice después de "accion"
// Encontrar fin de la acción actual
int nextAccion = accionesStr.indexOf("accion", idx);
String accionStr;
if (nextAccion == -1) {
accionStr = accionesStr.substring(idx);
accionStr.trim(); // Eliminar espacios innecesarios
idx = accionesStr.length();
} else {
accionStr = accionesStr.substring(idx, nextAccion);
accionStr.trim(); // Eliminar espacios innecesarios
idx = nextAccion;
}
// Parsear tipo, delayAntes y tarea
int firstSpace = accionStr.indexOf(' ');
int secondSpace = accionStr.indexOf(' ', firstSpace + 1);
if (firstSpace != -1 && secondSpace != -1) {
String tipoStr = accionStr.substring(0, firstSpace);
String delayStr = accionStr.substring(firstSpace + 1, secondSpace);
String tareaStr = accionStr.substring(secondSpace + 1);
Action accion;
accion.tipo = tipoStr.toInt();
accion.delayAntes = delayStr.toInt();
accion.tarea = tareaStr.toInt();
gestos[i].acciones[gestos[i].accionCount++] = accion;
}
} else {
break; // No más acciones
}
}
} else {
// Si no hay separador, solo secuencia
int idx = 0;
while (idx < value.length()) {
int commaIndex = value.indexOf(',', idx); // Encontrar coma como separador
if (commaIndex == -1) commaIndex = value.length(); // Si no hay coma, fin de cadena
String pinStr = value.substring(idx, commaIndex); // Extraer pin como string
int pin = pinStr.toInt(); // Convertir pin a entero
if (gestos[i].length < MAX_SECUENCIA) {
gestos[i].secuencia[gestos[i].length++] = pin; // Añadir pin a la secuencia
}
idx = commaIndex + 1; // Avanzar al siguiente pin
}
}
}
else {
gestoCount = i; // Si falta un gesto, ajustar conteo
break;
}
}
}
// Función para Manejar Comandos Recibidos por Serial
void handleCommand(const String& command) {
if (command.startsWith("gesto ")) {
// Formato: "gesto pin pin... = accion tipo delay tarea ... accion tipo delay tarea"
addGesto(command);
}
else if (command.equalsIgnoreCase("gesto")) {
// Si el comando es exactamente "gesto", listar gestos
D_PrintGestos(); // Imprimir gestos almacenados
}
else if (command.equalsIgnoreCase("stop")) {
execution = false; // Detener ejecución
D_Log("Ejecución detenida"); // Loguear detención
}
else if (command.equalsIgnoreCase("pin")) {
D_PrintPinValues(); // Imprimir valores de pines
}
else {
D_Log("Comando desconocido."); // Informar comando no reconocido
}
}
// Función para Añadir un Nuevo Gesto con Acciones
void addGesto(const String& command) {
if (gestoCount >= MAX_GESTOS) {
D_Log("Límite de gestos alcanzado."); // Loguear límite alcanzado
return;
}
// Encontrar el separador '='
int equalIndex = command.indexOf('=');
if (equalIndex == -1) {
D_Log("Formato incorrecto. Use: gesto pin pin... = accion tipo delay tarea ...");
return;
}
// Extraer secuencia y acciones
String secuenciaStr = command.substring(6, equalIndex); // Después de "gesto " hasta '='
secuenciaStr.trim(); // Eliminar espacios en blanco
String accionesStr = command.substring(equalIndex + 1);
accionesStr.trim(); // Eliminar espacios en blanco
// Crear nuevo gesto
Gesto newGesto;
newGesto.id = gestoCount;
newGesto.length = 0;
newGesto.accionCount = 0;
// Procesar secuencia de pines
int idx = 0;
while (idx < secuenciaStr.length()) {
int spaceIndex = secuenciaStr.indexOf(' ', idx);
if (spaceIndex == -1) spaceIndex = secuenciaStr.length();
String pinStr = secuenciaStr.substring(idx, spaceIndex);
int pin = pinStr.toInt();
if (isValidPin(pin)) {
if (newGesto.length < MAX_SECUENCIA) {
newGesto.secuencia[newGesto.length++] = pin;
}
else {
D_Log("Secuencia excede el tamaño máximo de " + String(MAX_SECUENCIA) + " pines.");
break;
}
}
else {
D_Log("Pin inválido: " + String(pin));
}
idx = spaceIndex + 1;
}
// Procesar acciones
idx = 0;
while (idx < accionesStr.length() && newGesto.accionCount < MAX_ACCIONES) {
if (!accionesStr.startsWith("accion", idx)) {
D_Log("Formato de acción incorrecto. Use: accion tipo delay tarea");
break;
}
idx += 6; // Mover índice después de "accion"
// Extraer tipo, delayAntes y tarea
int spaceIndex1 = accionesStr.indexOf(' ', idx);
if (spaceIndex1 == -1) break;
String tipoStr = accionesStr.substring(idx, spaceIndex1);
idx = spaceIndex1 + 1;
int spaceIndex2 = accionesStr.indexOf(' ', idx);
if (spaceIndex2 == -1) break;
String delayStr = accionesStr.substring(idx, spaceIndex2);
idx = spaceIndex2 + 1;
int spaceIndex3 = accionesStr.indexOf(' ', idx);
String tareaStr;
if (spaceIndex3 == -1) {
tareaStr = accionesStr.substring(idx);
idx = accionesStr.length();
}
else {
tareaStr = accionesStr.substring(idx, spaceIndex3);
idx = spaceIndex3 + 1;
}
if (tipoStr.length() == 0 || delayStr.length() == 0 || tareaStr.length() == 0) {
D_Log("Formato de acción incompleto.");
continue;
}
Action accion;
accion.tipo = tipoStr.toInt();
accion.delayAntes = delayStr.toInt();
accion.tarea = tareaStr.toInt();
newGesto.acciones[newGesto.accionCount++] = accion;
}
if (newGesto.length > 0) {
gestos[gestoCount] = newGesto; // Almacenar nuevo gesto
saveGesto(newGesto); // Guardar gesto en preferencias
D_Log("Gesto " + String(newGesto.id) + " agregado con secuencia y acciones."); // Loguear adición
gestoCount++; // Incrementar conteo de gestos
saveGestoCount(); // Guardar nuevo conteo de gestos
}
else {
D_Log("Secuencia de gesto inválida.");
}
}
// Función para Validar si un Pin es Válido
bool isValidPin(int pin) {
for (byte i = 0; i < NUM_PINS; i++) {
if (touchPins[i] == pin) return true; // Retornar verdadero si el pin es válido
}
return false; // Retornar falso si el pin no es válido
}
// Función para Guardar un Gesto en Preferencias (Incluye Secuencia y Acciones)
void saveGesto(const Gesto& gesto) {
String key = "gesto_" + String(gesto.id); // Clave para el gesto
String value;
// Guardar secuencia de pines separados por comas
for (byte i = 0; i < gesto.length; i++) {
value += String(gesto.secuencia[i]); // Añadir pin a la cadena
if (i < gesto.length - 1) value += ","; // Añadir coma como separador
}
value += "|"; // Separador entre secuencia y acciones
// Guardar acciones separadas por espacios
for (byte i = 0; i < gesto.accionCount; i++) {
value += "accion " + String(gesto.acciones[i].tipo) + " " + String(gesto.acciones[i].delayAntes) + " " + String(gesto.acciones[i].tarea);
if (i < gesto.accionCount - 1) value += " "; // Añadir espacio entre acciones
}
prefs.putString(key.c_str(), value); // Guardar secuencia y acciones en preferencias
}
// Función para Guardar el Conteo de Gestos en Preferencias
void saveGestoCount() {
prefs.putUInt(GESTO_COUNT_KEY, gestoCount); // Guardar conteo de gestos
}
// Función para Gestionar el Buffer Táctil
void addToBuffer(byte pin) {
if (currentBufferSize < BUFFER_SIZE) {
touchBuffer[currentBufferSize++] = pin; // Añadir pin al buffer
}
else {
memmove(touchBuffer, touchBuffer + 1, BUFFER_SIZE - 1); // Desplazar buffer hacia la izquierda
touchBuffer[BUFFER_SIZE - 1] = pin; // Añadir nuevo pin al final
}
lastTouchTime = millis(); // Actualizar tiempo del último toque
}
// Función para Limpiar el Buffer Táctil
void clearBuffer() {
currentBufferSize = 0; // Resetear tamaño del buffer
}
// Función para Detectar Gestos desde el Buffer Táctil
void detectGestures() {
for (byte g = 0; g < gestoCount; g++) {
if (currentBufferSize < gestos[g].length) continue; // Continuar si el buffer es más pequeño que el gesto
for (byte b = 0; b <= currentBufferSize - gestos[g].length; b++) {
bool match = true;
for (byte s = 0; s < gestos[g].length; s++) {
if (touchBuffer[b + s] != gestos[g].secuencia[s]) { // Comparar secuencias
match = false;
break;
}
}
if (match) {
D_Log("Gesto " + String(gestos[g].id) + " detectado."); // Loguear detección de gesto
digitalWrite(LED_PIN, HIGH); // Encender LED
delay(LED_BLINK_DURATION_DETECTED); // Esperar
digitalWrite(LED_PIN, LOW); // Apagar LED
// Ejecutar acciones asociadas al gesto
for (byte a = 0; a < gestos[g].accionCount; a++) {
performAction(gestos[g].acciones[a], gestos[g]);
}
break; // Evitar múltiples detecciones del mismo gesto
}
}
}
}
// Función para Ejecutar Acción Basada en Tipo
void performAction(const Action& accion, const Gesto& gesto) {
delay(accion.delayAntes); // Retardo antes de ejecutar la acción
switch(accion.tipo) {
case 0:
D_Action0(gesto); // Ejecutar acción tipo 0: debug
break;
// Aquí se pueden agregar más casos para otros tipos de acciones en el futuro
default:
D_Log("Tipo de acción desconocido: " + String(accion.tipo)); // Loguear tipo de acción desconocido
break;
}
}
// -----------------------------------------------------------------------------
// Funciones de Depuración (Debug)
// -----------------------------------------------------------------------------
// Función de Depuración para Loguear Mensajes y Parpadear el LED
void D_Log(const String& message) {
Serial.println(message); // Imprimir mensaje en serial
digitalWrite(LED_PIN, HIGH); // Encender LED
delay(LED_BLINK_DURATION); // Esperar
digitalWrite(LED_PIN, LOW); // Apagar LED
}
// Función de Depuración para Imprimir Valores de Pines
void D_PrintPinValues() {
String values = "Valores de pines: ";
for (byte i = 0; i < NUM_PINS; i++) {
values += "Pin " + String(touchPins[i]) + ": " + String(touchRead(touchPins[i])) + " "; // Añadir valor de pin
}
D_Log(values); // Loguear valores de pines
}
// Función de Depuración para Imprimir Gestos Almacenados
void D_PrintGestos() {
if (gestoCount == 0) {
D_Log("No hay gestos almacenados."); // Loguear ausencia de gestos
return;
}
for (byte i = 0; i < gestoCount; i++) {
String gestoInfo = "Gesto " + String(gestos[i].id) + ": ";
for (byte j = 0; j < gestos[i].length; j++) {
gestoInfo += String(gestos[i].secuencia[j]); // Añadir pin a la información del gesto
if (j < gestos[i].length - 1) gestoInfo += " "; // Añadir espacio como separador
}
D_Log(gestoInfo); // Loguear información del gesto
// Imprimir acciones asociadas al gesto
for (byte a = 0; a < gestos[i].accionCount; a++) {
String accionInfo = " Acción " + String(a) + ": Tipo=" + String(gestos[i].acciones[a].tipo) +
", Delay=" + String(gestos[i].acciones[a].delayAntes) +
", Tarea=" + String(gestos[i].acciones[a].tarea);
D_Log(accionInfo); // Loguear información de la acción
}
}
}
// Función de Depuración para Acción Tipo 0 (Debug)
void D_Action0(const Gesto& gesto) {
D_Log("Acción Debug ejecutada para gesto " + String(gesto.id) + " con tarea " + String(gesto.acciones[0].tarea)); // Loguear ejecución de acción
}