Esp32 ps4 servomotor

Hola buenas, estoy haciendo un trabajo de robotica y el servomotor no se me mueve cuando muevo ele eje X izquierdo del mando de PS4, si alguien me pudiera ayudar lo agradecería.
Este es el código:

#include <PS4Controller.h>
#include <ESP32Servo.h>
// Pines del ESP32
const int motorPin = 19;    // Pin de control del motor DC (PWM)
const int pinMotorA = 25;
const int pinMotorB = 26;
const int servoPin = 13;    // Pin del servo motor
const int LED_INTERMITENTE_R_Pin = 12;
const int LED_LUCES_Pin = 17;
const int LED_INTERMITENTE_L_Pin = 27;
const int ZumbadorPin = 5;
const int Luces_freno = 16;
Servo myservo;
int servoPos = 0;  // Posición inicial del servo (centro)
int val = 0;

// Función para obtener un número aleatorio entre a y b
double math_random_int(int a, int b) {
  if (a > b) {
    int c = a;
    a = b;
    b = c;
  }
  return (double)random(a, b + 1);
}

// Variables para botones
int no;
bool RadioPressed = false;
bool ClaxonPressed = false;
bool lucesPressed = false;
bool leftPressed = false;
bool rightPressed = false;
bool RadioPreviousState = false;
bool ClaxonPreviousState = false;
bool previousMillisZumbador = 0; 
bool lucesPreviousState = false;
bool leftPreviousState = false;
bool rightPreviousState = false;
int CANCION_RADIO_FM = 0;
int POU = 1;
int PinMotorA;
int PinMotorB;
int Valor_R2; 
int Valor_L2;
int Velocidad = Valor_R2 - Valor_L2;
int antVelocidad = 0;
int aceleracion; 
int Ciudad = Velocidad/3 ;  // Resta mapeada
// Variables para intermitentes
unsigned long previousMillisLeft = 0;
unsigned long previousMillisRight = 0;
const long interval = 500;  // Intervalo de 500 ms para el parpadeo
bool leftState = false;
bool zumbadorState = false;
bool rightState = false;

void setup() {
    // Iniciar comunicación con el controlador PS4
    PS4.begin();  // Dirección MAC del ESP32  
    //pinMode(servoPin, OUTPUT);
    myservo.attach(servoPin);
    pinMode (motorPin, OUTPUT);
    pinMode (pinMotorA, OUTPUT);
    pinMode (pinMotorB, OUTPUT);
    pinMode(Luces_freno, OUTPUT);
    pinMode(ZumbadorPin, OUTPUT);
    pinMode(LED_INTERMITENTE_L_Pin, OUTPUT);
    pinMode(LED_INTERMITENTE_R_Pin, OUTPUT);
    pinMode(LED_LUCES_Pin, OUTPUT);

    Serial.begin(9600);
   myservo.setPeriodHertz(10);// Standard 50hz servo
   myservo.attach(servoPin, 500, 2500);  
   // myservo.attach(servoPin);  
}

