#include <Servo.h>
const int trigPin = D23;
const int echoPin = D21;
const int relayPin = D2;
const int pirPin = D6;
const int servoPin = D5;
Servo servo;
long duration;
int distance;
boolean motionDetected = false;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
pinMode(pirPin, INPUT);
servo.attach(servoPin); // Attach the servo to the correct pin
servo.write(0); // Initialize servo at 0 degrees
Serial.begin(9600);
}
void loop() {
// Ultrasonic sensor distance measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin3, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// PIR sensor input
motionDetected = digitalRead(pirPin);
if (distance < 200)
{
servo.write(90); // Move the servo to 90 degrees
digitalWrite(relayPin, HIGH); // Turn on the relay
}
else if (motionDetected == HIGH)
{ // Assuming HIGH indicates motion detected
digitalWrite(relayPin, HIGH); // Turn on the relay
}
else
{
servo.write(0); // Move the servo back to 0 degrees
digitalWrite(relayPin, LOW); // Turn off the relay
}
delay(2000);
}