//need the servo and eeprom library, as well as
#include <Servo.h>
#include <EEPROM.h>
#include <LiquidCrystal.h> //for LCD
//Display
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
//define the pins for the sensor:
const int TrigPin = 4;
const int EchoPin = 3;
//servo pin:
const int ServoPin = 10;
//servo object:
Servo servo;
//variables for distance calculation:
int time;
int distance;
// Address in EEPROM to store the threshold distance
int thresholdAddress = 0;
void setup() {
lcd.begin(16, 2); //starts, set size.
lcd.print("Door Sensor");
lcd.setCursor(0, 0);
delay(2000); // Waits for 1000ms = 1 second
lcd.clear(); // Clears after the 1 second.
//do serial monitor for testing:
Serial.begin(9600);
//define I/O pins:
pinMode(EchoPin, INPUT)
}
// 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);
}