#include <Servo.h>
#include <LiquidCrystal.h>
#include <EEPROM.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
Servo MyServo;
// Declaring variables
uint8_t trigPin = A1;
uint8_t echoPin = A0;
uint8_t servoPin = A2;
int distance;
int threshold = EEPROM.read(0); // reads the 0 index threshold
int duration;
bool open = false;
void setup() {
lcd.begin(16, 2);
Serial.begin(9600);
Serial.print("Current threshold distance is " + String(threshold) + "cm\n");
Serial.print("Enter desired threshold activation distance in centimeters\n");
Serial.print("Interger numbers only, type in the value and hit enter\n");
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
MyServo.attach(servoPin); // Set up the servo motor
MyServo.write(0);
delay(1000);
}
void loop() {
digitalWrite(trigPin, LOW); //Ultrasonic trigger pin set up
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); //Echo pin set up
distance = (duration * 0.0343) / 2; // conversion of time to distance
lcd.clear();
if (distance > 0) // prints distance in real time
lcd.print("Distance: " + String(distance) + " cm");
if (distance <= 0)// distance only 0 when nothing is sensed, no value should be displayed
lcd.print("Distance: N/A");
lcd.setCursor(0, 1);
if (distance <= threshold) {
lcd.print("Open");
if (open == false) {
open = true;
MyServo.write(180);// Move the servo to 180 degrees
delay(1000);// time to let motor "open"
}
}
else {
MyServo.write(0);
lcd.setCursor(0, 1);
lcd.print("Closed");
open = false;
}
if (Serial.available() > 0) {//checks for any input from the serial monitor
threshold = Serial.readStringUntil('\n').toInt();// \n is the delimiter
EEPROM.write(0, threshold);
Serial.print("Threshold value updated to: " + String(threshold)+ "cm\n");
}
delay(150);
}