🐶 Smart Pet Feeder (Serial Controlled Version)
📌 Components Required
-
ESP32
-
SG90 Servo Motor
-
External 5V Supply (recommended)
-
Connecting Wires
-
Pet food container (mechanical gate)
🔌 Circuit Connection
Servo → ESP32
| Servo Wire | Connect To |
|---|---|
| Red (VCC) | 5V External Supply |
| Brown/Black (GND) | ESP32 GND |
| Orange/Yellow (Signal) | GPIO 18 |
⚠ IMPORTANT:
Connect External 5V GND and ESP32 GND together
(Common ground is mandatory)
💻 Complete ESP32 Code
Copy and paste in Arduino IDE:
#include <ESP32Servo.h>
Servo feederServo;
const int servoPin = 18;
int gateState = 0; // 0 = Closed, 1 = Open
void setup() {
Serial.begin(115200);
feederServo.attach(servoPin);
feederServo.write(0); // Start with gate closed
Serial.println("=== Smart Pet Feeder ===");
Serial.println("Type:");
Serial.println("OPEN - To open food gate");
Serial.println("CLOSE - To close food gate");
Serial.println("--------------------------");
}
void loop() {
if (Serial.available()) {
String command = Serial.readStringUntil('\n');
command.trim(); // Remove extra spaces
if (command.equalsIgnoreCase("OPEN")) {
openGate();
}
else if (command.equalsIgnoreCase("CLOSE")) {
closeGate();
}
else {
Serial.println("Invalid Command! Type OPEN or CLOSE");
}
}
}
void openGate() {
feederServo.write(90); // Rotate to 90 degree
gateState = 1;
Serial.println("Food Gate is OPEN");
}
void closeGate() {
feederServo.write(0); // Rotate back to 0 degree
gateState = 0;
Serial.println("Food Gate is CLOSED");
}
🧠 How It Works (Step-by-Step)
1️⃣ Include Library
This library allows ESP32 to control servo motors properly.
2️⃣ Create Servo Object
This creates a servo control object.
3️⃣ Define Servo Pin
Servo signal wire connected to GPIO 18.
4️⃣ Setup Function
Starts serial communication.
Attach servo to pin 18.
Start with gate closed.
5️⃣ Reading Serial Commands
Checks if user typed something in Serial Monitor.
Reads command until Enter is pressed.
6️⃣ Command Conditions
If user types:
-
OPEN → Gate opens (90°)
-
CLOSE → Gate closes (0°)
If wrong command → Error message shown.
📟 How to Use
-
Upload code to ESP32
-
Open Serial Monitor
-
Set baud rate to 115200
-
Set “New Line” in Serial Monitor
-
Type:
OPEN→ Gate opens
-
Type:
CLOSE→ Gate closes
📊 Output Example in Serial Monitor
Type:
OPEN – To open food gate
CLOSE – To close food gate
————————–
OPEN
Food Gate is OPEN
CLOSE
Food Gate is CLOSED
🎯 What Students Learn from This Version
-
Serial Communication
-
String handling
-
Conditional statements
-
Servo angle control
-
Function creation
-
Modular programming
🚀 Optional Upgrade (Automatic Close After Feeding)
If you want:
-
Gate opens
-
Waits 5 seconds
-
Closes automatically
I can give upgraded code.