ESP32 Smart Pet Feeder with Load Cell, Servo, OLED & Web Schedule

Build an ESP32 smart pet feeder that serves up to four scheduled meals, weighs every portion with a load cell, shows the bowl weight on an OLED and lets you feed or change the schedule from your phone.

  • DifficultyAdvanced
  • Build time5–7 hours
  • Board / MCUESP32 DevKit V1
  • Parts13 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 smart pet feeder feeds your dog or cat on time even when nobody is home. A servo opens a gate under a kibble hopper, and the bowl sits on a load cell, so the ESP32 keeps the gate open until the bowl has gained exactly the grams you asked for. You get up to four meals a day, a small OLED that shows the bowl weight and the next meal, a chime that calls your pet, and a phone web page to change the schedule or press Feed now.

It is a big combination project: Wi-Fi and NTP time, a weighing scale, a motor, a display and a web app all running on one board. Because it measures food by weight instead of by servo time, every portion is the same size no matter how full the hopper is, and it can tell you when the hopper is empty or jammed.

ESP32 smart pet feeder with servo-driven kibble hopper, bowl on a load cell with HX711, OLED display, buzzer, button and a phone showing the meal schedule web page

How It Works

  • Keeping time: after joining your Wi-Fi the ESP32 gets the time from an NTP server and sets it to Indian Standard Time (UTC+5:30). The internal clock keeps running if Wi-Fi drops later.
  • Weighing the bowl: the load cell bends very slightly under the bowl and its four strain gauges change resistance. The HX711 is a 24-bit amplifier and converter that turns this tiny change into a number. The code averages five readings and divides by a calibration factor to get grams. At power-on the empty bowl is tared to 0 g.
  • Closed-loop portions: at meal time the buzzer chimes twice, the servo swings the gate to 80°, and the ESP32 reads the bowl about 10 times a second. As soon as the bowl has gained the set grams (minus 2 g for kibble still falling), the gate closes. A 15 second timeout and a 400 g bowl limit stop it from ever overfilling.
  • Jam and empty hopper alarm: while the gate is open it wiggles by 15° every 2 seconds to break up stuck kibble. If less than 30 percent of the portion arrives, the OLED shows CHECK HOPPER / JAM, the web page turns red and the buzzer beeps every 30 seconds until you press the button.
  • Schedule in flash: the four meal slots (on/off, time and grams) are saved with the ESP32 Preferences library, so a power cut does not erase them. Each meal fires once per day.
  • Web app: open the IP address or http://petfeeder.local on a phone on the same Wi-Fi. The page shows the live bowl weight, next meal and last feed, and has Feed now, Tare scale and a schedule form.
  • Button: a short press feeds one portion (the size of meal 1) and clears the alarm. Holding it for 3 seconds tares the scale; do this with the empty bowl in place.

Components Required

  • ESP32 DevKit V1 (30-pin) – 1
  • MG996R metal-gear servo (or SG90 for a small feeder) – 1
  • 1 kg or 5 kg bar load cell – 1
  • HX711 load cell amplifier module – 1
  • 0.96 inch SSD1306 I2C OLED display (128×64) – 1
  • Active 5V buzzer – 1
  • BC547 NPN transistor and 1 kΩ base resistor – 1 each
  • Push button (feed now / tare) – 1
  • 5V 2A power adapter with DC jack – 1
  • 470 µF 16V electrolytic capacitor (across servo supply) – 1
  • Food hopper (2 L plastic container or cereal dispenser), gate flap or paddle, and a steel bowl – 1 set
  • Two small plates of acrylic or MDF to mount the load cell, M4/M5 screws – 1 set
  • Perfboard or breadboard and jumper wires – 1 set

Wiring Table

Part / pinESP32 pinNotes
HX711 VCC / GND3V3 / GNDKeeps HX711 outputs at 3.3V logic
HX711 DT / SCKGPIO16 / GPIO17
Load cell red / black / white / greenHX711 E+ / E- / A- / A+Swap white and green if weight reads negative
Servo signal (orange)GPIO18Servo power from the 5V 2A supply, not the ESP32 3V3
Servo red / brown5V / GND470 µF capacitor across these two
OLED VCC / GND3V3 / GND
OLED SDA / SCLGPIO21 / GPIO22I2C address 0x3C
BC547 baseGPIO25 through 1 kΩEmitter to GND, collector to buzzer -, buzzer + to 5V
ButtonGPIO27 and GNDInternal pull-up
5V supply +ESP32 VINDo not also power from USB while the servo runs

