Tb6612fng and servo doesnt work when i try to control it through esp now

Hello can somebody help me to fix my code ,the tb6612fng work as it is supposed to do the two esp32 are connected via ESPNOW and both send and receive the data the only issue i have is on how to control my servomotor

im using

GAMEPAD
Joyctick Module
ESP32 WROOM 32

CAR
ESP32 WROOM 32
TB6612FNG
SERVO

GAMEPAD

#include <esp_now.h>
#include <WiFi.h>
//E8:6B:EA:CA:54:20


// Define joystick pins
const int joyPinX = 34;  // Analog pin for X-axis
const int joyPinY = 32;  // (Optional) Analog pin for Y-axis if you want to use it


// Peer device MAC address (receiver's MAC)
uint8_t receiverAddress[] = {0xE8, 0x6B, 0xEA, 0xCA, 0x54, 0x20}; //find you device Mac address


typedef struct struct_message {
    int joyX;
    int joyY;
} struct_message;


struct_message joystickData;


void setup() {
    Serial.begin(115200);
    WiFi.mode(WIFI_STA);  // Set ESP32 to Wi-Fi station mode


    // Initialize ESP-NOW
    if (esp_now_init() != ESP_OK) {
        Serial.println("Error initializing ESP-NOW");
        return;
    }


    // Register peer
    esp_now_peer_info_t peerInfo;
    memcpy(peerInfo.peer_addr, receiverAddress, 6);
    peerInfo.channel = 0;  
    peerInfo.encrypt = false;


    if (esp_now_add_peer(&peerInfo) != ESP_OK) {
        Serial.println("Failed to add peer");
        return;
    }
}


void loop() {
    // Read joystick X and Y values
    joystickData.joyX = analogRead(joyPinX);  // Read X-axis
    joystickData.joyY = analogRead(joyPinY);  // (Optional) Read Y-axis if used


    // Send joystick data via ESP-NOW
    esp_err_t result = esp_now_send(receiverAddress, (uint8_t *) &joystickData, sizeof(joystickData));


    if (result == ESP_OK) {
        Serial.println("Sent successfully");
    } else {
        Serial.println("Error sending the data");
    }


    delay(100);  // Adjust delay as needed
}

CARCODE

#include <esp_now.h>
#include <WiFi.h>
#include <ESP32Servo.h>


// Pines para el control del motor con TB6612FNG
#define PWMA 27   // PWM para Motor A
#define PWMB 16   // PWM para Motor B
#define AIN1 26   // Dirección Motor A (IN1)
#define AIN2 17   // Dirección Motor A (IN2)
#define BIN1 14   // Dirección Motor B (IN1)
#define BIN2 12   // Dirección Motor B (IN2)
#define STBY 18   // Standby del driver


// Pin para el servomotor
#define SERVO_PIN 25


// Zona muerta
#define DEADZONE 150  // Tamaño de la zona muerta para el joystick


// Objeto para el servomotor
Servo servoX;


// Estructura de datos para recibir desde el transmisor
typedef struct struct_message {
    int joyX;
    int joyY;
} struct_message;


struct_message incomingData;


// Función para aplicar zona muerta
int applyDeadZone(int value, int center, int threshold) {
    if (abs(value - center) <= threshold) {
        return center; // Si está en la zona muerta, retorna el valor central
    }
    return value; // Si está fuera de la zona muerta, retorna el valor original
}


