#include <Wire.h>
#include <RTClib.h>
#include <Servo.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
RTC_DS3231 rtc;
Servo servo_test;
LiquidCrystal_I2C lcd(0x27, 16, 2);
boolean feed = true;
boolean settingTime = false; // Flag to indicate if setting feeding time
char key;
int r[6];
int t1, t2, t3, t4, t5, t6;
// Define the Keypad
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {2, 3, 4, 5};
byte colPins[COLS] = {6, 7, 8, 9};
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
servo_test.attach(10); // Connect the servo signal pin to digital pin 10
Wire.begin();
rtc.begin();
lcd.begin(16, 2);
lcd.backlight();
}
void loop() {
lcd.clear();
lcd.setCursor(0, 0);
char key = kpd.getKey();
if (key == 'A') {
settingTime = true;
}
if (settingTime) {
setFeedingTime();
}
DateTime now = rtc.now();
t1 = now.hour();
t2 = now.minute();
t3 = now.second();
t4 = now.year();
t5 = now.month();
t6 = now.day();
// Display current time
lcd.print("Time: ");
lcd.print(t1 < 10 ? "0" : "");
lcd.print(t1);
lcd.print(":");
lcd.print(t2 < 10 ? "0" : "");
lcd.print(t2);
lcd.print(":");
lcd.print(t3 < 10 ? "0" : "");
lcd.print(t3);
lcd.setCursor(0, 1);
lcd.print("Date: ");
lcd.print(t4, DEC);
lcd.print('/');
lcd.print(t5, DEC);
lcd.print('/');
lcd.print(t6, DEC);
// Check if current time matches set feeding time
if (t1 == r[0] && t2 == r[1] && t3 == r[2] && feed == true) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Dispensing Now");
delay(3000);
lcd.clear();
servo_test.write(100); // Command to rotate the servo to the specified angle
delay(400);
servo_test.write(55);
feed = false;
}
delay(1000);
}
void setFeedingTime() {
feed = true;
int i = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Set feeding Time");
lcd.setCursor(0, 1);
lcd.print("HH:MM");
char j = 0;
while (1) {
key = kpd.getKey();
if (key != NO_KEY) {
lcd.setCursor(j, 1);
lcd.print(key);
r[i] = key - 48;
i++;
j++;
if (j == 2) {
lcd.print(":");
j++;
}
delay(500);
}
if (key == 'D') {
key = 0;
settingTime = false; // Exit setting mode
displayConfirmation();
break;
} else if (key == 'C') {
cancelFeedingTime();
key = 0;
settingTime = false; // Exit setting mode
break;
}
}
}
void cancelFeedingTime() {
feed = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Feeding Time");
lcd.setCursor(0, 1);
lcd.print("Setting Canceled");
delay(2000); // Display the message for 2 seconds
lcd.clear();
}
void displayConfirmation() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Feeding Time Set!");
lcd.setCursor(0, 1);
lcd.print("Tap A to change");
delay(5000); // Display the confirmation for 3 seconds
lcd.clear();
}