Connection Diagram

The illustration near the top shows how the parts fit together. It is a layout guide only, so follow the pin-accurate drawing below, which matches the wiring table.

ESP32 Smart Pet Feeder – Pin-Accurate Wiring 5V 2A supply 5V to ESP32 VIN, servo red wire and buzzer + 470 µF capacitor across servo 5V and GND All GND pins joined together HX711 + load cell HX711 VCC to 3V3, GND to GND DT to GPIO16, SCK to GPIO17 Load cell: red E+, black E-, white A-, green A+ MG996R servo Signal (orange) to GPIO18 Red to 5V supply, brown to GND OLED (I2C) VCC to 3V3, GND to GND SDA to GPIO21, SCL to GPIO22 (address 0x3C) Buzzer driver GPIO25 to 1 kΩ to BC547 base Emitter to GND, collector to buzzer – Buzzer + to 5V Button One leg to GPIO27, other leg to GND (internal pull-up)
Pin-accurate connection diagram for the ESP32 smart pet feeder.

Building the Feeder

  • Mount the bar load cell between two plates in a Z shape: one end screwed to the base plate, the other end to the top plate that holds the bowl. Use spacers so the middle of the bar can bend freely and the arrow on it points down.
  • Cut a hole in the bottom of the hopper and fit a hinged flap or a small paddle on the servo horn so 80° opens it and 10° closes it. Test the two angles before you fix anything and change GATE_OPEN and GATE_CLOSED if needed.
  • Place the hopper outlet above the bowl but make sure the hopper and chute never touch the bowl or top plate, or the scale will read wrong.
  • Keep the electronics in a box away from water and the pet, and route all wires so the pet cannot chew them.

Calibrating the Scale

  • Upload the sketch with the empty bowl on the scale. It tares to 0 g at power-on.
  • Put a known weight on the bowl, for example a 200 g packet from the kitchen, and read the grams on the OLED.
  • New factor = current CAL_FACTOR × shown grams ÷ real grams. Put that in the code and upload again. Repeat once to check it reads within 2 g.
  • Run a test feed of 40 g and weigh the bowl on a kitchen scale to confirm.

Code

Install the esp32 by Espressif Systems board package in the Arduino IDE and select ESP32 Dev Module. From the Library Manager install HX711 by Rob Tillaart, ESP32Servo, Adafruit SSD1306 and Adafruit GFX Library. Replace the Wi-Fi placeholders with your own network name and password, then upload.

/*
  ESP32 Smart Pet Feeder with Load Cell, Servo, OLED & Web Schedule
  Arduino Project Hub - https://ardiunoprojecthub.online

  - Up to 4 daily meals, set from a phone web page (saved in flash)
  - Servo opens the hopper gate until the bowl gains the set grams (closed loop)
  - HX711 + load cell weighs the bowl, OLED shows time, bowl weight and next meal
  - Buzzer chime before each meal, jam/empty-hopper alarm
  - Button: short press = feed one portion now, hold 3 s = tare (zero) the scale

  Board: ESP32 Dev Module   Libraries: HX711 (Rob Tillaart), ESP32Servo,
  Adafruit SSD1306, Adafruit GFX
*/
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Preferences.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP32Servo.h>
#include <HX711.h>
#include <time.h>

// ---------- Wi-Fi (replace with your own) ----------
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

// ---------- Pins ----------
const int HX_DT    = 16;
const int HX_SCK   = 17;
const int SERVO_PIN = 18;
const int BUZZER   = 25;   // through BC547
const int BUTTON   = 27;   // to GND, internal pull-up

// ---------- Settings ----------
float CAL_FACTOR = 420.0;        // change after calibration (see post)
const int GATE_CLOSED = 10;      // servo angle with gate closed
const int GATE_OPEN   = 80;      // servo angle with gate open
const unsigned long FEED_TIMEOUT_MS = 15000; // max gate-open time
const float MAX_BOWL_G = 400;    // never feed above this bowl weight

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
Servo gate;
HX711 scale;
WebServer server(80);
Preferences prefs;

