Siddhant Kumar
Project 014 Β· Smart Home

Smart Pet Feeder & Monitor.

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.

Intermediate 12–18 hours 43 min read CameraSchedulerApp
Jump to source Bill of materials
Smart Pet Feeder & Monitor β€” reference build illustration
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
β‚Ή6,400 – β‚Ή8,200
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Smart Home
Last updated
28 July 2026
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.

A brushed DC gear motor
A DC gear motor. The feeder uses one with an encoder to drive the auger, chosen over a servo because a servo cannot report that it is stalling. Photograph sourced from Wikimedia Commons β€” DC motor.jpg. Reused under the licence stated on that page; please check it before republishing.

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

SettingHow it is used
Scheduled feeding while awayThe core case, and the one where verified delivery rather than assumed delivery genuinely matters.
Portion control for weight managementVets prescribe grams per day; a feeder that measures grams is the only way to actually comply.
Multi-pet householdsCombine with RFID collar tags so each animal gets its own portion from its own bowl.
Medication timingFood-motivated dosing requires the meal to happen at a specific time, reliably.
Feeding behaviour monitoringA change in how fast or how completely a pet eats is often the earliest sign of illness.
Animal shelters and catteriesPer-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

AttributeValue
Difficulty levelIntermediate
Estimated completion time12–18 hours
Indicative build costβ‚Ή6,400 – β‚Ή8,200
Primary disciplineSmart Home
Reference platformESP32 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.

ComponentKey specificationQtyApprox. 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 DAC1β‚Ή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 SPS1β‚Ή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 encoder1β‚Ή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 PWM1β‚Ή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 pulse1β‚Ή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 flash1β‚Ή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Β²C1β‚Ή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 out1β‚Ή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 diameter1β‚Ή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 % efficiency1β‚Ή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 barrel1β‚Ή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 grid1β‚Ή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 diameter1β‚Ή400
Stainless steel bowl
Stainless only. Plastic bowls harbour bacteria and many animals react to them.
15 cm, dishwasher safe1β‚Ή250
Sealed hopper container3–5 L, airtight lid1β‚Ή450
Manual feed buttonNO momentary, large1β‚Ή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

PartSpecificationSupplyInterfaceReference
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 DAC3.3 V logic / 5 V USBUART, SPI, IΒ²C, IΒ²S, CAN, PWMDatasheet
5 kg load cell + HX711 24-bit ADCStrain-gauge bridge, 1.0 mV/V output, HX711 128Γ— gain, 10/80 SPS2.6–5.5 V2-wire serial (bit-banged)Datasheet
N20 micro gear motor (6 V, 200 rpm) with encoder6 V, 200 rpm, 0.4 kgΒ·cm, 12 mm Γ— 10 mm gearbox, magnetic encoder3–9 VPWM + H-bridgeDatasheet
TB6612FNG dual MOSFET motor driver2 Γ— 1.2 A continuous (3.2 A peak), 2.5–13.5 V motors, 100 kHz PWM2.7–5.5 V logicAIN/BIN + PWM + STBYDatasheet
HC-SR04 ultrasonic distance sensor2–400 cm, Β±3 mm, 15Β° beam, 40 kHz, 10 Β΅s trigger pulse5 VTrigger/Echo digitalDatasheet
ESP32-CAM (AI-Thinker) + OV2640ESP32-S chip, 4 MB PSRAM, 2 MP OV2640 camera, microSD slot, on-board LED flash5 V in / 3.3 V logicUART (programmer required), SPI, IΒ²CDatasheet
0.96β€³ SSD1306 OLED display128 Γ— 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz IΒ²C3.3–5 VIΒ²C (0x3C)Datasheet
DS3231 precision RTC + CR2032 backupΒ±2 ppm (Β±1 min/year), temperature-compensated crystal, alarms, 32 kHz out2.3–5.5 VIΒ²C (0x68)Datasheet
Active piezo buzzer 5 V85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter3–5 VDigital / PWMDatasheet
LM2596 adjustable buck converter module4.5–40 V in, 1.25–37 V out, 2 A (3 A peak), ~92 % efficiency4.5–40 VScrew terminals + trimmerDatasheet
12 V 5 A SMPS adapter100–240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ— 2.1 mm barrel12 VDC barrelDatasheet
Double-sided perfboard 7 Γ— 9 cm + headersFR-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.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA β€” size the regulator accordingly.
5 kg load cell + HX711 24-bit ADC2.6–5.5 V1.5Mechanical mounting dominates accuracy β€” bolt it to a rigid plate, not plastic.
N20 micro gear motor (6 V, 200 rpm) with encoder3–9 V120The encoder makes closed-loop speed control trivial β€” worth the extra cost.
TB6612FNG dual MOSFET motor driver2.7–5.5 V logic1.5MOSFET output means ~0.5 V drop β€” noticeably more runtime than an L298N.
HC-SR04 ultrasonic distance sensor5 V15Echo pin outputs 5 V β€” divide it down before feeding a 3.3 V ESP32.
ESP32-CAM (AI-Thinker) + OV26405 V in / 3.3 V logic220No USB-serial on board β€” needs an FTDI/CP2102 adapter to flash.
0.96β€³ SSD1306 OLED display3.3–5 V20Static images burn in β€” invert or scroll the screen periodically.
DS3231 precision RTC + CR2032 backup2.3–5.5 V0.2Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell β€” cut that resistor.
Active piezo buzzer 5 V3–5 V30Active buzzers make tone on DC; passive ones need a PWM carrier.
LM2596 adjustable buck converter module4.5–40 V8Set the output voltage with no load connected before wiring the board.
12 V 5 A SMPS adapter12 V5000Fuse 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.json under 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 dialout group: sudo usermod -aG dialout $USER and 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

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager β†’ "PubSubClient" by Nick O'Leary
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager β†’ "ArduinoJson" by Benoit Blanchon
HX711 0.7.xBit-banged 24-bit ADC read with tare and calibration factor.Library Manager β†’ "HX711" by Bogdan Necula
Adafruit SSD1306 + GFX 2.5.xFramebuffer and text/graphics primitives for the OLED.Library Manager β†’ "Adafruit SSD1306"
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core
NTPClient / configTime bundledWall-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.

