#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h>
#include <ESP32Servo.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
RTC_DS1307 rtc;
// uint8_t set_Sec = 0;
// uint8_t set_Minute = 47;
// uint8_t set_Hour = 13;
// uint8_t set_Day = 11;
// uint8_t set_Month = 9;
// uint16_t set_Year = 2024;
Servo myservo;
int servoPin = 13;
int pushButtonPin = 25;
int angle = 0;
bool doorOpen = false;
DateTime doorOpenedTime;
unsigned long doorOpenTimestamp = 0;
void setup(void) {
Serial.begin(115200);
// lcd.init();
// lcd.backlight();
// if (!rtc.begin()) { // Initialize the RTC
// Serial.println("Couldn't find RTC");
// while (1); // Stop the program if the RTC is not found
// }
// if (!rtc.isrunning()) { // Check if the RTC is running
// Serial.println("RTC is NOT running, setting the time!");
// rtc.adjust(DateTime(set_Year, set_Month, set_Day, set_Hour, set_Minute, set_Sec)); // Set the time
// }
// delay(1000); /* Wait for 1000ms */
myservo.attach (servoPin);
pinMode(pushButtonPin,INPUT_PULLUP);
Serial.println("opening and closing the door");
}
void loop(void) {
// date_time();
DateTime currenttime = rtc.now();
door_control(currenttime);
}
// void date_time(){
// DateTime now = rtc.now(); // Get the current time from the RTC
// lcd.setCursor(0, 0); // Reset the cursor to the first row
// lcd.print("Time: ");
// lcd.print(now.hour());
// lcd.print(":");
// lcd.print(now.minute());
// lcd.print(":");
// lcd.print(now.second());
// // Update the date on the second row
// lcd.setCursor(0, 1);
// lcd.print("Date: ");
// lcd.print(now.day());
// lcd.print(".");
// lcd.print(now.month());
// lcd.print(".");
// lcd.print(now.year());
// delay(1000); // Wait for 1 second before refreshing the display
// }
// void door_control(){
// while(digitalRead(pushButtonPin) == LOW){
// // // change the angle for next time through the loop:
// // angle = angle + 90;
// // // reverse the direction of the moving at the ends of the angle:
// // if (angle <= 0 || angle >= 180) {
// // angleStep = -angleStep;
// // }
// // myservo.write(angle); // move the servo to desired angle
// // Serial.print("Moved to: ");
// // Serial.print(angle); // print the angle
// // Serial.println(" degree");
// // delay(100); // waits for the servo to get there
// }// while
// }
void open_door(){
angle = 90;
myservo.write(angle);
doorOpenedTime = rtc.now();
doorOpenTimestamp = millis();
}
void close_door(){
angle = 0;
myservo.write(angle);
}
void door_control(DateTime currenttime) {
unsigned long currentMillis = millis();
unsigned long elapsedMillis = currentMillis - doorOpenTimestamp;
if (digitalRead(pushButtonPin) == LOW) { // If the button is pressed
open_door();
} else if (elapsedMillis >= 600000) { // 600000 milliseconds = 600 seconds = 10 minutes
close_door();
}
}