//*********************************
#include <ESP32Servo.h>
const int PinTrigger = 5;
const int PinEcho = 4;
int const PinServo = 18;
int const PinPotenciometro = 34;
int PotVal = 0 ;
int angulo = 0 ;
int tiempoObjeto = 0;
int distanciaObjeto = 0;
Servo Servo1;
void setup()
{
Servo1.attach(PinServo, 500, 2500);
pinMode(PinTrigger, OUTPUT); // Sets the trigPin as an Output
pinMode(PinEcho, INPUT); // Sets the echoPin as an Input
Serial.begin(9600);
}
void loop()
{
leerSensores();
realizarCalculos();
realizarAcciones();
mostrarLogs();
}
long leerSensorUltrasonido()
{
//Desactivo el trigger
digitalWrite(PinTrigger, LOW);
delayMicroseconds(2);
//Activo el Trigger por 10 microsegundos
digitalWrite(PinTrigger, HIGH);
delayMicroseconds(10);
//Desactivo el trigger
digitalWrite(PinTrigger, LOW);
//Leo el pin de Echo, y retorno el tiempo en
//microsegundos en donde se encuentra el objeto
return pulseIn(PinEcho, HIGH);
}
void leerSensores()
{
// leo el valor sensado por el potenciometro
PotVal = analogRead(PinPotenciometro);
//leo el valor sensado por el ultrasonido
tiempoObjeto = leerSensorUltrasonido();
}
void realizarCalculos()
{
//segun el valor del poteniometro calculo el valor del angulo
angulo=map(PotVal,0,4096,0,180);
//calculo la distancia del objeto aplicando la formula
//de la velocidad del sonido
distanciaObjeto=0.01723*tiempoObjeto;
}
void realizarAcciones()
{
//muevo el servo según el angulo calculado
Servo1.write(angulo);
}
void mostrarLogs()
{
Serial.print("PotVal:");
Serial.print(PotVal);
Serial.print(" angulo:");
Serial.print(angulo);
Serial.print(" Distancia: ");
Serial.print(distanciaObjeto);
Serial.print("cm");
Serial.println ();
}