// Pines del joystick y LEDs
const int JOYSTICK_X_PIN = 34; // Entrada analógica del joystick (Eje X)
const int LED_LEFT_PIN = 25; // LED izquierdo
const int LED_MIDDLE_PIN = 26; // LED central
const int LED_RIGHT_PIN = 27; // LED derecho
// Rango de entrada del ESP32 (ADC de 12 bits)
const int ADC_MIN = 0;
const int ADC_MAX = 4095;
// Rango de salida PWM (0-255)
const int PWM_MIN = 0;
const int PWM_MAX = 255;
// Variables para suavizar transiciones
float smoothLeft = 0;
float smoothMiddle = 0;
float smoothRight = 0;
const float smoothFactor = 0.1; // Cuanto más bajo, más suave la transición
// Función para suavizar transiciones usando un filtro exponencial
float smoothTransition(float currentValue, float targetValue) {
return currentValue + smoothFactor * (targetValue - currentValue);
}
void setup() {
pinMode(LED_LEFT_PIN, OUTPUT);
pinMode(LED_MIDDLE_PIN, OUTPUT);
pinMode(LED_RIGHT_PIN, OUTPUT);
}
void loop() {
// Leer la posición del joystick en el eje X
int joyX = analogRead(JOYSTICK_X_PIN);
// Convertir el valor del joystick a un rango de -1.0 (izquierda) a 1.0 (derecha)
float position = map(joyX, ADC_MIN, ADC_MAX, -100, 100) / 100.0;
// Determinar los valores objetivo para los LEDs según la posición del joystick
int targetLeft = map(position * 100, -100, 100, PWM_MAX, PWM_MIN); // Izquierda fuerte
int targetMiddle = map(abs(position * 100), 0, 100, PWM_MIN + 100, PWM_MAX); // Medio fuerte en centro
int targetRight = map(position * 100, -100, 100, PWM_MIN, PWM_MAX); // Derecha fuerte
// Aplicar los valores correctos según las posiciones requeridas
if (position < -0.5) { // Joystick a la izquierda
targetLeft = PWM_MAX; // 100%
targetMiddle = PWM_MAX * 0.3; // 40%
targetRight = PWM_MAX * 0.1; // 10%
}
else if (position > 0.5) { // Joystick a la derecha
targetLeft = PWM_MAX * 0.1; // 10%
targetMiddle = PWM_MAX * 0.3; // 40%
targetRight = PWM_MAX; // 100%
}
else { // Joystick en el centro
targetLeft = PWM_MAX * 0.3; // 40%
targetMiddle = PWM_MAX; // 100%
targetRight = PWM_MAX * 0.3; // 40%
}
// Suavizar la transición de los LEDs
smoothLeft = smoothTransition(smoothLeft, targetLeft);
smoothMiddle = smoothTransition(smoothMiddle, targetMiddle);
smoothRight = smoothTransition(smoothRight, targetRight);
// Aplicar valores PWM a los LEDs
analogWrite(LED_LEFT_PIN, (int)smoothLeft);
analogWrite(LED_MIDDLE_PIN, (int)smoothMiddle);
analogWrite(LED_RIGHT_PIN, (int)smoothRight);
// Pequeño retraso para estabilidad
delay(10);
}