#include <Servo>
// Pin definitions
const int trigPin = 17; // HC-SR04 TRIG pin
const int echoPin = 16; // HC-SR04 ECHO pin
const int servoPin = 5; // Servo control pin
// Create servo object
Servo foodServo;
// Setup variables
long duration;
int distance;
const int waterLevelThreshold = 30; // Threshold for feeding in cm
void setup() {
Serial.begin(115200);
// Initialize sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize servo
foodServo.attach(servoPin);
foodServo.write(0); // Ensure servo is at initial position
Serial.println("Setup complete");
}
void loop() {
// Measure water level
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.0344 / 2;
// Print distance to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if water level is below threshold
if (distance < waterLevelThreshold) {
// Activate servo to dispense food
foodServo.write(90); // Rotate servo to dispense food
delay(2000); // Wait for 2 seconds
foodServo.write(0); // Return servo to initial position
delay(5000); // Wait for 5 seconds before checking again
}
delay(60000); // Wait for 1 minute before the next measurement
}