// =====================================================================================
// === PROYECTO ESCLAVO (CON BLUETOOTH) ===
// =====================================================================================
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP32Encoder.h>
#include <BluetoothSerial.h>
// --- CONFIGURACIÓN DE BLUETOOTH ---
BluetoothSerial SerialBT;
String btBuffer = "";
const char* masterDeviceName = "PatroDJ_Master";
// ... (El resto de las configuraciones y pines son idénticos) ...
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define VOL_CLK_PIN 12
#define VOL_DT_PIN 13
#define GAIN_CLK_PIN 1
#define GAIN_DT_PIN 3
#define HIGH_CLK_PIN 34
#define HIGH_DT_PIN 35
#define MID_HIGH_CLK_PIN 32
#define MID_HIGH_DT_PIN 33
#define MID_LOW_CLK_PIN 25
#define MID_LOW_DT_PIN 26
#define LOW_CLK_PIN 27
#define LOW_DT_PIN 14
#define DISPLAY_TIMEOUT_MS 3000
#define ENCODER_STEPS_PER_DB 2
const int VOL_MIN = -80, VOL_MAX = 10;
const int GAIN_MIN = -20, GAIN_MAX = 20;
const int EQ_MIN = -15, EQ_MAX = 15;
ESP32Encoder encoderVol;
ESP32Encoder encoderGain;
ESP32Encoder encoderHigh;
ESP32Encoder encoderMidHigh;
ESP32Encoder encoderMidLow;
ESP32Encoder encoderLow;
int currentVolDB = 0;
int currentGainDB = 0;
int currentHighDB = 0;
int currentMidHighDB = 0;
int currentMidLowDB = 0;
int currentLowDB = 0;
enum DisplayMode { MODE_IDLE, MODE_PARAM };
DisplayMode currentMode = MODE_IDLE;
unsigned long lastInteractionTime = 0;
// --- PROTOTIPOS DE FUNCIONES ---
void actualizarPantallaParametro(const char *paramName, int currentValue, int minValue, int maxValue);
void handleBluetoothCommands();
void showConnectedScreen(); // <<-- CAMBIO: Renombrada para mayor claridad
// =====================================================================================
// === SETUP ===
// =====================================================================================
void setup() {
Wire.begin();
SerialBT.begin("PatroDJ_Slave");
// ... (Inicialización de encoders es idéntica) ...
encoderVol.attachHalfQuad(VOL_DT_PIN, VOL_CLK_PIN);
encoderVol.setCount(VOL_MIN * ENCODER_STEPS_PER_DB);
currentVolDB = VOL_MIN;
encoderGain.attachHalfQuad(GAIN_DT_PIN, GAIN_CLK_PIN);
encoderGain.setCount(0 * ENCODER_STEPS_PER_DB);
encoderHigh.attachHalfQuad(HIGH_DT_PIN, HIGH_CLK_PIN);
encoderHigh.setCount(0 * ENCODER_STEPS_PER_DB);
encoderMidHigh.attachHalfQuad(MID_HIGH_DT_PIN, MID_HIGH_CLK_PIN);
encoderMidHigh.setCount(0 * ENCODER_STEPS_PER_DB);
encoderMidLow.attachHalfQuad(MID_LOW_DT_PIN, MID_LOW_CLK_PIN);
encoderMidLow.setCount(0 * ENCODER_STEPS_PER_DB);
encoderLow.attachHalfQuad(LOW_DT_PIN, LOW_CLK_PIN);
encoderLow.setCount(0 * ENCODER_STEPS_PER_DB);
// --- Inicialización de la pantalla OLED ---
display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(20, 10);
display.println("ESCLAVO");
display.setTextSize(1);
display.setCursor(10, 35);
display.print("Buscando Maestro...");
display.display();
// <<-- CAMBIO: Bucle de conexión persistente, es la prioridad
while (!SerialBT.connect(masterDeviceName)) {
delay(1000); // Esperar 1 segundo antes de reintentar
}
// Conectado!
showConnectedScreen();
lastInteractionTime = millis();
}
// =====================================================================================
// === MAIN LOOP ===
// =====================================================================================
void loop() {
// <<-- CAMBIO: Si se pierde la conexión, la prioridad es reconectar
if (!SerialBT.connected()) {
display.clearDisplay();
display.setTextSize(1);
display.setCursor(10, 35);
display.print("CONEXION PERDIDA");
display.setCursor(10, 45);
display.print("Reconectando...");
display.display();
while (!SerialBT.connect(masterDeviceName)) {
delay(1000); // Reintentar cada segundo
}
showConnectedScreen(); // Volver a la pantalla de conectado
lastInteractionTime = millis(); // Resetear el temporizador de pantalla
}
bool interaction = false;
// --- 0. PROCESAR COMANDOS ENTRANTES DEL MAESTRO ---
if (SerialBT.available()) {
handleBluetoothCommands();
interaction = true;
}
// --- 1. LEER ENCODERS LOCALES Y ENVIAR COMANDOS ---
// ... (El resto del loop es idéntico, leyendo encoders y enviando por BT) ...
long newVol = encoderVol.getCount() / ENCODER_STEPS_PER_DB;
if (newVol > VOL_MAX) { newVol = VOL_MAX; encoderVol.setCount(newVol * ENCODER_STEPS_PER_DB); }
if (newVol < VOL_MIN) { newVol = VOL_MIN; encoderVol.setCount(newVol * ENCODER_STEPS_PER_DB); }
if (newVol != currentVolDB) {
currentVolDB = newVol;
SerialBT.printf("V%d;", currentVolDB);
actualizarPantallaParametro("VOLUMEN", currentVolDB, VOL_MIN, VOL_MAX);
interaction = true;
}
// ... resto de encoders ...
long newGain = encoderGain.getCount() / ENCODER_STEPS_PER_DB;
if (newGain > GAIN_MAX) { newGain = GAIN_MAX; encoderGain.setCount(newGain * ENCODER_STEPS_PER_DB); }
if (newGain < GAIN_MIN) { newGain = GAIN_MIN; encoderGain.setCount(newGain * ENCODER_STEPS_PER_DB); }
if (newGain != currentGainDB) {
currentGainDB = newGain;
SerialBT.printf("G%d;", currentGainDB);
actualizarPantallaParametro("GAIN", currentGainDB, GAIN_MIN, GAIN_MAX);
interaction = true;
}
long newHigh = encoderHigh.getCount() / ENCODER_STEPS_PER_DB;
if (newHigh > EQ_MAX) { newHigh = EQ_MAX; encoderHigh.setCount(newHigh * ENCODER_STEPS_PER_DB); }
if (newHigh < EQ_MIN) { newHigh = EQ_MIN; encoderHigh.setCount(newHigh * ENCODER_STEPS_PER_DB); }
if (newHigh != currentHighDB) {
currentHighDB = newHigh;
SerialBT.printf("H%d;", currentHighDB);
actualizarPantallaParametro("HIGH", currentHighDB, EQ_MIN, EQ_MAX);
interaction = true;
}
long newMidHigh = encoderMidHigh.getCount() / ENCODER_STEPS_PER_DB;
if (newMidHigh > EQ_MAX) { newMidHigh = EQ_MAX; encoderMidHigh.setCount(newMidHigh * ENCODER_STEPS_PER_DB); }
if (newMidHigh < EQ_MIN) { newMidHigh = EQ_MIN; encoderMidHigh.setCount(newMidHigh * ENCODER_STEPS_PER_DB); }
if (newMidHigh != currentMidHighDB) {
currentMidHighDB = newMidHigh;
SerialBT.printf("M%d;", currentMidHighDB);
actualizarPantallaParametro("MID HIGH", currentMidHighDB, EQ_MIN, EQ_MAX);
interaction = true;
}
long newMidLow = encoderMidLow.getCount() / ENCODER_STEPS_PER_DB;
if (newMidLow > EQ_MAX) { newMidLow = EQ_MAX; encoderMidLow.setCount(newMidLow * ENCODER_STEPS_PER_DB); }
if (newMidLow < EQ_MIN) { newMidLow = EQ_MIN; encoderMidLow.setCount(newMidLow * ENCODER_STEPS_PER_DB); }
if (newMidLow != currentMidLowDB) {
currentMidLowDB = newMidLow;
SerialBT.printf("N%d;", currentMidLowDB);
actualizarPantallaParametro("MID LOW", currentMidLowDB, EQ_MIN, EQ_MAX);
interaction = true;
}
long newLow = encoderLow.getCount() / ENCODER_STEPS_PER_DB;
if (newLow > EQ_MAX) { newLow = EQ_MAX; encoderLow.setCount(newLow * ENCODER_STEPS_PER_DB); }
if (newLow < EQ_MIN) { newLow = EQ_MIN; encoderLow.setCount(newLow * ENCODER_STEPS_PER_DB); }
if (newLow != currentLowDB) {
currentLowDB = newLow;
SerialBT.printf("L%d;", currentLowDB);
actualizarPantallaParametro("LOW", currentLowDB, EQ_MIN, EQ_MAX);
interaction = true;
}
// --- 2. GESTIONAR EL MODO DE LA PANTALLA ---
if (interaction) {
lastInteractionTime = millis();
currentMode = MODE_PARAM; // Ya lo fuerza la propia función de actualizar
} else {
if (currentMode == MODE_PARAM && (millis() - lastInteractionTime > DISPLAY_TIMEOUT_MS)) {
showConnectedScreen(); // Dibujar pantalla de reposo
}
}
delay(20);
}
// ... (handleBluetoothCommands es idéntico) ...
// <<-- CAMBIO: Función renombrada y con texto más claro
void showConnectedScreen() {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(15, 24);
display.println("CONECTADO");
display.setTextSize(1);
display.setCursor(30, 45);
display.println("A MAESTRO");
display.display();
currentMode = MODE_IDLE;
}
// =====================================================================================
// === FUNCIONES DE COMUNICACIÓN BLUETOOTH ===
// =====================================================================================
void handleBluetoothCommands() {
String message = SerialBT.readStringUntil(';');
if (message.length() > 1) {
char command = message.charAt(0);
int value = message.substring(1).toInt();
// Actualizar el estado local y sincronizar el encoder correspondiente
switch (command) {
case 'V':
currentVolDB = value;
encoderVol.setCount(currentVolDB * ENCODER_STEPS_PER_DB);
actualizarPantallaParametro("VOLUMEN", currentVolDB, VOL_MIN, VOL_MAX);
break;
case 'G':
currentGainDB = value;
encoderGain.setCount(currentGainDB * ENCODER_STEPS_PER_DB);
actualizarPantallaParametro("GAIN", currentGainDB, GAIN_MIN, GAIN_MAX);
break;
case 'H':
currentHighDB = value;
encoderHigh.setCount(currentHighDB * ENCODER_STEPS_PER_DB);
actualizarPantallaParametro("HIGH", currentHighDB, EQ_MIN, EQ_MAX);
break;
case 'M': // Mid High
currentMidHighDB = value;
encoderMidHigh.setCount(currentMidHighDB * ENCODER_STEPS_PER_DB);
actualizarPantallaParametro("MID HIGH", currentMidHighDB, EQ_MIN, EQ_MAX);
break;
case 'N': // Mid Low
currentMidLowDB = value;
encoderMidLow.setCount(currentMidLowDB * ENCODER_STEPS_PER_DB);
actualizarPantallaParametro("MID LOW", currentMidLowDB, EQ_MIN, EQ_MAX);
break;
case 'L': // Low
currentLowDB = value;
encoderLow.setCount(currentLowDB * ENCODER_STEPS_PER_DB);
actualizarPantallaParametro("LOW", currentLowDB, EQ_MIN, EQ_MAX);
break;
}
}
}
// --- Función para dibujar la pantalla de reposo del esclavo ---
void drawIdleScreen() {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(15, 24);
display.println("CONECTADO");
display.display();
currentMode = MODE_IDLE;
}
// --- La función de dibujar parámetros es idéntica a la del maestro ---
void actualizarPantallaParametro(const char *paramName, int currentValue, int minValue, int maxValue) {
currentMode = MODE_PARAM; // Asegurarse de que estamos en el modo correcto
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(paramName, 0, 0, &x1, &y1, &w, &h);
display.setCursor((SCREEN_WIDTH - w) / 2, 2);
display.println(paramName);
char dbStr[10];
sprintf(dbStr, "%+d dB", currentValue);
display.getTextBounds(dbStr, 0, 0, &x1, &y1, &w, &h);
display.setCursor((SCREEN_WIDTH - w) / 2, 20);
display.print(dbStr);
int barWidth = map(currentValue, minValue, maxValue, 0, SCREEN_WIDTH);
display.drawRect(0, 42, SCREEN_WIDTH, 16, SSD1306_WHITE);
if (minValue < 0 && maxValue > 0) {
int zeroPoint = map(0, minValue, maxValue, 0, SCREEN_WIDTH);
display.drawFastVLine(zeroPoint, 40, 20, SSD1306_WHITE);
if (barWidth > zeroPoint) {
display.fillRect(zeroPoint, 42, barWidth - zeroPoint, 16, SSD1306_WHITE);
} else {
display.fillRect(barWidth, 42, zeroPoint - barWidth, 16, SSD1306_WHITE);
}
} else {
display.fillRect(0, 42, barWidth, 16, SSD1306_WHITE);
}
display.display();
}