#include <Servo.h>
#include <TimeLib.h> // Include the Time library
#define TRIGGER_PIN 10
#define ECHO_PIN 11
#define SERVO_PIN 9
#define BUZZER_PIN 5
#define LED_PIN 6
#define POTENTIOMETER_PIN A0
Servo servoMotor;
// Variables for the distance measurement
long duration;
int distance;
// Feeding schedule
int feedTimes[3] = {8, 14, 20}; // Feeding hours (8 AM, 2 PM, 8 PM)
int feedCount = 0;
void setup() {
Serial.begin(9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
servoMotor.attach(SERVO_PIN);
servoMotor.write(0);
// Set the initial time (adjust as needed)
setTime(7, 0, 0, 5, 22, 2024); // Set time to 07:00:00 on 01 Jan 2021
}
void loop() {
// Get the current time
int currentHour = hour();
// Calculate the distance to an object
distance = getDistance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if it's time to feed the pet
if (distance > 2 && distance < 10 && isFeedTime(currentHour)) {
feedPet();
feedCount++;
// Wait until the next feed time
delay(3600000); // Delay for 1 hour
}
// Check food storage level and trigger alarm if low
int foodLevel = analogRead(POTENTIOMETER_PIN);
if (foodLevel < 100) {
triggerAlarm();
} else {
noAlarm();
}
delay(100); // Adds a short delay to prevent too frequent readings
}
int getDistance() {
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2;
return distance;
}
void feedPet() {
servoMotor.write(90);
delay(1000);
servoMotor.write(0);
delay(500);
}
void triggerAlarm() {
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
}
void noAlarm() {
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(LED_PIN, LOW);
}
bool isFeedTime(int currentHour) {
for (int i = 0; i < 3; i++) {
if (currentHour == feedTimes[i] && feedCount == i) {
return true;
}
}
return false;
}