#include <ESP32Servo.h>
Servo servoMotor; // Objeto para controlar un servo
// Servo
int pinServo = 18; // Pin GPIO conectado al servo
int anguloCentral = 0; // Ángulo inicial para el servo
//Motor
int pinMotor1A = 27; // IN1 en el L298
int pinMotor1B = 26; // IN2 en el L298
int pinHabilitarMotor1 = 25; // ENA en el L298
//Variables char = variable escrita adaptables a matematicas (comando -1)
// bool = variable que puede ser verdadera o falsa
char comando;
bool acelerar = false;
void setup() {
servoMotor.attach(pinServo);
servoMotor.write(anguloCentral); // Posicionar el servo en el centro
// Configurar pines del motor como salidas
pinMode(pinMotor1A, OUTPUT);
pinMode(pinMotor1B, OUTPUT);
pinMode(pinHabilitarMotor1, OUTPUT);
// Iniciar la comunicación Bluetooth
Serial2.begin(9600, SERIAL_8N1, 16, 17); // Nombre del dispositivo Bluetooth
Serial.begin(115200); // Iniciar la comunicación Serial
Serial.println("Listo para conectar por Bluetooth");
}
void loop() {
if (Serial2.available()) { // Verificar si hay datos por Bluetooth
comando = Serial2.read(); // Leer el comando recibido
Serial.print("Comando: ");
Serial.println(comando);
//Definir el estado y el sentido del giro
if (comando == 'A' || comando == 'a') {
digitalWrite(pinMotor1A, HIGH);
digitalWrite(pinMotor1B, LOW);
acelerar = true;
} else if (comando == 'C' || comando == 'c') {
digitalWrite(pinMotor1A, LOW);
digitalWrite(pinMotor1B, HIGH);
acelerar = true;
} else if (comando == 'H' || comando == 'h') {
digitalWrite(pinMotor1A, LOW);
digitalWrite(pinMotor1B, LOW);
acelerar = false;
}
//Activar el motor
if (acelerar) {
analogWrite(pinHabilitarMotor1, 255); // Velocidad máxima
} else {
analogWrite(pinHabilitarMotor1, 0); // Motor apagado
}
//Servo shananigans
if (comando == 'D' || comando == 'd') {
servoMotor.write(anguloCentral - 25);
} else if (comando == 'B' || comando == 'b') {
servoMotor.write(anguloCentral + 25);
} else if (comando == 0 || comando == 'E' || comando == 'e') {
servoMotor.write(anguloCentral);
}
}
}