#include <Wire.h>
#include <RTClib.h>
#include <ESP32Servo.h> // ใช้ไลบรารี ESP32Servo
RTC_DS3231 rtc; // ใช้สำหรับควบคุม RTC DS3231
Servo feederServo; // ตัวแปรควบคุมเซอร์โว
const int SERVO_PIN = 18; // ขาเชื่อมต่อเซอร์โว
const int FEED_OPEN_POSITION = 90; // ตำแหน่งเปิดให้อาหาร
const int FEED_CLOSE_POSITION = 0; // ตำแหน่งปิด
// เวลาที่ต้องการให้อาหาร (เช่น 6:00, 12:00 และ 18:00)
const int feedHours[] = {15, 15, 15};
const int feedMinutes[] = {38, 39, 40};
void setup() {
// เริ่มต้นการทำงานของ Serial Monitor
Serial.begin(115200);
// เชื่อมต่อเซอร์โว
feederServo.attach(SERVO_PIN, 500, 2400); // กำหนดช่วงสัญญาณ PWM ตั้งแต่ 500 ถึง 2400 ไมโครวินาที
feederServo.write(FEED_CLOSE_POSITION); // ตั้งค่าเริ่มต้นเป็นปิด
// เริ่มต้นการทำงานของ RTC
if (!rtc.begin()) {
Serial.println("ไม่สามารถเริ่มการทำงานของ RTC ได้!");
while (1);
}
// ตั้งค่าเวลาในกรณีที่ RTC ถูกรีเซ็ต
if (rtc.lostPower()) {
rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // ตั้งเวลาเริ่มต้นในกรณี RTC เสียพลังงาน
}
}
void loop() {
DateTime now = rtc.now(); // ดึงเวลาปัจจุบันจาก RTC
// ตรวจสอบเวลาในทุกนาทีว่าตรงกับเวลาที่ต้องการให้อาหารหรือไม่
for (int i = 0; i < sizeof(feedHours) / sizeof(feedHours[0]); i++) {
if (now.hour() == feedHours[i] && now.minute() == feedMinutes[i] && now.second() == 0) {
feedChickens();
delay(60000); // รอ 1 นาที เพื่อป้องกันการให้อาหารซ้ำ
}
}
delay(1000); // ตรวจสอบเวลาใหม่ทุกๆ 1 วินาที
}
void feedChickens() {
Serial.println("กำลังให้อาหารไก่...");
feederServo.write(FEED_OPEN_POSITION); // หมุนเซอร์โวไปที่ตำแหน่งเปิด
delay(1000); // รอให้เซอร์โวหมุนเสร็จ
feederServo.write(FEED_CLOSE_POSITION); // หมุนเซอร์โวกลับไปที่ตำแหน่งปิด
delay(1000); // รอให้เซอร์โวกลับสู่ตำแหน่งปิด
}