struct Meal { bool on; uint8_t h; uint8_t m; uint16_t grams; };
Meal meals[4];
int lastFedDay[4] = {-1, -1, -1, -1};
float bowlG = 0;
String lastFeed = "none";
bool jamAlarm = false;

// ---------- Helpers ----------
void beep(int times, int ms) {
  for (int i = 0; i < times; i++) {
    digitalWrite(BUZZER, HIGH); delay(ms);
    digitalWrite(BUZZER, LOW);  delay(ms);
  }
}

float readBowl() {
  if (!scale.is_ready()) return bowlG;
  float g = scale.get_units(5);
  if (g < 0 && g > -3) g = 0;     // hide tiny negative drift
  return g;
}

void loadMeals() {
  prefs.begin("feeder", true);
  for (int i = 0; i < 4; i++) {
    String k = "m" + String(i);
    meals[i].on    = prefs.getBool((k + "on").c_str(), i < 2);
    meals[i].h     = prefs.getUChar((k + "h").c_str(), i == 0 ? 8 : (i == 1 ? 18 : 12));
    meals[i].m     = prefs.getUChar((k + "m").c_str(), 0);
    meals[i].grams = prefs.getUShort((k + "g").c_str(), 40);
  }
  CAL_FACTOR = prefs.getFloat("cal", CAL_FACTOR);
  prefs.end();
}

void saveMeals() {
  prefs.begin("feeder", false);
  for (int i = 0; i < 4; i++) {
    String k = "m" + String(i);
    prefs.putBool((k + "on").c_str(), meals[i].on);
    prefs.putUChar((k + "h").c_str(), meals[i].h);
    prefs.putUChar((k + "m").c_str(), meals[i].m);
    prefs.putUShort((k + "g").c_str(), meals[i].grams);
  }
  prefs.end();
}

String nowText() {
  struct tm t;
  if (!getLocalTime(&t, 10)) return "--:--";
  char b[6]; sprintf(b, "%02d:%02d", t.tm_hour, t.tm_min);
  return String(b);
}

String nextMealText() {
  struct tm t;
  if (!getLocalTime(&t, 10)) return "no time";
  int nowMin = t.tm_hour * 60 + t.tm_min, best = 9999, idx = -1;
  for (int i = 0; i < 4; i++) {
    if (!meals[i].on) continue;
    int mm = meals[i].h * 60 + meals[i].m;
    int diff = (mm - nowMin + 1440) % 1440;
    if (diff == 0) diff = 1440;
    if (diff < best) { best = diff; idx = i; }
  }
  if (idx < 0) return "none";
  char b[16]; sprintf(b, "%02d:%02d %dg", meals[idx].h, meals[idx].m, meals[idx].grams);
  return String(b);
}

// ---------- Feeding (closed loop on bowl weight) ----------
bool feed(uint16_t grams) {
  float start = readBowl();
  if (start >= MAX_BOWL_G) return true;          // bowl already full
  float target = min(start + grams, MAX_BOWL_G);
  beep(2, 120);                                   // dinner chime
  gate.write(GATE_OPEN);
  unsigned long t0 = millis();
  float g = start;
  while (millis() - t0 < FEED_TIMEOUT_MS) {
    g = readBowl();
    if (g >= target - 2) break;                   // 2 g allowance for falling kibble
    // wiggle the gate every 2 s to clear a jam
    if (((millis() - t0) / 2000) % 2 == 1) gate.write(GATE_OPEN - 15); else gate.write(GATE_OPEN);
    delay(50);
  }
  gate.write(GATE_CLOSED);
  delay(800);
  bowlG = readBowl();
  float added = bowlG - start;
  lastFeed = nowText() + " +" + String(added, 0) + " g";
  Serial.printf("Fed %.0f g (target %u g)\n", added, grams);
  jamAlarm = (added < grams * 0.3);               // little food came out: hopper empty or jammed
  return !jamAlarm;
}

