#include <Servo.h>
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;
Servo foodServo;
int trigPin = 2; // Ultrasonic sensor trigger pin (connected to digital pin 2)
int echoPin = 3; // Ultrasonic sensor echo pin (connected to digital pin 3)
int buzzerPin = 4; // Buzzer connected to digital pin 4
int ledPin = 13; // Optional LED for visual indication
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
foodServo.attach(9); // Attach servo to pin 9
Wire.begin();
rtc.begin();
// Uncomment the next line and set the RTC time if needed:
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
void loop() {
DateTime now = rtc.now();
// Check for scheduled feeding times (e.g., 8:00 AM and 6:00 PM)
if ((now.hour() == 8 && now.minute() == 0) || (now.hour() == 21 && now.minute() == 03)) {
digitalWrite(buzzerPin, HIGH);
tone(buzzerPin, 1000); // Play a tone of 1000 Hz
digitalWrite(ledPin, HIGH); // Turn on LED
delay(5000); // Buzzer sound for 5 second
digitalWrite(buzzerPin, LOW);
noTone(buzzerPin); // Stop the tone
digitalWrite(ledPin, LOW); // Turn off LED
// Wait for a brief moment to allow the pet to approach
delay(5000); // 5 seconds delay for pet to approach
// Check presence using ultrasonic sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long distance = duration * 0.0343 / 2;
if (distance < 20) { // Adjust the threshold distance as needed
// Dispense food using the servo
foodServo.write(90); // Rotate servo to middle position
delay(1000); // Wait for food to be dispensed
foodServo.write(0); // Return servo to initial position
delay(1000); // Delay before checking again
}
}
// Add a delay to avoid continuous checking
delay(60000); // Check every minute (adjust as needed)
}