Smart Pet Feeder & Monitor β€” system block diagramFunctional block diagram of the Smart Pet Feeder & Monitor system. SenseLoad cell + HX711bowl massHC-SR04hopper levelEncoderauger turnsDecideSchedule + RTCmealsBurst controllertarget massActTB6612 β†’ augershort burstsJam recoveryreverse + retryVerifyWeigh + logaudit trailCamera + MQTTconfirmationmass, timedispensedelivered mass
Smart Pet Feeder & Monitor β€” system block diagram

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.

Smart Pet Feeder & Monitor β€” wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBHX711 load cell ampGPIO 16 / 4Bit-banged 24-bitADCHC-SR04 hopper levelGPIO 5 / 18Echo through adividerN20 motor encoderGPIO 34 / 35Quadrature,interruptManual feed buttonGPIO 32Pull-upDS3231 RTC + OLEDGPIO 21 / 22Shared IΒ²CTB6612FNGGPIO 26 / 27 / 25Auger motor driveTB6612FNGGPIO 33Must be high toenableBuzzerGPIO 14Feed chime + alarmsESP32-CAMGPIO 12Separate board,pulse to capture
Smart Pet Feeder & Monitor β€” wiring schematic
PeripheralPeripheral pinController pinSignal
HX711 load cell ampDT / SCKGPIO 16 / 4Bit-banged 24-bit ADC
HC-SR04 hopper levelTRIG / ECHOGPIO 5 / 18Echo through a divider
N20 motor encoderA / BGPIO 34 / 35Quadrature, interrupt
Manual feed buttonNOGPIO 32Pull-up
DS3231 RTC + OLEDSDA / SCLGPIO 21 / 22Shared IΒ²C
TB6612FNGAIN1 / AIN2 / PWMAGPIO 26 / 27 / 25Auger motor drive
TB6612FNGSTBYGPIO 33Must be high to enable
Buzzer+GPIO 14Feed chime + alarms
ESP32-CAMTriggerGPIO 12Separate 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.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
An ESP32 development board running the weighing, dispensing and scheduling logic. Photograph sourced from Wikimedia Commons β€” ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

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.

