#include <Servo.h>
#define TRIG_PIN 10
#define ECHO_PIN 11
#define SERVO_PIN 9
#define BUZZER_PIN 8
#define LED_PIN 7
Servo servoMotor;
int distance;
int previousDistance = 0;
bool doorOpen = false;
int threshold = 20; // Adjust this value according to your needs
void setup() {
Serial.begin(9600);
servoMotor.attach(SERVO_PIN);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// Measure distance using ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
distance = pulseIn(ECHO_PIN, HIGH) * 0.034 / 2; // Calculate distance in cm
Serial.print("Distance: ");
Serial.println(distance);
// Check if the door needs to be opened or closed
if (distance < threshold && !doorOpen) {
openDoor();
beep();
flashLED();
} else if (distance >= threshold && doorOpen) {
closeDoor();
}
delay(100); // Adjust delay according to your needs
}
void openDoor() {
// Open the door
servoMotor.write(90); // Assuming 90 degrees is the open position
doorOpen = true;
Serial.println("Door opened");
}
void closeDoor() {
// Close the door
servoMotor.write(0); // Assuming 0 degrees is the closed position
doorOpen = false;
Serial.println("Door closed");
}
void beep() {
// Activate the buzzer
tone(BUZZER_PIN, 1000); // Adjust frequency as needed
delay(1000); // Adjust duration as needed
noTone(BUZZER_PIN);
}
void flashLED() {
// Flash the LED
digitalWrite(LED_PIN, HIGH);
delay(1000); // Adjust duration as needed
digitalWrite(LED_PIN, LOW);
}