void checkSchedule() {
  struct tm t;
  if (!getLocalTime(&t, 10)) return;
  for (int i = 0; i < 4; i++) {
    if (meals[i].on && t.tm_hour == meals[i].h && t.tm_min == meals[i].m && lastFedDay[i] != t.tm_yday) {
      lastFedDay[i] = t.tm_yday;
      feed(meals[i].grams);
    }
  }
}

// ---------- Display ----------
void drawOled() {
  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);
  oled.setTextSize(1); oled.setCursor(0, 0);
  oled.print(nowText()); oled.print("  ");
  oled.print(WiFi.status() == WL_CONNECTED ? "WiFi OK" : "No WiFi");
  oled.setTextSize(2); oled.setCursor(0, 14);
  oled.print(bowlG, 0); oled.print(" g");
  oled.setTextSize(1); oled.setCursor(0, 36);
  oled.print("Next: "); oled.print(nextMealText());
  oled.setCursor(0, 48);
  if (jamAlarm) oled.print("CHECK HOPPER / JAM!");
  else { oled.print("Last: "); oled.print(lastFeed); }
  oled.display();
}

// ---------- Web page ----------
const char PAGE[] PROGMEM = R"HTML(<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Pet Feeder</title><style>body{font-family:Arial;margin:16px;background:#f4f7f7}
.c{background:#fff;border-radius:10px;padding:14px;margin-bottom:12px;box-shadow:0 1px 4px #0002}
h2{margin:0 0 8px;color:#00796b}.big{font-size:32px;font-weight:bold}
button{background:#ef6c00;color:#fff;border:0;border-radius:8px;padding:10px 16px;font-size:16px;margin:4px 4px 0 0}
input{width:70px;padding:4px}.row{margin:6px 0}</style></head><body>
<div class="c"><h2>Bowl</h2><div class="big" id="w">--</div>
<div id="info"></div>
<button onclick="act('/feed')">Feed now</button><button onclick="act('/tare')">Tare scale</button></div>
<div class="c"><h2>Meal schedule</h2><form id="f"></form><button onclick="save()">Save schedule</button></div>
<script>
function act(u){fetch(u,{method:'POST'}).then(r=>r.text()).then(t=>alert(t))}
function load(){fetch('/data').then(r=>r.json()).then(d=>{
 w.innerHTML=d.bowl+' g';info.innerHTML='Time '+d.time+'<br>Next meal '+d.next+'<br>Last feed '+d.last+(d.jam?'<br><b style="color:red">Check hopper or jam!</b>':'');
 if(!f.dataset.done){let h='';d.meals.forEach((m,i)=>{h+=`<div class="row"><input type="checkbox" id="on${i}" ${m.on?'checked':''}> Meal ${i+1}
 <input type="time" id="t${i}" value="${String(m.h).padStart(2,'0')}:${String(m.m).padStart(2,'0')}"> <input type="number" id="g${i}" min="5" max="200" value="${m.g}"> g</div>`});
 f.innerHTML=h;f.dataset.done=1}})}
function save(){let q=[];for(let i=0;i<4;i++){let t=document.getElementById('t'+i).value.split(':');
 q.push(`on${i}=${document.getElementById('on'+i).checked?1:0}&h${i}=${t[0]}&m${i}=${t[1]}&g${i}=${document.getElementById('g'+i).value}`)}
 fetch('/save?'+q.join('&'),{method:'POST'}).then(r=>r.text()).then(t=>alert(t))}
load();setInterval(load,3000);
</script></body></html>)HTML";

void handleData() {
  String j = "{\"bowl\":" + String(bowlG, 0) + ",\"time\":\"" + nowText() + "\",\"next\":\"" + nextMealText() +
             "\",\"last\":\"" + lastFeed + "\",\"jam\":" + (jamAlarm ? "true" : "false") + ",\"meals\":[";
  for (int i = 0; i < 4; i++) {
    j += "{\"on\":" + String(meals[i].on ? "true" : "false") + ",\"h\":" + meals[i].h + ",\"m\":" + meals[i].m + ",\"g\":" + meals[i].grams + "}";
    if (i < 3) j += ",";
  }
  j += "]}";
  server.send(200, "application/json", j);
}

void handleSave() {
  for (int i = 0; i < 4; i++) {
    String s = String(i);
    if (!server.hasArg("h" + s)) continue;
    meals[i].on = server.arg("on" + s) == "1";
    meals[i].h = constrain(server.arg("h" + s).toInt(), 0, 23);
    meals[i].m = constrain(server.arg("m" + s).toInt(), 0, 59);
    meals[i].grams = constrain(server.arg("g" + s).toInt(), 5, 200);
  }
  saveMeals();
  server.send(200, "text/plain", "Schedule saved");
}

void setup() {
  Serial.begin(115200);
  pinMode(BUZZER, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);
  gate.setPeriodHertz(50);
  gate.attach(SERVO_PIN, 500, 2400);
  gate.write(GATE_CLOSED);

  Wire.begin(21, 22);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE);
  oled.setCursor(0, 0); oled.print("Pet feeder starting"); oled.display();

  loadMeals();
  scale.begin(HX_DT, HX_SCK);
  scale.set_scale(CAL_FACTOR);
  scale.tare(20);   // keep the EMPTY bowl on the scale at power-on

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  unsigned long t0 = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(300);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Open http://"); Serial.println(WiFi.localIP());
    MDNS.begin("petfeeder");
  }
  configTime(19800, 0, "pool.ntp.org", "time.google.com"); // IST = UTC+5:30

  server.on("/", []() { server.send_P(200, "text/html", PAGE); });
  server.on("/data", handleData);
  server.on("/save", HTTP_POST, handleSave);
  server.on("/feed", HTTP_POST, []() {
    server.send(200, "text/plain", "Feeding one portion");
    feed(meals[0].grams);
  });
  server.on("/tare", HTTP_POST, []() { scale.tare(20); server.send(200, "text/plain", "Scale set to zero"); });
  server.begin();
  beep(1, 80);
}

