#include <ESP32Servo.h>
#define SERVO_PIN 12
#define MOTOR_PIN 13
#define LED_PIN 14
#define TRIGGER_PIN 15
#define ECHO_PIN 16
Servo servoMotor;
void setup() {
pinMode(MOTOR_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
servoMotor.attach(SERVO_PIN);
// Inicialmente, desactivamos el motor, el LED y colocamos el servo en 0 grados
digitalWrite(MOTOR_PIN, LOW);
digitalWrite(LED_PIN, LOW);
servoMotor.write(0);
}
void loop() {
long duration, distance;
// Generamos un pulso de 10 microsegundos en el pin TRIGGER_PIN
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Medimos el tiempo de respuesta del pin ECHO_PIN
duration = pulseIn(ECHO_PIN, HIGH);
// Calculamos la distancia en centímetros
distance = duration * 0.034 / 2;
// Si la distancia es menor a 20 cm, activamos el servo y desactivamos el motor y el LED
if (distance < 20) {
servoMotor.write(0); // Regresamos el servo a 0 grados
digitalWrite(MOTOR_PIN, LOW); // Desactivamos el motor
digitalWrite(LED_PIN, LOW); // Apagamos el LED
} else {
// Si la distancia es mayor a 20 cm, activamos el motor y el LED
digitalWrite(MOTOR_PIN, HIGH); // Activamos el motor
digitalWrite(LED_PIN, HIGH); // Encendemos el LED
}
delay(100); // Esperamos un poco para la próxima lectura del sensor
}