#include <Servo.h>
// Definición de pines
const int pirPin = 2; // Pin del sensor PIR
const int relay1Pin = 11; // Pin del relé para el LED
const int relay2Pin = 9; // Pin del relé para el servomotor
const int servoPin = 10; // Pin del servomotor
// Variables de tiempo
const unsigned long ledDuration = 5000; // Duración del LED en milisegundos (2.3 segundos)
const unsigned long relay2Delay = 1000; // Retraso para el segundo relé (1 segundo)
const unsigned long relay2Duration = 5000; // Duración del servomotor en milisegundos (3 segundos)
const unsigned long returnDelay = 2000; // Tiempo para que el servomotor regrese a la posición inicial (5 segundos)
// Crear un objeto Servo
Servo myServo;
void setup() {
// Configurar pines
pinMode(pirPin, INPUT);
pinMode(relay1Pin, OUTPUT);
pinMode(relay2Pin, OUTPUT);
myServo.attach(servoPin);
// Asegurarse de que todo esté apagado inicialmente
digitalWrite(relay1Pin, LOW);
digitalWrite(relay2Pin, LOW);
}
void loop() {
// Leer el estado del sensor PIR
int pirState = digitalRead(pirPin);
if (pirState == HIGH) { // Si el PIR detecta movimiento
// Enciende el LED verde a través del relé
digitalWrite(relay1Pin, HIGH);
delay(ledDuration); // Mantiene el LED encendido durante 2.3 segundos
// Apaga el LED verde
digitalWrite(relay1Pin, LOW);
// Espera 1 segundo antes de activar el servomotor
delay(relay2Delay);
// Activa el segundo relé para encender el servomotor
digitalWrite(relay2Pin, HIGH);
myServo.write(0); // Girar el servomotor hacia la izquierda (0 grados)
delay(relay2Duration); // Mantiene el servomotor girado durante 3 segundos
// Después de 3 segundos, el servomotor regresa a la posición inicial después de 5 segundos
digitalWrite(relay2Pin, LOW);
delay(returnDelay); // Espera 5 segundos antes de mover el servomotor de regreso
// Regresar el servomotor a la posición inicial (90 grados)
digitalWrite(relay2Pin, HIGH);
myServo.write(90); // Regresar el servomotor a la posición inicial (90 grados)
delay(1000); // Mantener el servomotor en la posición inicial durante 2 segundos
digitalWrite(relay2Pin, LOW);
// Espera antes de volver a verificar el sensor PIR
delay(2000); // Espera 2 segundos antes de volver a comprobar el sensor PIR
}
}