Quiero sacar la posición del encoder a la vez que me mueve la rueda que tengo conectada al motor hacia adelante y hacia atrás. Con lo que tengo, solo me saca la posición del encoder pero no gira el motor, y está comprobado que le llega corriente cuando está en el modo de adelante o atrás.
El código es el siguiente (para Arduino IDE):
#include <Arduino.h>
#include <ESP32Encoder.h>
// Asignación de pines del ESP32
int motor2Pin0 = 27;
int motor2Pin1 = 26;
int enable2Pin = 14;
const int pwmChannel0 = 0; // Canal 0 PWM
const int pwmChannel1 = 1; // Canal 1 PWM
const int freq = 30000; // Frecuencia PWM
const int resolution = 8; // Resolución PWM en bits
// Definición de los pines para el encoder
#define PIN_IN1 18
#define PIN_IN2 19
// Crear un objeto ESP32Encoder
ESP32Encoder encoder;
int lastPos = 0;
unsigned long lastPrintTime = 0;
const unsigned long printInterval = 5000; // Intervalo de 5 segundos
void setup() {
// Declaración de los pines como salidas
pinMode(motor2Pin0, OUTPUT);
pinMode(motor2Pin1, OUTPUT);
pinMode(enable2Pin, OUTPUT);
// Configurar las funcionalidades del PWM
ledcAttachChannel(motor2Pin0, freq, resolution, pwmChannel0 );
ledcAttachChannel(motor2Pin1, freq, resolution, pwmChannel1 );
Serial.begin(115200);
Serial.println("Initializing...");
// Inicializar el encoder
// ESP32Encoder::useInternalWeakPullResistors = true;
encoder.attachSingleEdge(PIN_IN1, PIN_IN2);
encoder.clearCount();
}
void loop() {
// Leer la posición actual del encoder
int newPos = encoder.getCount();
// Imprimir la posición del encoder si ha cambiado o cada 5 segundos
unsigned long currentTime = millis();
if (newPos != lastPos || (currentTime - lastPrintTime) >= printInterval) {
Serial.print("Encoder Position: ");
Serial.println(newPos);
lastPos = newPos;
lastPrintTime = currentTime;
}
// Verificar entrada serial para controlar el motor
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
command.trim(); // Elimina espacios en blanco al inicio y al final
int speed = 0;
String action;
if (command.startsWith("FORWARD")) {
speed = command.substring(8).toInt();
action = "FORWARD";
} else if (command.startsWith("BACKWARD")) {
speed = command.substring(9).toInt();
action = "BACKWARD";
} else if (command == "STOP") {
action = "STOP";
} else {
action = "INVALID";
}
switch (action.charAt(0)) {
case 'F': // FORWARD
moveMotorForward(speed);
break;
case 'B': // BACKWARD
moveMotorBackward(speed);
break;
case 'S': // STOP
stopMotor();
break;
default:
Serial.println("Invalid command");
break;
}
}
//delay(10);
}
void moveMotorForward(int speed) {
int dutyCycle = map(speed, 0, 255, 0, 255);
Serial.print("Moving Forward with speed: ");
Serial.println(dutyCycle);
digitalWrite(enable2Pin, HIGH);
digitalWrite(motor2Pin0, HIGH);
digitalWrite(motor2Pin1, LOW);
ledcWrite(pwmChannel0, dutyCycle); // Set the duty cycle to desired speed
ledcWrite(pwmChannel1, 0); // Set the duty cycle to desired speed
}
void moveMotorBackward(int speed) {
int dutyCycle = map(speed, 0, 255, 0, 255);
Serial.print("Moving Backwards with speed: ");
Serial.println(dutyCycle);
digitalWrite(enable2Pin, HIGH);
digitalWrite(motor2Pin0, LOW);
digitalWrite(motor2Pin1, HIGH);
ledcWrite(pwmChannel0, 0); // Set the duty cycle to desired speed
ledcWrite(pwmChannel1, dutyCycle); // Set the duty cycle to desired speed
}
void stopMotor() {
Serial.println("Motor stopped");
digitalWrite(enable2Pin, LOW);
digitalWrite(motor2Pin0, LOW);
digitalWrite(motor2Pin1, LOW);
ledcWrite(pwmChannel0, 0); // Set the duty cycle to desired speed
ledcWrite(pwmChannel1, 0); // Set the duty cycle to desired speed
}
Saca la posición del encoder pero no mueve el motor, está comprobado que le llega corriente y bien cableado. Llevo varias semanas intentando otros códigos pero no consigo resolverlo. Si alguien tiene alguna idea de esto y me pudiera ayudar, estaría realmente agradecido.








