Contents β 26 sections
Project Overview
A portion-controlled feeder that weighs what it actually dispensed rather than guessing, detects a jam before the bowl stays empty all day, and shows you a photo of your pet eating it.
The failure mode that matters in a pet feeder is not over-feeding β it is silent under-feeding. An auger that jams on a large kibble, a hopper that bridges and stops flowing, a servo that stalls: all of them produce a feeder that reports "fed successfully" to an app while the bowl stays empty. If you are away for three days, that is a serious problem.
This design closes the loop with a load cell under the bowl. Every feed cycle runs the auger in short bursts and weighs the bowl between them, stopping when the target mass is reached and raising an alarm if the mass has not increased after several attempts. The feeder knows what it delivered rather than what it intended to deliver, and that single change eliminates the entire class of silent failures.
The second design decision is the dispensing mechanism. A screw auger gives a repeatable volume per revolution and handles a wide kibble size range; a rotating drum with pockets is simpler but jams on irregular kibble; a simple gate is uncontrollable. The auger is driven by a geared DC motor with encoder feedback rather than a servo, because a servo has no way to report that it is stalling against a jammed kibble.
Around that sits the rest of what makes a feeder actually usable: a camera so you can see whether the food was eaten, a hopper level sensor so you know before it runs out, a schedule that survives a power cut, and manual dispensing that works with the network completely down.
What this project does
- Dispenses a target mass of food, verified by a load cell rather than assumed from motor run time.
- Detects jams and bridging by checking that mass actually increased between auger bursts.
- Runs a daily schedule stored on-device, so a network outage never means a missed meal.
- Measures hopper level with an ultrasonic sensor and warns days before it empties.
- Captures a photo when the pet approaches, so you can confirm the food was eaten.
- Logs every feed with target mass, delivered mass, duration and any retries.
- Allows manual dispensing from a physical button that works with no network at all.
Real-World Applications
| Setting | How it is used |
|---|---|
| Scheduled feeding while away | The core case, and the one where verified delivery rather than assumed delivery genuinely matters. |
| Portion control for weight management | Vets prescribe grams per day; a feeder that measures grams is the only way to actually comply. |
| Multi-pet households | Combine with RFID collar tags so each animal gets its own portion from its own bowl. |
| Medication timing | Food-motivated dosing requires the meal to happen at a specific time, reliably. |
| Feeding behaviour monitoring | A change in how fast or how completely a pet eats is often the earliest sign of illness. |
| Animal shelters and catteries | Per-animal records of what was offered and what was consumed. |
Deployment contexts where a build of this kind earns its keep.
Features & Capabilities
- Closed-loop mass dispensing with a 5 kg load cell and HX711, accurate to about Β±2 g.
- Burst-and-weigh algorithm β short auger runs with a settle and weigh between each.
- Jam detection after three bursts with no mass increase, with an auger reverse-and-retry.
- Hopper level by ultrasonic time-of-flight, reported in days of food remaining.
- Anti-gorge lockout preventing more than a configured mass in any rolling six-hour window.
- Camera capture on approach, triggered by a change in bowl weight rather than by motion.
- Schedule in NVS with a DS3231 RTC, so meals happen on time with no network and no NTP.
- Full audit log of target versus delivered mass, which is what tells you the mechanism is degrading.
Difficulty, Time & Required Skills
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 12β18 hours |
| Indicative build cost | βΉ6,400 β βΉ8,200 |
| Primary discipline | Smart Home |
| Reference platform | ESP32 DevKit V1 (ESP-WROOM-32) |
Skills you should have (or will pick up)
- Arduino C++ with state machines
- Load cell calibration and the HX711 interface
- Driving a geared DC motor with an H-bridge
- Basic mechanical assembly and 3D printing
- MQTT and scheduling
Bill of Materials
Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift β treat them as a budgeting guide, not a quotation.
| Component | Key specification | Qty | Approx. cost |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) Wi-Fi transmit bursts peak near 500 mA β size the regulator accordingly. | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18Γ 12-bit ADC, 2Γ 8-bit DAC | 1 | βΉ450 |
| 5 kg load cell + HX711 24-bit ADC Mechanical mounting dominates accuracy β bolt it to a rigid plate, not plastic. | Strain-gauge bridge, 1.0 mV/V output, HX711 128Γ gain, 10/80 SPS | 1 | βΉ320 |
| N20 micro gear motor (6 V, 200 rpm) with encoder The encoder makes closed-loop speed control trivial β worth the extra cost. | 6 V, 200 rpm, 0.4 kgΒ·cm, 12 mm Γ 10 mm gearbox, magnetic encoder | 1 | βΉ420 |
| TB6612FNG dual MOSFET motor driver MOSFET output means ~0.5 V drop β noticeably more runtime than an L298N. | 2 Γ 1.2 A continuous (3.2 A peak), 2.5β13.5 V motors, 100 kHz PWM | 1 | βΉ260 |
| HC-SR04 ultrasonic distance sensor Echo pin outputs 5 V β divide it down before feeding a 3.3 V ESP32. | 2β400 cm, Β±3 mm, 15Β° beam, 40 kHz, 10 Β΅s trigger pulse | 1 | βΉ90 |
| ESP32-CAM (AI-Thinker) + OV2640 No USB-serial on board β needs an FTDI/CP2102 adapter to flash. | ESP32-S chip, 4 MB PSRAM, 2 MP OV2640 camera, microSD slot, on-board LED flash | 1 | βΉ620 |
| 0.96β³ SSD1306 OLED display Static images burn in β invert or scroll the screen periodically. | 128 Γ 64 monochrome, 1.3β3.3 V logic, 100 kHzβ400 kHz IΒ²C | 1 | βΉ250 |
| DS3231 precision RTC + CR2032 backup Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell β cut that resistor. | Β±2 ppm (Β±1 min/year), temperature-compensated crystal, alarms, 32 kHz out | 1 | βΉ180 |
| Active piezo buzzer 5 V Active buzzers make tone on DC; passive ones need a PWM carrier. | 85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter | 1 | βΉ25 |
| LM2596 adjustable buck converter module Set the output voltage with no load connected before wiring the board. | 4.5β40 V in, 1.25β37 V out, 2 A (3 A peak), ~92 % efficiency | 1 | βΉ90 |
| 12 V 5 A SMPS adapter Fuse the 12 V rail at ~1.5Γ your calculated draw. | 100β240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ 2.1 mm barrel | 1 | βΉ650 |
| Double-sided perfboard 7 Γ 9 cm + headers Solder female headers so the MCU can be swapped without desoldering. | FR-4, 0.1β³ pitch, plated through-holes, 24 Γ 18 grid | 1 | βΉ60 |
| 3D-printed auger, hopper and chute Print the auger solid at 100 % infill β a hollow auger flexes and the pitch changes under load. | PETG or food-safe PLA, 20 mm auger diameter | 1 | βΉ400 |
| Stainless steel bowl Stainless only. Plastic bowls harbour bacteria and many animals react to them. | 15 cm, dishwasher safe | 1 | βΉ250 |
| Sealed hopper container | 3β5 L, airtight lid | 1 | βΉ450 |
| Manual feed button | NO momentary, large | 1 | βΉ80 |
Estimated total: βΉ4,595, excluding tools, shipping and consumables.
Tools and consumables
- Soldering iron (temperature controlled, 350 Β°C) with 0.8 mm 60/40 or lead-free solder
- Digital multimeter β continuity, DC volts and current ranges
- Wire strippers, flush cutters and a small set of precision screwdrivers
- Heat-shrink tubing and a heat gun (or a lighter, carefully)
- A laptop with a USB port and the toolchain listed above
Hardware Specifications
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18Γ 12-bit ADC, 2Γ 8-bit DAC | 3.3 V logic / 5 V USB | UART, SPI, IΒ²C, IΒ²S, CAN, PWM | Datasheet |
| 5 kg load cell + HX711 24-bit ADC | Strain-gauge bridge, 1.0 mV/V output, HX711 128Γ gain, 10/80 SPS | 2.6β5.5 V | 2-wire serial (bit-banged) | Datasheet |
| N20 micro gear motor (6 V, 200 rpm) with encoder | 6 V, 200 rpm, 0.4 kgΒ·cm, 12 mm Γ 10 mm gearbox, magnetic encoder | 3β9 V | PWM + H-bridge | Datasheet |
| TB6612FNG dual MOSFET motor driver | 2 Γ 1.2 A continuous (3.2 A peak), 2.5β13.5 V motors, 100 kHz PWM | 2.7β5.5 V logic | AIN/BIN + PWM + STBY | Datasheet |
| HC-SR04 ultrasonic distance sensor | 2β400 cm, Β±3 mm, 15Β° beam, 40 kHz, 10 Β΅s trigger pulse | 5 V | Trigger/Echo digital | Datasheet |
| ESP32-CAM (AI-Thinker) + OV2640 | ESP32-S chip, 4 MB PSRAM, 2 MP OV2640 camera, microSD slot, on-board LED flash | 5 V in / 3.3 V logic | UART (programmer required), SPI, IΒ²C | Datasheet |
| 0.96β³ SSD1306 OLED display | 128 Γ 64 monochrome, 1.3β3.3 V logic, 100 kHzβ400 kHz IΒ²C | 3.3β5 V | IΒ²C (0x3C) | Datasheet |
| DS3231 precision RTC + CR2032 backup | Β±2 ppm (Β±1 min/year), temperature-compensated crystal, alarms, 32 kHz out | 2.3β5.5 V | IΒ²C (0x68) | Datasheet |
| Active piezo buzzer 5 V | 85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter | 3β5 V | Digital / PWM | Datasheet |
| LM2596 adjustable buck converter module | 4.5β40 V in, 1.25β37 V out, 2 A (3 A peak), ~92 % efficiency | 4.5β40 V | Screw terminals + trimmer | Datasheet |
| 12 V 5 A SMPS adapter | 100β240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ 2.1 mm barrel | 12 V | DC barrel | Datasheet |
| Double-sided perfboard 7 Γ 9 cm + headers | FR-4, 0.1β³ pitch, plated through-holes, 24 Γ 18 grid | β | β | Datasheet |
Consolidated electrical and interface specifications for every active part in the build.
Power Budget & Supply Sizing
Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA β size the regulator accordingly. |
| 5 kg load cell + HX711 24-bit ADC | 2.6β5.5 V | 1.5 | Mechanical mounting dominates accuracy β bolt it to a rigid plate, not plastic. |
| N20 micro gear motor (6 V, 200 rpm) with encoder | 3β9 V | 120 | The encoder makes closed-loop speed control trivial β worth the extra cost. |
| TB6612FNG dual MOSFET motor driver | 2.7β5.5 V logic | 1.5 | MOSFET output means ~0.5 V drop β noticeably more runtime than an L298N. |
| HC-SR04 ultrasonic distance sensor | 5 V | 15 | Echo pin outputs 5 V β divide it down before feeding a 3.3 V ESP32. |
| ESP32-CAM (AI-Thinker) + OV2640 | 5 V in / 3.3 V logic | 220 | No USB-serial on board β needs an FTDI/CP2102 adapter to flash. |
| 0.96β³ SSD1306 OLED display | 3.3β5 V | 20 | Static images burn in β invert or scroll the screen periodically. |
| DS3231 precision RTC + CR2032 backup | 2.3β5.5 V | 0.2 | Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell β cut that resistor. |
| Active piezo buzzer 5 V | 3β5 V | 30 | Active buzzers make tone on DC; passive ones need a PWM carrier. |
| LM2596 adjustable buck converter module | 4.5β40 V | 8 | Set the output voltage with no load connected before wiring the board. |
| 12 V 5 A SMPS adapter | 12 V | 5000 | Fuse the 12 V rail at ~1.5Γ your calculated draw. |
Summed typical draw is 5576.2 mA. With a 1.5Γ design margin the supply should deliver at least 8400 mA continuously at the stated rail voltage.
Software Requirements & Development Environment
Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.
- Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
- Add
https://espressif.github.io/arduino-esp32/package_esp32_index.jsonunder File β Preferences β Additional Board Manager URLs, then install esp32 from the Boards Manager. - Set the correct port under Tools β Port. On Linux add yourself to the
dialoutgroup:sudo usermod -aG dialout $USERand log out and back in. - Open the Serial Monitor at 115200 baud β every sketch here logs its state there.
- Keep File β Preferences β Show verbose output during: compilation switched on while you are debugging build errors.
Required libraries
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| PubSubClient 2.8 | Lightweight MQTT 3.1.1 client for constrained devices. | Library Manager β "PubSubClient" by Nick O'Leary |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager β "ArduinoJson" by Benoit Blanchon |
| HX711 0.7.x | Bit-banged 24-bit ADC read with tare and calibration factor. | Library Manager β "HX711" by Bogdan Necula |
| Adafruit SSD1306 + GFX 2.5.x | Framebuffer and text/graphics primitives for the OLED. | Library Manager β "Adafruit SSD1306" |
| Preferences (NVS) bundled | Wear-levelled key/value storage in ESP32 flash for settings. | Bundled with the ESP32 core |
| NTPClient / configTime bundled | Wall-clock time from an NTP server for timestamping. | Bundled (`configTime()` on ESP32) |
Block Diagram
The block diagram shows the functional decomposition of the system β what senses, what decides, what acts, and where the data ends up.
Circuit Diagram & Wiring
Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| HX711 load cell amp | DT / SCK | GPIO 16 / 4 | Bit-banged 24-bit ADC |
| HC-SR04 hopper level | TRIG / ECHO | GPIO 5 / 18 | Echo through a divider |
| N20 motor encoder | A / B | GPIO 34 / 35 | Quadrature, interrupt |
| Manual feed button | NO | GPIO 32 | Pull-up |
| DS3231 RTC + OLED | SDA / SCL | GPIO 21 / 22 | Shared IΒ²C |
| TB6612FNG | AIN1 / AIN2 / PWMA | GPIO 26 / 27 / 25 | Auger motor drive |
| TB6612FNG | STBY | GPIO 33 | Must be high to enable |
| Buzzer | + | GPIO 14 | Feed chime + alarms |
| ESP32-CAM | Trigger | GPIO 12 | Separate board, pulse to capture |
Wire one row at a time and tick it off β most "it does not work" reports trace back to a single swapped pair.
Wiring explanation
- Mount the load cell so the bowl loads it in the direction its strain gauges are oriented β there is an arrow on the body. Loading it sideways gives readings that change when the bowl is nudged.
- The load cell must be bolted to a rigid plate at the fixed end and to the bowl platform at the free end, with a gap so it can flex. Screwing both ends to the same rigid surface means it never bends and reads a constant value.
- Use a TB6612FNG rather than an L298N. The L298N drops about 2 V across its output transistors, which on a 6 V motor is a third of your voltage and a large fraction of your torque β exactly what you need when clearing a jam.
- The HC-SR04 echo pin outputs 5 V. Divide it to 3.3 V before the ESP32 or you will damage the input.
- GPIO 34 and 35 are input-only, which suits the encoder channels. They need external pull-ups if the encoder is open-collector.
- Keep the HX711 leads short and away from the motor wiring. It is a 24-bit amplifier reading microvolts, and motor PWM coupling into those leads produces weight readings that jump by tens of grams whenever the auger runs.
System Architecture
Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.
Working Principle
A load cell is an aluminium beam with four strain gauges bonded to it in a Wheatstone bridge. When the beam flexes, two gauges stretch and two compress, unbalancing the bridge and producing a differential voltage proportional to load. The output is tiny β a 5 kg cell rated at 1.0 mV/V excited at 5 V produces 5 mV at full scale, which is 1 Β΅V per gram. That is why the HX711 exists: it is a 24-bit ADC with a programmable gain amplifier of 128, specifically designed for bridge sensors.
Calibration is a two-point affair: tare (record the raw reading with the empty bowl in place) and scale (place a known mass and compute counts per gram). Both must be redone if you change the bowl, because the tare includes the bowl's own weight and any change in mounting stiffness changes the scale factor slightly.
The burst-and-weigh algorithm is what makes the feeder honest. Running the auger continuously and stopping at a target mass overshoots badly, because kibble in flight after the motor stops still lands in the bowl, and because the mass reading during motion is corrupted by vibration. Running in 400 ms bursts with an 800 ms settle before weighing gives a stable reading and bounds the overshoot to roughly one burst's worth of food β typically 2β4 g.
Jam detection then falls out for free. If a burst produces no measurable mass increase, either the hopper has bridged (kibble arching over the auger inlet), a piece is wedged in the auger, or the hopper is empty. The response is to reverse the auger briefly β which usually breaks a bridge or frees a wedged piece β and retry. After three failed retries the feeder stops and raises an alarm, which is the correct behaviour: continuing to grind against a jam destroys the mechanism and still delivers nothing.
The anti-gorge lockout exists because the most dangerous failure of an automatic feeder is dispensing repeatedly. A bug, a duplicated MQTT command, or a cat that has learned to trigger the manual button can all deliver a day's food in an hour, which for some animals causes bloat β a genuine emergency. A hard cap on total mass in any rolling six-hour window, enforced independently of the schedule logic, makes that impossible.
The maths behind it
Load cell sensitivity and resolution
Cell: 5 kg, 1.0 mV/V, excitation 5 V
Full-scale output = 5 V Γ 1.0 mV/V = 5 mV
Per gram = 5 mV / 5000 g = 1 Β΅V/g
HX711 at gain 128, 24-bit, Β±0.5 V/gain differential range:
input range = Β±20 mV
LSB = 40 mV / 2^24 = 2.38 nV
Theoretical resolution = 1 Β΅V / 2.38 nV β 420 counts/g
In practice noise limits usable resolution to about
Β±2 g β which is far better than a pet feeder needs,
and the extra headroom absorbs mechanical drift.
Auger volume per revolution
Auger outer diameter D = 20 mm, shaft d = 6 mm, pitch p = 15 mm
Swept volume per revolution:
V = Ο/4 Γ (DΒ² β dΒ²) Γ p
= 0.7854 Γ (400 β 36) Γ 15 = 4288 mmΒ³ β 4.29 mL
Dry kibble bulk density β 0.35 g/mL
mass per revolution β 1.5 g
Motor at 200 rpm = 3.33 rev/s β 5.0 g/s
400 ms burst β 2.0 g
So a 40 g meal takes about 20 bursts β
which at ~1.2 s per burst-and-weigh cycle is 24 s.
Hopper level in days
Hopper cross-section A = 150 Γ 150 mm = 22 500 mmΒ²
Ultrasonic distance to surface h_air (mm)
Hopper internal height H = 300 mm
volume_remaining = A Γ (H β h_air) mmΒ³
mass_remaining = volume Γ 0.35 g/mL / 1000
h_air = 90 mm:
V = 22500 Γ 210 = 4 725 000 mmΒ³ = 4725 mL
m = 4725 Γ 0.35 = 1654 g
Daily ration 120 g β 13.8 days remaining.
Warn at 4 days, alarm at 1 day.
Program Flowchart
The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.
Assembly Instructions
Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.
Step-by-Step Implementation Guide
Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.
Complete Source Code
The listing below is complete and compiles as written β there are no elided sections. Read the annotations under each block before you upload it.
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Smart Pet Feeder β ESP32 + 5 kg load cell + auger
Dispenses a target MASS, verified by weighing between short auger
bursts. Detects jams and bridging, reverses to clear them, and
refuses to exceed a rolling anti-gorge limit. The schedule lives
on-device so a network outage never means a missed meal.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <HX711.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Preferences.h>
#include <time.h>
#define WIFI_SSID "YOUR_WIFI"
#define WIFI_PASS "YOUR_PASSWORD"
#define MQTT_HOST "192.168.1.50"
#define DEVICE_ID "feeder-cat"
#define PIN_HX_DT 16
#define PIN_HX_SCK 4
#define PIN_TRIG 5
#define PIN_ECHO 18
#define PIN_ENC_A 34
#define PIN_BTN 32
#define PIN_AIN1 26
#define PIN_AIN2 27
#define PIN_PWMA 25
#define PIN_STBY 33
#define PIN_BUZZER 14
#define PIN_CAM_TRIG 12
#define BURST_MS 400
#define SETTLE_MS 800
#define MAX_BURSTS 60 // hard cap on one feed cycle
#define JAM_RETRIES 3
#define MIN_GAIN_G 0.8f // a burst must add at least this
#define GORGE_WINDOW_MS (6UL*3600UL*1000UL)
#define GORGE_MAX_G 120.0f
#define HOPPER_HEIGHT_MM 300.0f
#define HOPPER_AREA_MM2 22500.0f
#define KIBBLE_G_PER_ML 0.35f
HX711 scale;
Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WiFiClient net;
PubSubClient mqtt(net);
Preferences prefs;
float calFactor = 420.0f; // counts per gram, from calibration
float bowlG = 0, hopperG = 0;
float dailyRationG = 120.0f;
struct Meal { uint8_t hour, minute; float grams; bool enabled; };
Meal meals[4] = {
{ 7, 30, 40, true }, { 12, 30, 30, true },
{ 18, 30, 50, true }, { 22, 0, 0, false }
};
struct GorgeEntry { uint32_t at; float grams; } gorge[16];
uint8_t gorgeHead = 0;
volatile uint32_t encoderTicks = 0;
bool jamAlarm = false;
void IRAM_ATTR encoderISR() { encoderTicks++; }
/* ββ weighing βββββββββββββββββββββββββββββββββββββββββββββββββ */
float readBowlGrams() {
if (!scale.is_ready()) return bowlG;
long raw = scale.read_average(8);
return (raw - scale.get_offset()) / calFactor;
}
void tareBowl() {
scale.tare(20);
bowlG = 0;
Serial.println("Bowl tared");
}
/* ββ auger ββββββββββββββββββββββββββββββββββββββββββββββββββββ */
void augerRun(bool forward, uint16_t ms, uint8_t duty = 200) {
digitalWrite(PIN_STBY, HIGH);
digitalWrite(PIN_AIN1, forward ? HIGH : LOW);
digitalWrite(PIN_AIN2, forward ? LOW : HIGH);
ledcWrite(0, duty);
delay(ms);
ledcWrite(0, 0);
digitalWrite(PIN_AIN1, LOW);
digitalWrite(PIN_AIN2, LOW);
}
/* ββ anti-gorge βββββββββββββββββββββββββββββββββββββββββββββββ */
float gorgeInWindow() {
uint32_t now = millis();
float total = 0;
for (auto &g : gorge)
if (g.at && now - g.at < GORGE_WINDOW_MS) total += g.grams;
return total;
}
void gorgeRecord(float grams) {
gorge[gorgeHead] = { millis(), grams };
gorgeHead = (gorgeHead + 1) % 16;
}
/* ββ the feed cycle βββββββββββββββββββββββββββββββββββββββββββ */
float dispense(float targetG, const char *trigger) {
if (jamAlarm) { publishEvent(trigger, targetG, 0, "jam-alarm-latched"); return 0; }
float already = gorgeInWindow();
if (already + targetG > GORGE_MAX_G) {
publishEvent(trigger, targetG, 0, "anti-gorge-refused");
tone(PIN_BUZZER, 400, 500);
return 0;
}
float startG = readBowlGrams();
float lastG = startG;
uint8_t bursts = 0, retries = 0;
tone(PIN_BUZZER, 2200, 120); // feed chime β pets learn it fast
delay(300);
while (bursts < MAX_BURSTS) {
augerRun(true, BURST_MS);
delay(SETTLE_MS); // vibration must die before weighing
bursts++;
float nowG = readBowlGrams();
float delivered = nowG - startG;
if (delivered >= targetG) {
bowlG = nowG;
gorgeRecord(delivered);
publishEvent(trigger, targetG, delivered, "ok");
digitalWrite(PIN_CAM_TRIG, HIGH); delay(50); digitalWrite(PIN_CAM_TRIG, LOW);
return delivered;
}
if (nowG - lastG < MIN_GAIN_G) { // nothing came out
if (++retries > JAM_RETRIES) {
jamAlarm = true;
publishEvent(trigger, targetG, delivered, "jam");
for (int i = 0; i < 6; i++) { tone(PIN_BUZZER, 600, 200); delay(300); }
return delivered;
}
augerRun(false, 600, 255); // reverse hard to clear
delay(400);
augerRun(true, 200);
delay(SETTLE_MS);
} else {
retries = 0;
}
lastG = nowG;
}
float delivered = readBowlGrams() - startG;
publishEvent(trigger, targetG, delivered, "burst-limit");
return delivered;
}
/* ββ hopper level βββββββββββββββββββββββββββββββββββββββββββββ */
float hopperGrams() {
digitalWrite(PIN_TRIG, LOW); delayMicroseconds(3);
digitalWrite(PIN_TRIG, HIGH); delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
long us = pulseIn(PIN_ECHO, HIGH, 30000);
if (!us) return hopperG; // no echo: keep last value
float mm = us * 0.1715f; // 343 m/s, there and back
if (mm < 20 || mm > HOPPER_HEIGHT_MM + 40) return hopperG;
float fillMm = HOPPER_HEIGHT_MM - mm;
if (fillMm < 0) fillMm = 0;
float ml = HOPPER_AREA_MM2 * fillMm / 1000.0f;
return ml * KIBBLE_G_PER_ML;
}
/* ββ MQTT βββββββββββββββββββββββββββββββββββββββββββββββββββββ */
void publishEvent(const char *trigger, float target, float delivered, const char *result) {
JsonDocument d;
d["trigger"] = trigger;
d["target_g"] = roundf(target * 10) / 10.0f;
d["delivered_g"] = roundf(delivered * 10) / 10.0f;
d["result"] = result;
d["bowl_g"] = roundf(bowlG);
d["hopper_g"] = roundf(hopperG);
d["days_left"] = dailyRationG > 0 ? roundf(hopperG / dailyRationG * 10) / 10.0f : 0;
char b[256]; size_t n = serializeJson(d, b, sizeof(b));
mqtt.publish("home/pet/" DEVICE_ID "/feed", (uint8_t *)b, n, false);
Serial.printf("%s: target %.1f g, delivered %.1f g β %s\n",
trigger, target, delivered, result);
}
void onMessage(char *topic, byte *payload, unsigned int len) {
JsonDocument d;
if (deserializeJson(d, payload, len)) return;
const char *action = d["action"] | "";
if (!strcmp(action, "feed")) dispense(d["grams"] | 20.0f, "remote");
else if (!strcmp(action, "tare")) tareBowl();
else if (!strcmp(action, "clear")) { jamAlarm = false; Serial.println("Jam alarm cleared"); }
else if (!strcmp(action, "schedule")) {
int i = d["index"] | -1;
if (i >= 0 && i < 4) {
meals[i] = { (uint8_t)(d["hour"] | 7), (uint8_t)(d["minute"] | 0),
(float)(d["grams"] | 30.0f), (bool)(d["enabled"] | true) };
prefs.putBytes("meals", meals, sizeof(meals));
}
}
}
/* ββ setup / loop βββββββββββββββββββββββββββββββββββββββββββββ */
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT); pinMode(PIN_ECHO, INPUT);
pinMode(PIN_BTN, INPUT_PULLUP);
pinMode(PIN_AIN1, OUTPUT); pinMode(PIN_AIN2, OUTPUT);
pinMode(PIN_STBY, OUTPUT); digitalWrite(PIN_STBY, LOW);
pinMode(PIN_CAM_TRIG, OUTPUT);
pinMode(PIN_ENC_A, INPUT);
attachInterrupt(PIN_ENC_A, encoderISR, RISING);
ledcSetup(0, 20000, 8);
ledcAttachPin(PIN_PWMA, 0);
scale.begin(PIN_HX_DT, PIN_HX_SCK);
Wire.begin(21, 22);
oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
prefs.begin("feeder", false);
calFactor = prefs.getFloat("cal", 420.0f);
if (prefs.getBytesLength("meals") == sizeof(meals))
prefs.getBytes("meals", meals, sizeof(meals));
delay(1500);
tareBowl();
WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS);
for (int i = 0; i < 40 && WiFi.status() != WL_CONNECTED; i++) delay(250);
configTime(19800, 0, "pool.ntp.org");
mqtt.setServer(MQTT_HOST, 1883);
mqtt.setCallback(onMessage);
Serial.println("Feeder ready");
}
void loop() {
if (!mqtt.connected() && WiFi.status() == WL_CONNECTED) {
if (mqtt.connect(DEVICE_ID)) mqtt.subscribe("home/pet/" DEVICE_ID "/cmd");
}
mqtt.loop();
if (digitalRead(PIN_BTN) == LOW) { // manual: works with no network
delay(40);
if (digitalRead(PIN_BTN) == LOW) {
dispense(20.0f, "manual");
while (digitalRead(PIN_BTN) == LOW) delay(10);
}
}
static uint32_t lastSlow = 0;
if (millis() - lastSlow < 5000) return;
lastSlow = millis();
bowlG = readBowlGrams();
hopperG = hopperGrams();
// Scheduled meals β checked against the RTC, fired once per minute slot.
static int lastFiredMinute = -1;
time_t t = time(nullptr); struct tm tm; localtime_r(&t, &tm);
int slot = tm.tm_hour * 60 + tm.tm_min;
if (slot != lastFiredMinute) {
for (auto &m : meals) {
if (!m.enabled || m.grams <= 0) continue;
if (m.hour == tm.tm_hour && m.minute == tm.tm_min) {
lastFiredMinute = slot;
dispense(m.grams, "scheduled");
}
}
}
oled.clearDisplay();
oled.setTextColor(SSD1306_WHITE);
oled.setTextSize(2); oled.setCursor(0, 0);
oled.printf("%.0f g", bowlG);
oled.setTextSize(1);
oled.setCursor(0, 22); oled.printf("hopper %.0f g", hopperG);
oled.setCursor(0, 34); oled.printf("%.1f days left",
dailyRationG > 0 ? hopperG / dailyRationG : 0);
oled.setCursor(0, 46);
oled.print(jamAlarm ? "JAM - clear via app" : "ready");
oled.setCursor(0, 56); oled.printf("%02d:%02d", tm.tm_hour, tm.tm_min);
oled.display();
}
Configuration & Calibration
Configuration steps
- Calibrate the load cell first: tare with the empty bowl in place, put a known mass on it (a 100 g weight, or a measured volume of water), and set
calFactor = raw_counts / grams. - Measure your kibble's bulk density by weighing a known volume β the 0.35 g/mL default varies by 30 % between brands and it feeds directly into the hopper-days estimate.
- Set
GORGE_MAX_Gto about 1.2Γ the daily ration. Tight enough to prevent a runaway, loose enough that a legitimate extra meal is not refused. - Tune
BURST_MSfor your auger and motor. Aim for roughly 2 g per burst β larger bursts overshoot the target, smaller ones make a meal take too long. - Set the meal schedule through the MQTT command topic, which persists it to NVS. Verify it survives a power cut before you rely on it.
Calibration procedure
An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.
Two-point load cell calibration
Place the empty bowl and tare. Then place a known mass and read the raw counts.
calFactor = (raw_loaded β raw_tare) / known_grams. Repeat with a different mass to confirm linearity β the two factors should agree within about 1 %.Measure grams per burst
Tare the bowl, run exactly ten bursts, and weigh. Divide by ten. This number tells you both your effective auger throughput and whether
MIN_GAIN_Gis set sensibly β it should be roughly 40 % of a normal burst.Calibrate the hopper depth
Fill the hopper to a known mass and record the ultrasonic distance. Repeat at half and empty. If the relationship is not close to linear, the hopper walls are not vertical or the sensor is seeing the wall rather than the surface.
Verify jam recovery
Deliberately wedge a piece of kibble or a small object in the auger and run a feed. The feeder should reverse, retry, and after three attempts latch a jam alarm β not grind indefinitely.
Network Architecture & Connectivity
| Topic / endpoint | Direction | Payload |
|---|---|---|
home/pet/feeder-cat/feed | device β broker | JSON: trigger, target_g, delivered_g, result, bowl_g, hopper_g, days_left |
home/pet/feeder-cat/cmd | broker β device | JSON: action = feed | tare | clear | schedule |
home/pet/feeder-cat/status | device β broker (retained) | "online" / "offline" (LWT) |
Message contract between the device and the broker.
Dashboard setup
Plot delivered mass against target mass over time. A widening gap is the mechanism degrading β the auger wearing, the hopper geometry changing as the food settles differently, or the motor losing torque. It gives you weeks of warning before an outright failure.
Plot bowl mass continuously. The decay curve after a meal tells you how fast the animal ate, and a change in that curve is one of the earliest detectable signs of illness in cats.
Security considerations
- The command topic can dispense food. Use broker authentication β an open topic is a cat that gets fed by anyone on your network.
- Keep the anti-gorge limit in firmware, not in the automation layer. It must hold even if the broker sends a hundred feed commands.
- Add a Last Will so a dead feeder is visibly dead. Silence from a feeder while you are away is exactly the failure you cannot afford to miss.
Testing Procedure & Expected Output
Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop β the first failing step tells you exactly where to look.
| Test | What you should see |
|---|---|
| Tare with an empty bowl, then add a known 100 g mass | Reading within about 2 g of 100 g. |
| Request a 40 g feed | Roughly 20 bursts over about 25 s, delivering 40β44 g. Overshoot beyond one burst means the settle time is too short. |
| Block the auger with a wedged object | Reverse, retry three times, then a jam alarm and a distinctive buzzer pattern β no grinding. |
| Request feeds until the anti-gorge limit is reached | The next request is refused, logged as anti-gorge-refused, and a low tone sounds. |
| Fill the hopper and check the estimate | Days-remaining figure within about 20 % of your own calculation from the actual mass and daily ration. |
| Power-cycle and check the schedule | Meals still fire at the right times from the RTC, with no network required. |
| Disconnect Wi-Fi and press the manual button | A normal feed cycle. The manual path must never depend on the network. |
| Watch bowl mass for an hour after a meal | A decay curve as the animal eats, which is the data that makes the load cell worth having beyond dosing. |
Bench-test checklist. If a row fails, stop and fix it before moving on.
Expected output
With everything wired and the firmware uploaded, the Serial Monitor at 115200 baud should look similar to the trace below. Values will differ; the shape of the output should not.
Troubleshooting: Common Errors & Fixes
Performance Optimisation
- Re-tare before every feed cycle rather than only at boot. It removes thermal drift from the measurement that actually matters, at a cost of two seconds.
- Average eight HX711 samples per reading. The HX711 runs at 10 SPS by default, so eight samples takes 800 ms β which is exactly the settle time you already need.
- Keep the schedule check gated to one firing per minute slot, or a slow loop iteration can fire the same meal twice.
- Replace every
delay()with amillis()comparison β blocking delays are the single most common cause of dropped readings. - Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
- Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
- Use
uint8_t/uint16_twhere the range allows; on an 8-bit AVR a 32-bit add costs four times as much. - Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
- Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
- For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 Β΅A asleep, which is the difference between days and months of runtime.
- Profile before optimising β print
micros()deltas around each stage and fix the slowest one first.
Safety Precautions
- A feeder that fails silently is the real hazard. Verify the Last Will alert reaches your phone before relying on it while away, and always have a person who can check.
- Never leave a jam alarm unattended for days. Keep a backup manual feeding arrangement for any absence longer than 24 hours.
- Use food-safe materials for anything the kibble touches. Standard PLA is generally regarded as food-contact acceptable for dry, short-contact use, but layer lines harbour bacteria β smooth them, or use a food-grade liner.
- Keep the motor and electronics fully enclosed. Animals chew cables, and a chewed 12 V lead in a water bowl is a genuine hazard.
- Moving parts pinch. Keep fingers, cables and hair out of gear trains and wheels, and always test motion with the drivetrain unloaded and the robot on blocks first.
- Motors are inductive β always fit a flyback diode across a DC coil, or use a driver that already has one, or the back-EMF spike will destroy your GPIO.
- Wear eye protection when soldering or cutting, and solder in a ventilated space β rosin flux fumes are a respiratory irritant.
- Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
- Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.
Maintenance
- Wash the bowl and chute weekly. Fat from kibble builds up and goes rancid, and animals refuse food from a dirty bowl long before a human notices.
- Check the auger for wear every few months β a worn auger delivers less per revolution, which shows up as more bursts per meal in the log.
- Re-verify the load cell calibration quarterly with a known mass.
- Re-check every screw terminal and header after the first week β thermal cycling loosens connections that felt tight on day one.
- Listen for gear chatter. A servo that buzzes at rest is either stripped or fighting a mechanical bind β fix it before it burns out.
- Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
- Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware β not only in flash.
- Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.
Future Improvements & Upgrades
A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.
- Add RFID collar recognition so each animal in a multi-pet household gets its own portion, and one cannot eat another's prescription food.
- Add a water bowl with its own load cell β declining water intake is a very early indicator of feline kidney disease and is much harder to notice by eye than food intake.
- Add eating-rate analysis: the shape of the mass decay curve after a meal changes measurably when an animal is unwell.
- Add a hopper stirrer driven off the same motor through a one-way clutch, which nearly eliminates bridging.
- Add battery backup so a power cut during an absence does not mean missed meals.
- Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
- Add over-the-air firmware updates so you never have to physically reach a deployed node again.
- Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
- Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
- Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
- Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.
Frequently Asked Questions
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- HX711 24-bit ADC for weigh scales β datasheetAvia Semiconductor
- Load cell theory, Wheatstone bridges and mountingHBM
- TB6612FNG dual motor driver β datasheetToshiba
- Screw conveyor (auger) capacity and design fundamentalsConveyor Equipment Manufacturers Association
- Feline nutrition and portion guidanceWSAVA Global Nutrition Committee
- Bulk solids flow and hopper bridgingJenike & Johanson