unsigned long lastUi = 0, lastAlarm = 0;

void loop() {
  server.handleClient();

  // Button: short press feeds, 3 s hold tares
  if (digitalRead(BUTTON) == LOW) {
    unsigned long t0 = millis();
    while (digitalRead(BUTTON) == LOW && millis() - t0 < 3000) delay(10);
    if (millis() - t0 >= 3000) { scale.tare(20); beep(3, 60); }
    else { jamAlarm = false; feed(meals[0].grams); }
    while (digitalRead(BUTTON) == LOW) delay(10);
  }

  if (millis() - lastUi > 1000) {
    lastUi = millis();
    bowlG = readBowl();
    checkSchedule();
    drawOled();
  }

  if (jamAlarm && millis() - lastAlarm > 30000) {  // remind every 30 s
    lastAlarm = millis();
    beep(3, 200);
  }
}

Testing

  • Open the Serial Monitor at 115200 baud and note the IP address after “Open http://”.
  • Check that the OLED shows the correct time within a minute of boot.
  • Press the button once and check that the gate opens, closes when about 40 g has dropped, and the serial line shows the grams fed.
  • Set a meal two minutes ahead on the web page, save it and wait for the chime and feed.
  • Empty the hopper and press Feed now to check the jam alarm.

Troubleshooting

ProblemFix
ESP32 resets when the servo movesThe servo is pulling too much current. Use a 5V 2A supply, add the 470 µF capacitor, and keep the servo off the ESP32 3V3 pin.
Weight reads negative or does not changeSwap the load cell white and green wires, check that the bar is mounted with room to bend, and make sure nothing touches the top plate.
Weight drifts slowlyLet the HX711 warm up for a few minutes, keep the load cell wires short and twisted, and tare again with the empty bowl.
Portions are too bigKibble keeps falling after the gate closes. Raise the 2 g allowance in feed() or make the outlet smaller.
Time shows –:–The ESP32 has not reached the NTP server. Check the Wi-Fi name and password and that the router has internet.
Jam alarm with a full hopperLarge kibble is blocking the outlet. Make the hole bigger or increase GATE_OPEN.

Ideas to Extend

  • Add an IR break-beam sensor in the hopper to warn when food is low before it runs out.
  • Send a phone notification with ntfy after each meal with the grams eaten.
  • Weigh the bowl before the next meal to log how much your pet actually ate each day.

1 thought on “ESP32 Smart Pet Feeder with Load Cell, Servo, OLED & Web Schedule”

Leave a Comment