#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// LCD module configuration
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Ultrasonic sensor 1 pins
const int trigPin1 = 12;
const int echoPin1 = 13;
// Ultrasonic sensor 2 pins
const int trigPin2 = 10;
const int echoPin2 = 11;
// Buzzer pin
const int buzzerPin = 5;
// Servo motor pin
const int servoPin = 9;
Servo servoMotor;
// LED pin
const int ledPin = 4;
// Feeding parameters
const int distanceThresholdServo = 100; // Distance threshold for servo control in cm
const int distanceThresholdLCD = 20; // Distance threshold for LCD display in cm
const int servoOpenAngle = 90; // Angle to open the feeding mechanism
const int servoClosedAngle = 0; // Angle to close the feeding mechanism
const int feedingDuration = 2000; // Duration for which the feeding mechanism stays open in milliseconds
// Variables to store previous distance values
int previousDistance1 = 0;
void setup() {
// Initialize LCD
lcd.init(); // initialize the lcd
lcd.backlight(); // open the backlight
// Initialize ultrasonic sensor 1 pins
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
// Initialize ultrasonic sensor 2 pins
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
// Initialize buzzer pin
pinMode(buzzerPin, OUTPUT);
// Initialize servo motor
servoMotor.attach(servoPin);
// Initialize LED pin
pinMode(ledPin, OUTPUT);
// Print initial message on LCD
lcd.setCursor(0, 0);
lcd.print("Smart Feeder");
}
void loop() {
// Measure distance using ultrasonic sensor 1
long duration1, distance1;
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
duration1 = pulseIn(echoPin1, HIGH);
distance1 = (duration1 / 2) / 29.1;
// Update LCD with distance from ultrasonic sensor 1 if it has changed
if (distance1 != previousDistance1) {
updateLCD(distance1);
previousDistance1 = distance1;
}
// Check if distance is less than the threshold and activate the buzzer
if (distance1 <= distanceThresholdLCD) {
activateBuzzer();
} else {
deactivateBuzzer();
}
// Measure distance using ultrasonic sensor 2
long duration2, distance2;
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration2 = pulseIn(echoPin2, HIGH);
distance2 = (duration2 / 2) / 29.1;
// Check if feeding is required for servo control
if (distance2 <= distanceThresholdServo) {
feed();
}
}
void updateLCD(int distance) {
// Clear LCD and print distance value
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
}
void activateBuzzer() {
digitalWrite(buzzerPin, HIGH);
}
void deactivateBuzzer() {
digitalWrite(buzzerPin, LOW);
}
void feed() {
// Activate the feeding mechanism
servoMotor.write(servoOpenAngle);
digitalWrite(ledPin, HIGH);
// Wait for the feeding duration
delay(feedingDuration);
// Deactivate the feeding mechanism
servoMotor.write(servoClosedAngle);
digitalWrite(ledPin, LOW);
}