// Función para recibir datos
void OnDataRecv(const esp_now_recv_info *info, const uint8_t *data, int len) {
    if (len == sizeof(incomingData)) {
        memcpy(&incomingData, data, sizeof(incomingData));


        // Aplicar zona muerta
        int filteredJoyX = applyDeadZone(incomingData.joyX, 2048, DEADZONE);
        int filteredJoyY = applyDeadZone(incomingData.joyY, 2048, DEADZONE);


        // Mapeo de valores del joystick
        int servoAngleX = map(filteredJoyX, 0, 4095, 0, 180);       // X a ángulo del servo
        int motorSpeed = map(filteredJoyY, 0, 4095, -255, 255);     // Y a velocidad de motor


        // Constricción del ángulo del servomotor
        servoAngleX = constrain(servoAngleX, 50, 120);


        // Imprimir valores
        Serial.print("Filtered X: ");
        Serial.print(filteredJoyX);
        Serial.print(" | Filtered Y: ");
        Serial.println(filteredJoyY);


        Serial.print("Servo X Angle: ");
        Serial.println(servoAngleX);
        Serial.print("Motor velocity: ");
        Serial.println(motorSpeed);


        // Control del servomotor
        servoX.write(servoAngleX);


        // Control de ambos motores (PWM y dirección)
        if (motorSpeed > 0) {
            // Adelante
            digitalWrite(AIN1, HIGH);
            digitalWrite(AIN2, LOW);
            digitalWrite(BIN1, HIGH);
            digitalWrite(BIN2, LOW);
            analogWrite(PWMA, motorSpeed);
            analogWrite(PWMB, motorSpeed);
        } else if (motorSpeed < 0) {
            // Atrás
            digitalWrite(AIN1, LOW);
            digitalWrite(AIN2, HIGH);
            digitalWrite(BIN1, LOW);
            digitalWrite(BIN2, HIGH);
            analogWrite(PWMA, -motorSpeed);
            analogWrite(PWMB, -motorSpeed);
        } else {
            // Detener ambos motores
            digitalWrite(AIN1, LOW);
            digitalWrite(AIN2, LOW);
            digitalWrite(BIN1, LOW);
            digitalWrite(BIN2, LOW);
            analogWrite(PWMA, 0);
            analogWrite(PWMB, 0);
        }
    } else {
        Serial.println("Error: longitud de datos recibida no coincide.");
    }
}


void setup() {
    Serial.begin(115200);


    // Configurar pines del motor
    pinMode(PWMA, OUTPUT);
    pinMode(PWMB, OUTPUT);
    pinMode(AIN1, OUTPUT);
    pinMode(AIN2, OUTPUT);
    pinMode(BIN1, OUTPUT);
    pinMode(BIN2, OUTPUT);
    pinMode(STBY, OUTPUT);


    // Habilitar el driver (quitar standby)
    digitalWrite(STBY, HIGH);


    // Configurar el servomotor
    servoX.attach(SERVO_PIN);


    // Configurar ESP-NOW
    WiFi.mode(WIFI_STA);
    if (esp_now_init() != ESP_OK) {
        Serial.println("Error al inicializar ESP-NOW");
        return;
    }


    // Registrar función de callback para recibir datos
    esp_now_register_recv_cb(OnDataRecv);


    Serial.println("Receptor listo para recibir datos.");
}


void loop() {
    delay(100); // Ajustar según sea necesario
}


I have moved your topic from the Spanish language forum to the Using Arduino> Project Guidance category @loquini007.

From now on, please use the category appropriate to the language in which you wish to post. This is important for the responsible use of the forum, and it is explained here in the guide "How to get the best out of this forum".
This guide contains a lot of useful information. Please read it.

Thank you in advance for your cooperation.

Please don't post both codes in one code block; it took me a while to figure out where the car code was. I've fixed it for you.

Hi, @loquini007
Welcome to the forum.

Have you written your code in stages.

Do you have code that JUST proves you can make the servo sweep/work?
Nothing else connected or in the code.

Can you please post a copy of your circuit, a picture of a hand drawn circuit in jpg, png?
Hand drawn and photographed is perfectly acceptable.
Please include ALL hardware, power supplies, component names and pin labels.

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

Not with the TB6612FNG. It drives DC motors.

Hi, @loquini007

Can you please post a link to spec/data of your servo?

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

hello i already solved it

Can you share your solution so others that encounter a similar problem might be able to fix their problem.

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