// January 25th, 2024
//libraries for LCD screen
#include <LiquidCrystal.h>
//servo library
#include <Servo.h>
//EEPROM library
#include <EEPROM.h>
Servo door;
//LCD setup -- pins
const int rs=12, en=11, d4=5, d5=4, d6=3, d7=2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
//serial monitor
//Serial.readStringUntil(delimiter)
// example if we want delimiter to be enter, then we need to
//set the delimiter to be newline char so that when
//user presses enter it saves the entered value in the serial
//EEPROM
//need to store user entered thresshold value using write
//pins for trig and echo
const int trig = 9;
const int echo = 8;
//variable setups for ultrasonic sensor
float duration, distance;
const int door_pin = 19;
int threshold;
int state;
void setup() {
//trig pin
pinMode(trig, OUTPUT);
//echo pin
pinMode(echo, INPUT);
door.attach(door_pin);
Serial.begin(9600);
Serial.println("hello world");
lcd.begin(16,2); //setup of lcd with rows, cols of screensize
//reruns each power cycle
//use eeprom read in setup so it only runs when power is lost/regained
//eprom read should not be used in loop (slows program)
//reading previous value stored for the threshold value
threshold = EEPROM.read(0);
}
void loop() {
//writing value from serial into memory, if a user enters something into the serial
if (Serial.available() > 0){
//reads integer from serial
String entered = Serial.readStringUntil('\n');
int thresh2 = entered.toInt();
EEPROM.write(0, thresh2);
Serial.println(thresh2);
threshold = thresh2;
}
//trig pin starts on low for 2 us
digitalWrite(trig, LOW);
delayMicroseconds(2);
//then we set it to high for 10 us, so that it will then send a burst
digitalWrite(trig, HIGH);
delayMicroseconds(10);
//now we are awaiting a pulse back, so we can read the duration
duration = pulseIn(echo, HIGH); //reads how long echo is high aka how long until the pulse returns
// vsound = 0.034cm/μs
//calculate distance
float v = 0.034;
distance = (duration * v)/2;
lcd.setCursor(0,0);
lcd.print("Distance: ");
lcd.print(distance);
if (distance < threshold){
door.write(180);
lcd.setCursor(0,1);
lcd.print("State: Open");
}
else{
door.write(0);
lcd.setCursor(0,1);
lcd.print("State: Closed");
}
delay(100);
}