void loop() {
    if (PS4.isConnected()) {
        Valor_R2 = (PS4.R2Value());  
        Valor_L2 = (PS4.L2Value());
        Velocidad = Valor_R2 - Valor_L2;
        Serial.print("Valor_R2: ");
        Serial.println(Valor_R2);
        Serial.print("Valor_L2: ");
        Serial.println(Valor_L2);
        Serial.print("Velocidad: ");
        Serial.println(Velocidad);
        aceleracion = Velocidad - antVelocidad;
        Serial.print("aceleracion: ");
        Serial.println(aceleracion);
        antVelocidad = Velocidad;

        if (aceleracion < 0 && Velocidad >= 0) {
            digitalWrite(Luces_freno, HIGH);  // Encender LED si está frenando
        } else {
            digitalWrite(Luces_freno, LOW);  // Apagar LED si no está frenando
        }

        // Control del motor
        if (Velocidad > 0) { 
            PS4.setRumble(Valor_L2, Valor_R2);  
            digitalWrite(pinMotorA, LOW);
            digitalWrite(pinMotorB, HIGH);
            analogWrite(motorPin, Velocidad);  
        }
        else if (Velocidad < 0) {
            PS4.setRumble(Valor_L2, Valor_R2);
            digitalWrite(pinMotorA, HIGH);
            digitalWrite(pinMotorB, LOW);
            analogWrite(motorPin, -Velocidad);  
        }
        else {  
            digitalWrite(pinMotorA, LOW);
            digitalWrite(pinMotorB, LOW);
            analogWrite(motorPin, 0);
        }
       
        int servoX;
        servoX = PS4.LStickX();            // read the up/down value of the Left Stick
        val = map(servoX, -127, 127,0 ,180);     // scale it to use it with the servo
        Serial.print("val: ");
        Serial.println(val); //Print the angle to the Serial Monitor
        Serial.print("PS L X: ");
        Serial.println(PS4.LStickX()); 
        myservo.write(val);  //write the value to the servo

        delay (1000);

        // Alternar luces al presionar el botón "Up"
        bool lucesState = PS4.Up();
        if (lucesState && !lucesPreviousState) {
            lucesPressed = !lucesPressed;  // Alternar el estado de las luces
            Serial.println("Luces alternadas");
        }
        lucesPreviousState = lucesState;

        if (lucesPressed) {
            digitalWrite(LED_LUCES_Pin, HIGH);  // Encender luces
        } else {
            digitalWrite(LED_LUCES_Pin, LOW);    // Apagar luces
        }
               bool leftStatePS4 = PS4.Left();
        if (leftStatePS4 && !leftPreviousState) {
            // Solo alternar el intermitente izquierdo si el derecho NO está activo
            if (!rightPressed) {
                leftPressed = !leftPressed;  // Alternar el estado del intermitente izquierdo
                Serial.println("Intermitente izquierdo alternado");
            } else {
                Serial.println("No se puede activar el intermitente izquierdo porque el derecho está activado");
            }
        }
        leftPreviousState = leftStatePS4;

        // Leer estado de la flecha derecha (Intermitente derecho)
        bool rightStatePS4 = PS4.Right();
        if (rightStatePS4 && !rightPreviousState) {
            // Solo alternar el intermitente derecho si el izquierdo NO está activo
            if (!leftPressed) {
                rightPressed = !rightPressed;  // Alternar el estado del intermitente derecho
                Serial.println("Intermitente derecho alternado");
            } else {
                Serial.println("No se puede activar el intermitente derecho porque el izquierdo está activado");
            }
        }
        rightPreviousState = rightStatePS4;

        // Control del parpadeo de los intermitentes
        unsigned long currentMillis = millis();

        // Intermitente izquierdo
        if (leftPressed) {
            if (currentMillis - previousMillisLeft >= interval) {
                previousMillisLeft = currentMillis;
                leftState = !leftState;  // Cambiar el estado del LED
                digitalWrite(LED_INTERMITENTE_L_Pin, leftState ? HIGH : LOW);
            }
        } else {
            digitalWrite(LED_INTERMITENTE_L_Pin, LOW);  // Apagar el LED izquierdo
        }

        // Intermitente derecho
        if (rightPressed) {
            if (currentMillis - previousMillisRight >= interval) {
                previousMillisRight = currentMillis;
                rightState = !rightState;  // Cambiar el estado del LED
                digitalWrite(LED_INTERMITENTE_R_Pin, rightState ? HIGH : LOW);
            }
        } else {
            digitalWrite(LED_INTERMITENTE_R_Pin, LOW);  // Apagar el LED derecho
        }
    }
}

La placa es una ESP32-Steammaker y el servomotor es de la marca Miuzei Micro servo 9g MS18. Gracias por vuestra atencion y espero solucionar este problema pronto.

Pero funciona algo?
Que control PS4 usas, dinos la marca.
Lee esto y la recomendación a un hilo mas viejo donde explico como aparear mando SONY y ESP32 a través de programa que si o si requieres para conocer que MAC tiene el mando.

Funcionan los pins, se mueve de 90 a 180, es un mando original de ps4, pero necesito más movilidad para el proyecto, gracias por leer mi post

Qué significa necesito mas movilidad? Da mas detalles.

Ahora que releí todo entiendo, al hacerlo de 90 a 180 te esta faltando de 0 a 90.
Es eso?
Por favor, no tengo ganas de analizar el código, explica que tocas cuando lo hace de 90 a 180 y que tocas y no hace nada cuando quieres que haga de 0 a 90.

Más de 45º de movimiento, xq si lo pongo de 90-180 me va, pero solo se mueve esos 45º, y de 0 a 90 no me va o de 180 a 270. Quiero ponerlo de 0 a 135 o 180, pero si lo pongo solo me va cuando muevo el joystick a la derecha y a la izquierda no hace nada. Si no quieres analizar el código no lo analices, pero si sabes como solucionarlo dilo, porfa.

Okay, deja tu código y analiza el comando, a ver si esta variando como se espera.

        int servoX;
        servoX = PS4.LStickX();            // read the up/down value of the Left Stick
        val = map(servoX, -127, 127,0 ,180);     // scale it to use it with the servo
        Serial.print("val: ");
        Serial.println(val); //Print the angle to the Serial Monitor
        Serial.print("PS L X: ");
        Serial.println(PS4.LStickX()); 
        myservo.write(val);  //write the value to the servo

Olvida todo el codigo y crea un código simple que muestre PS4.LStickX() y PS4.RStickX()

#include <PS4Controller.h>

void setup() {
  Serial.begin(115200);
  PS4.begin();
  Serial.println("Ready.");
}

void loop() {
  // Below has all accessible outputs from the controller
  if (PS4.isConnected()) {
    if (PS4.LStickX()) {
      Serial.printf("Left Stick x at %d\n", PS4.LStickX());
    }
    if (PS4.LStickY()) {
      Serial.printf("Left Stick y at %d\n", PS4.LStickY());
    }
    if (PS4.RStickX()) {
      Serial.printf("Right Stick x at %d\n", PS4.RStickX());
    }
    if (PS4.RStickY()) {
      Serial.printf("Right Stick y at %d\n", PS4.RStickY());
    }
    delay(1000);
  }
}

No recuerdo cuales son pero prueba tener un desplazamiento correcto en alguno y luego usa ese.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.