// ENEL 301 Lab 2
// Includes
#include <LiquidCrystal.h>
#include <Servo.h>
#include <EEPROM.h>
// LCD setup
LiquidCrystal lcd(13,12, 11, 10, 9, 8);
// Threshold distance for the door opener
double thresholdDistance; // (cm)
// The state of the door
bool isOpen = false;
// Defining the Servo variable
Servo myServo;
// Opens the door
void openDoor() {
isOpen = true;
myServo.write(180);
delay(1000);
}
// Closes the door
void closeDoor() {
isOpen = false;
myServo.write(0);
delay(1000);
}
// Updates the LCD display
void updateLCD(double distance) {
lcd.setCursor(0,0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" ");
lcd.setCursor(0,1);
if(isOpen) {lcd.print("Open ");}
else {lcd.print("Closed");}
}
// Returns the distance currently being read by the HDS
double getDistance() {
// Sends pulse
digitalWrite(23, HIGH);
delayMicroseconds(10);
digitalWrite(23, LOW);
// Receives pulse
double duration = pulseIn(25, HIGH);
// Calulates distance
double distance = 0.0344 * duration / 2;
return distance;
}
// Enters a mode so that the threshold value can be set
void setupMode() {
// Waits for the button to be released
while (true) {
int buttonState = digitalRead(53);
if (buttonState == 1) {
break;
}
}
// Prints data to the LCD
lcd.clear();
lcd.print("SETUP MODE");
lcd.setCursor(0,1);
lcd.print("DISTANCE: ");
// Reads the distance while the button has not been pressed
while(true) {
delay(100);
lcd.setCursor(10,1);
lcd.print(getDistance());
lcd.print(" ");
// If the button is pressed, then set the thresholdDistance and exit the loop
int buttonState = digitalRead(53);
if (buttonState == 0) {
thresholdDistance = getDistance();
EEPROM.write(0, thresholdDistance);
break;
}
}
// Displays the new thresholdDistance
lcd.clear();
lcd.print("NEW THRESHOLD");
lcd.setCursor(0,1);
lcd.print(thresholdDistance);
delay(2000);
return;
}
void setup() {
Serial.begin(9600);
// LCD Setup
lcd.begin(16,2);
// Distance Sensor Pin Setup
pinMode(23, OUTPUT);
pinMode(25, INPUT);
// Button
pinMode(53, INPUT_PULLUP);
// Servo
myServo.attach(7);
// Reading thresholdDistance from the EEPROM
thresholdDistance = EEPROM.read(0);
// Setting the inital value of the
}
void loop() {
delay(100); // Delay to reduce flashing on the LCD
// Gets the current distance
double distance = getDistance();
// If the button is pressed, enter setup mode
int buttonState = digitalRead(53);
if(buttonState == 0) {setupMode();}
// If the thresholdDistance is crossed, then the door will open or close
if (distance < thresholdDistance & isOpen == false) {openDoor();}
else if (distance > thresholdDistance & isOpen == true) {closeDoor();}
updateLCD(distance);
}