Smart Pet Feeder & Monitor β€” architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) Β· HC-SR04 ultrasonic distance sensorDriver layerwifi Β· pubsub Β· arduinojson Β· hx711Application logicsampling loop Β· filtering Β· thresholds Β· state machineTransport layerWi-Fi + MQTT Β· TLS Β· retry and backoffPresentation layerdashboard Β· mobile notifications Β· historical charts
Smart Pet Feeder & Monitor β€” architecture stack

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

plainLoad 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

plainAuger 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

plainHopper 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.

Smart Pet Feeder & Monitor β€” firmware flowchartControl flow through the main program loop. Boot: tare bowl, load scheduleWait for scheduled time ormanual buttonAnti-gorge window clear?yesrefuse and logRun auger for a 400 ms burstSettle 800 ms, weigh the bowlTarget mass reached?donecheck for jamMass increased since lastburst?continuereverse, retry, then alarmLog delivered mass, triggercamera
Smart Pet Feeder & Monitor β€” firmware flowchart

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.

cpppet-feeder.ino
/* ═══════════════════════════════════════════════════════════════
   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();
}
dispense() returns delivered, not targetEvery caller gets the mass that actually landed in the bowl. That is the whole design principle β€” the feeder never reports success based on what it intended to do.
delay(SETTLE_MS) before weighingThe load cell picks up motor vibration and kibble still in flight. Weighing during or immediately after a burst gives readings that swing by tens of grams. Eight hundred milliseconds is enough for both to settle.
nowG βˆ’ lastG < MIN_GAIN_GJam detection in one line: a burst that adds less than 0.8 g delivered nothing. Whether the cause is a bridge, a wedged kibble or an empty hopper, the response β€” reverse and retry β€” is the same.
augerRun(false, 600, 255)Reverse at full duty for longer than a forward burst. Breaking a bridge needs more torque than normal dispensing, and reversing is the only motion that reliably does it without grinding.
gorgeInWindow() checked before every dispenseThe anti-gorge limit is enforced at the single entry point to dispensing, so it applies equally to scheduled, remote and manual feeds. A cat that learns to press the button cannot defeat it.
jamAlarm latched until cleared remotelyA jam needs a human to look at the mechanism. Auto-clearing would mean the feeder grinds against an obstruction every meal until something breaks.
Manual button before the 5 s slow loopThe manual feed path is checked every loop and never depends on Wi-Fi, MQTT or the RTC. If everything else fails, the button still feeds the animal.

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_G to about 1.2Γ— the daily ration. Tight enough to prevent a runaway, loose enough that a legitimate extra meal is not refused.
  • Tune BURST_MS for 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.

  1. 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 %.

  2. 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_G is set sensibly β€” it should be roughly 40 % of a normal burst.

  3. 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.

  4. 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

Smart Pet Feeder & Monitor β€” network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsFeederESP32 + load cellCameraESP32-CAMWi-Fi 2.4 GHzRouterIoT VLANMQTT 1883Local brokerMosquitto + HAPhone appfeed + photoGrafanaconsumption trend
Smart Pet Feeder & Monitor β€” network topology
Topic / endpointDirectionPayload
home/pet/feeder-cat/feeddevice β†’ brokerJSON: trigger, target_g, delivered_g, result, bowl_g, hopper_g, days_left
home/pet/feeder-cat/cmdbroker β†’ deviceJSON: action = feed | tare | clear | schedule
home/pet/feeder-cat/statusdevice β†’ 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.

TestWhat you should see
Tare with an empty bowl, then add a known 100 g massReading within about 2 g of 100 g.
Request a 40 g feedRoughly 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 objectReverse, retry three times, then a jam alarm and a distinctive buzzer pattern β€” no grinding.
Request feeds until the anti-gorge limit is reachedThe next request is refused, logged as anti-gorge-refused, and a low tone sounds.
Fill the hopper and check the estimateDays-remaining figure within about 20 % of your own calculation from the actual mass and daily ration.
Power-cycle and check the scheduleMeals still fire at the right times from the RTC, with no network required.
Disconnect Wi-Fi and press the manual buttonA normal feed cycle. The manual path must never depend on the network.
Watch bowl mass for an hour after a mealA 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.

A USB webcam
A camera module. Confirming the food was actually eaten is as useful as confirming it was dispensed. Photograph sourced from Wikimedia Commons β€” Webcam.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Weight readings jump by tens of grams when the auger runs

Likely cause. Motor PWM noise coupling into the HX711 leads, or mechanical vibration reaching the load cell.

Fix. Shorten and separate the HX711 leads from the motor wiring, twist the load cell pairs, and add a 100 nF capacitor across the HX711 supply. Then confirm you are only reading during the settle window, never during a burst.

The reading drifts steadily over hours

Likely cause. Temperature affecting the load cell, or mechanical creep in the mounting.

Fix. Some drift is inherent β€” aluminium cells have a temperature coefficient. Re-tare before each feed cycle rather than only at boot, which removes drift entirely from the measurement that matters.

The load cell reads a constant value regardless of load

Likely cause. Both ends bolted to the same rigid surface, so the beam cannot flex.

Fix. One end must be fixed and the other must carry the load with an air gap beneath it. This is the single most common load cell mounting error and it produces a perfectly stable, entirely useless reading.

The auger jams constantly with large kibble

Likely cause. Auger pitch or clearance too small for the kibble size.

Fix. Increase the auger pitch and the clearance between the auger and its housing to at least 1.5Γ— the largest kibble dimension. Also add a stirrer or a sloped hopper β€” bridging is a hopper geometry problem more than an auger problem.

Delivered mass consistently overshoots the target

Likely cause. Burst too long, or settle time too short so kibble in flight is not counted.

Fix. Reduce BURST_MS until each burst delivers about 2 g, and increase SETTLE_MS until repeated weighings of a static bowl agree within 1 g.

The hopper level reading is erratic

Likely cause. The ultrasonic sensor is seeing the hopper wall or an uneven food surface.

Fix. Mount it centrally, pointing straight down, at least 30 mm from any wall, and above the 25 cm blind zone. Median-filter several readings β€” a food surface is not flat and single readings scatter.

The sketch will not upload β€” "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools β†’ Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it β€” it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 Β΅F electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise β€” shorten the cable and keep motor wiring away from the USB lead.

An IΒ²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an IΒ²C scanner sketch first β€” it should print the device address. Most breakout boards include 4.7 kΞ© pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device β€” check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

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 a millis() 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_t where 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

Why weigh at all? Timed dispensing is much simpler.

Because timed dispensing cannot detect its own failure. An auger that jams, a hopper that bridges, or a motor that stalls all produce a feeder that runs for the right duration and delivers nothing β€” and reports success. If you are away for three days, that is the difference between an inconvenience and a genuine welfare problem.

Auger, drum or gate?

Auger. A rotating drum with pockets is simpler to print but jams badly on irregular or large kibble, and its volume per rotation is fixed so you cannot fine-tune portions. A gate is uncontrollable β€” it either flows or it does not. An auger gives repeatable volume per revolution, handles a wide kibble range, and can be reversed to clear a jam.

How accurate is the portioning?

About Β±2 g on the load cell measurement and Β±2 g on the overshoot from the final burst, so roughly Β±4 g on a 40 g meal β€” around 10 %. That is well inside what any veterinary portion guidance requires and dramatically better than a volumetric feeder, which is typically Β±25 %.

What happens if the Wi-Fi is down?

Everything except remote control and logging. The schedule lives in NVS and fires from the DS3231 RTC; the manual button works unconditionally; the anti-gorge and jam logic are entirely local. The network is for visibility, never for feeding.

Will the motor noise scare my pet?

Usually the opposite β€” most animals learn the sound within days and treat it as a dinner bell, which is why the firmware sounds a chime before dispensing. If your animal is genuinely noise-averse, reduce the PWM duty and lengthen the bursts; a slower auger is much quieter.

Can it handle wet food?

No. An auger and a hopper are dry-food mechanisms β€” wet food will not flow, will clog the auger and will spoil in the hopper. A wet-food feeder is a completely different design based on sealed portion trays and a rotating lid, and it needs refrigeration for anything beyond a few hours.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. HX711 24-bit ADC for weigh scales β€” datasheetAvia Semiconductor
  2. Load cell theory, Wheatstone bridges and mountingHBM
  3. TB6612FNG dual motor driver β€” datasheetToshiba
  4. Screw conveyor (auger) capacity and design fundamentalsConveyor Equipment Manufacturers Association
  5. Feline nutrition and portion guidanceWSAVA Global Nutrition Committee
  6. Bulk solids flow and hopper bridgingJenike & Johanson