#include <Servo.h>
#include <EEPROM.h>
// Define pins for ultrasonic sensor
const int trigPin = 10;
const int echoPin = 11;
// Define pin for servo
const int servoPin = 9;
// Define variables for distance measurement
long duration;
int distance;
// Create a servo object
Servo myServo;
// Address in EEPROM to store the threshold distance
int thresholdAddress = 0;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Define the pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(servoPin, OUTPUT);
// Attach the servo to the corresponding pin
myServo.attach(servoPin);
// Read threshold distance from EEPROM
int storedThreshold = EEPROM.read(thresholdAddress);
if (storedThreshold >= 0 && storedThreshold <= 255) {
Serial.print("Threshold read from EEPROM: ");
Serial.println(storedThreshold);
} else {
Serial.println("Invalid threshold value in EEPROM. Using default value.");
storedThreshold = 50; // Default threshold value
}
}
void loop() {
// Generate a pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse from the ultrasonic sensor
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if an object is detected within 50 centimeters
if (distance < 50) {
// Rotate the servo to 90 degrees
myServo.write(180);
Serial.println("OPEN");
// Wait for 5 seconds
delay(5000);
// Measure the distance again
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Check if the object is still there
if (distance < 50) {
// Keep the servo at 180 degrees
myServo.write(180);
Serial.println("OPEN");
} else {
// Return the servo to the initial position
myServo.write(0);
Serial.println("CLOSED");
}
} else {
// Return the servo to the initial position
myServo.write(0);
Serial.println("CLOSED");
}
// Check if data is available in the serial buffer
while (Serial.available() > 0) {
// Read the entered character
char input = Serial.read();
// Check if the Enter key is pressed
if (input == '\n' || input == 's') {
Serial.println("Serial monitor stopped.");
return; // Exit the loop and stop further readings
}
}
// Wait for some time before measuring the distance again
delay(500);
}