#include <LiquidCrystal.h>
#include <Servo.h>
#include <EEPROM.h>
Servo doorServo;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
const int trigPin = 2;
const int echoPin = 3;
int thresholdDistance = 30;
int doorState = 0;
int getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
int duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034 / 2;
return distance;
}
void openDoor() {
doorServo.write(180);
doorState = 1;
}
void closeDoor() {
doorServo.write(0);
doorState = 0;
}
void setup() {
doorServo.attach(44);
lcd.begin(16, 2);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
thresholdDistance = EEPROM.read(0); // Read from address 0
Serial.begin(9600);
Serial.print("Initial Threshold Distance: ");
Serial.println(thresholdDistance); //prints variable.
}
void loop() {
if (Serial.available() > 0) {
String input = Serial.readStringUntil('\n');
int newThreshold = input.toInt(); //have to turn into integer.
if (newThreshold >= 0 && newThreshold <= 255) {
thresholdDistance = newThreshold;
Serial.print("New Threshold Distance: ");
Serial.println(thresholdDistance);
EEPROM.write(0, thresholdDistance); // Store the new threshold distance in EEPROM
}
}
int distance = getDistance();
//code to show distance on the screen. only used for testing.
// Serial.print("Distance: ");
// Serial.print(distance);
// Serial.println(" cm");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Door: ");
lcd.print(doorState == 1 ? "Open" : "Closed");
lcd.setCursor(0, 1);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
if (distance < thresholdDistance && doorState == 0) {
openDoor();
} else if (distance >= thresholdDistance && doorState == 1) {
closeDoor();
}
delay(100);
}