Built-in project · Arduino Uno R3

Automatic pet feeder on an Arduino Uno

A DS3231 clock opens an MG996R food gate at three meal times a day, with a chirp first, the next meal on an I2C LCD and a FEED NOW button. The whole build, an Arduino Uno and 5 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Intermediate About 25 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $44. On Mokxi they're free.

The circuit runs here once the page has loaded.

What you'll learn

  • Reading a real-time clock over I2C
  • Driving a servo from a separate power supply
  • Comparing the clock to a list of meal times
  • Serving an event once, not every loop
  • Using a pull-up button wired to ground
  • Difficulty: Intermediate
  • Time: About 25 minutes
  • Board: Arduino Uno R3
  • Parts: 10

How it works

A DS3231 clock chip keeps the time and talks to the Uno over the I2C pins. The sketch reads it all the time and shows the clock and the next meal on the LCD, updating once per second.

When the clock reaches 07:30, 12:00 or 18:00, the buzzer chirps three times, the servo swings the gate to 90 degrees for 1.5 seconds, then it closes. The time and which meal was served print to the serial monitor.

The FEED NOW button on pin 2 gives an extra portion whenever you press it. The servo runs from its own 6 V supply, with its ground joined to the Uno's.

Parts list

10 parts, plus the jumper wires. They retail for about $44; on Mokxi they're free.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Real-time clock, DS3231 pin SCLArduino Uno R3 pin SCL
Real-time clock, DS3231 pin SDAArduino Uno R3 pin SDA
Arduino Uno R3 pin GNDGround
Servo, MG996R metal gear pin PWMArduino Uno R3 pin 9
Buzzer pin 1Arduino Uno R3 pin 8
Pushbutton pin 1bArduino Uno R3 pin 2
Character LCD with I2C backpack pin SDAArduino Uno R3 pin A4
Character LCD with I2C backpack pin SCLArduino Uno R3 pin A5
Real-time clock, DS3231 pin VCC5 V
Real-time clock, DS3231 pin GNDGround
Servo, MG996R metal gear pin GNDGround
Servo, MG996R metal gear pin VCC6 V
Pushbutton pin 2bGround
Buzzer pin 2Ground
Character LCD with I2C backpack pin GNDGround
Character LCD with I2C backpack pin VCC5 V

The note on the canvas

Word for word, as it sits beside the circuit in the editor.

Try it
1. Press Run. The clock starts at 07:29:50 and the screen shows the next meal, 07:30.
2. Wait ten seconds: the buzzer chirps, the gate opens for a portion and closes, and the serial monitor logs the meal.
3. Press FEED NOW for an extra portion at any time.
4. Change MEALS in the sketch to your own times.

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · Arduino Uno R3
// Automatic pet feeder: a DS3231 keeps the time, and at each meal time a
// servo opens the food gate for one portion and closes it again.
//
//   DS3231   SDA and SCL to the Uno's SDA and SCL, VCC 5V, GND
//   LCD      16x2 with an I2C backpack at 0x27: SDA A4, SCL A5, VCC 5V, GND
//            (A4 and A5 are the same I2C bus as SDA and SCL)
//   servo    MG996R signal on pin 9, VCC from its own 5 to 6 V supply,
//            GND joined to the Uno's
//   button   FEED NOW on pin 2, to GND (the pin's pull-up holds it HIGH)
//   buzzer   active buzzer on pin 8, other leg to GND
//
// HOW IT WORKS
//   The screen shows the time and the next meal. When the clock reaches a
//   meal time the buzzer chirps three times (so the pet learns the sound),
//   the gate opens to OPEN_ANGLE for PORTION_MS and closes. Each meal is
//   logged on the serial monitor with the time it was served.
//
//   A meal is served once: the sketch remembers the day and minute it last
//   fed, so the minute the clock sits on 07:30 gives one portion, not sixty.
//   FEED NOW gives an extra portion at any time, and is logged as one.
//
// WHAT TO CHANGE
//   MEALS        the meal times, as hour and minute, up to eight
//   PORTION_MS   how long the gate stays open: a longer time, a bigger meal
//   OPEN_ANGLE   how far the gate opens; CLOSED_ANGLE where it rests
//
// SETTING THE CLOCK. A DS3231 keeps time on its coin cell. To set a real
// one, run rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); once from setup()
// and upload again without it. In Mokxi the clock starts at the time in its
// "start" property.

#include <Wire.h>
#include <RTClib.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>

RTC_DS3231 rtc;
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo gate;

const int SERVO_PIN = 9;
const int BUTTON_PIN = 2;
const int BUZZER_PIN = 8;

struct Meal {
  uint8_t hour;
  uint8_t minute;
};
const Meal MEALS[] = {{7, 30}, {12, 0}, {18, 0}};
const int MEAL_COUNT = sizeof(MEALS) / sizeof(MEALS[0]);

const unsigned long PORTION_MS = 1500;
const int OPEN_ANGLE = 90;
const int CLOSED_ANGLE = 0;

long lastFed = -1;   // the day and minute of the last scheduled meal
int lastSecond = -1;

void two(Print &out, int n) {
  if (n < 10) out.print('0');
  out.print(n);
}

void showTime(Print &out, const DateTime &t, bool seconds) {
  two(out, t.hour());
  out.print(':');
  two(out, t.minute());
  if (seconds) {
    out.print(':');
    two(out, t.second());
  }
}

// The next meal after this minute, wrapping round to tomorrow's first.
int nextMeal(const DateTime &t) {
  int now = t.hour() * 60 + t.minute();
  for (int i = 0; i < MEAL_COUNT; i++) {
    if (MEALS[i].hour * 60 + MEALS[i].minute > now) return i;
  }
  return 0;
}

void chirp() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(BUZZER_PIN, HIGH);
    delay(100);
    digitalWrite(BUZZER_PIN, LOW);
    delay(100);
  }
}

void feed(const char *why) {
  DateTime t = rtc.now();
  lcd.setCursor(0, 1);
  lcd.print("Feeding...      ");
  chirp();
  gate.write(OPEN_ANGLE);
  delay(PORTION_MS);
  gate.write(CLOSED_ANGLE);
  showTime(Serial, t, true);
  Serial.print("  ");
  Serial.println(why);
  lastSecond = -1;  // redraw the screen at once
}

void setup() {
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(BUZZER_PIN, OUTPUT);
  gate.attach(SERVO_PIN);
  gate.write(CLOSED_ANGLE);
  lcd.init();
  lcd.backlight();
  if (!rtc.begin()) {
    Serial.println("no DS3231 at 0x68: check SDA, SCL and VCC");
    lcd.print("No clock found");
    while (true) delay(10);
  }
  if (rtc.lostPower()) Serial.println("the clock lost power: set the time");
  Serial.print("pet feeder ready, meals at");
  for (int i = 0; i < MEAL_COUNT; i++) {
    Serial.print(' ');
    two(Serial, MEALS[i].hour);
    Serial.print(':');
    two(Serial, MEALS[i].minute);
  }
  Serial.println();
}

void loop() {
  DateTime t = rtc.now();

  // A meal time: once per day and minute, however long the minute lasts.
  long stamp = (long)(t.unixtime() / 60);
  for (int i = 0; i < MEAL_COUNT; i++) {
    if (t.hour() == MEALS[i].hour && t.minute() == MEALS[i].minute && stamp != lastFed) {
      lastFed = stamp;
      char why[] = "meal 0 served";
      why[5] = '1' + i;
      feed(why);
    }
  }

  if (digitalRead(BUTTON_PIN) == LOW) {
    feed("extra portion (FEED NOW)");
    while (digitalRead(BUTTON_PIN) == LOW) delay(10);
  }

  if (t.second() != lastSecond) {
    lastSecond = t.second();
    lcd.setCursor(0, 0);
    lcd.print("Time ");
    showTime(lcd, t, true);
    lcd.print("   ");
    const Meal &next = MEALS[nextMeal(t)];
    lcd.setCursor(0, 1);
    lcd.print("Next meal ");
    two(lcd, next.hour);
    lcd.print(':');
    two(lcd, next.minute);
    lcd.print(' ');
  }
  delay(50);
}

Code walkthrough

The key functions of the sketch, and what each one does.

loop sketch.ino

Each pass reads the time and checks it against every entry in MEALS. It turns the time into a minute count and compares it to lastFed, so a meal fires once even though the clock sits on 07:30 for a whole minute. It also checks the button and redraws the LCD when the second changes.

void loop() {
  DateTime t = rtc.now();

  // A meal time: once per day and minute, however long the minute lasts.
  long stamp = (long)(t.unixtime() / 60);
  for (int i = 0; i < MEAL_COUNT; i++) {
    if (t.hour() == MEALS[i].hour && t.minute() == MEALS[i].minute && stamp != lastFed) {
      lastFed = stamp;
      char why[] = "meal 0 served";
      why[5] = '1' + i;
      feed(why);
    }
  }

  if (digitalRead(BUTTON_PIN) == LOW) {
    feed("extra portion (FEED NOW)");
    while (digitalRead(BUTTON_PIN) == LOW) delay(10);
  }

  if (t.second() != lastSecond) {
    lastSecond = t.second();
    lcd.setCursor(0, 0);
    lcd.print("Time ");
    showTime(lcd, t, true);
    lcd.print("   ");
    const Meal &next = MEALS[nextMeal(t)];
    lcd.setCursor(0, 1);
    lcd.print("Next meal ");
  // ... 7 more lines in the editor

feed sketch.ino

Shows Feeding on the screen, calls chirp, opens the gate to OPEN_ANGLE, waits PORTION_MS, and closes it again to CLOSED_ANGLE. Then it prints the time and the reason to the serial monitor. Both the scheduled meals and the button use this same function.

void feed(const char *why) {
  DateTime t = rtc.now();
  lcd.setCursor(0, 1);
  lcd.print("Feeding...      ");
  chirp();
  gate.write(OPEN_ANGLE);
  delay(PORTION_MS);
  gate.write(CLOSED_ANGLE);
  showTime(Serial, t, true);
  Serial.print("  ");
  Serial.println(why);
  lastSecond = -1;  // redraw the screen at once
}

nextMeal sketch.ino

Finds which meal comes next. It turns the current time into minutes since midnight and returns the first meal later than that. If every meal today has passed, it wraps around and returns the first one, which is tomorrow's.

// The next meal after this minute, wrapping round to tomorrow's first.
int nextMeal(const DateTime &t) {
  int now = t.hour() * 60 + t.minute();
  for (int i = 0; i < MEAL_COUNT; i++) {
    if (MEALS[i].hour * 60 + MEALS[i].minute > now) return i;
  }
  return 0;
}

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • The screen says No clock found and nothing runs. This project
    Check that the DS3231 SDA and SCL are wired to the Uno's SDA and SCL and that its VCC is on 5 V.
  • The servo twitches or the Uno resets when the gate moves. This project
    Power the MG996R from its own 6 V supply, not the Uno, and join its ground to the Uno's ground.
  • Meals fire at the wrong time of day. This project
    Edit the hours and minutes in MEALS. They use a 24 hour clock, so 18:00 is 6 PM.
  • The time shows odd numbers, such as 0x23 printed as 35, when you read it. Real-time clock
    All time registers are BCD, not plain binary. Convert each byte with (b >> 4) * 10 + (b & 0x0F) to read, and the reverse to write. A library such as RTClib does this for you.
  • The clock does not respond, or the I2C bus hangs. Real-time clock
    The DS3231 address is 0x68. Wire SDA and SCL to the right pins with pull-ups, about 4.7k, to the supply. Many breakout boards already have them. Join the grounds.
  • The servo jitters, resets the board, or the Arduino reboots when it moves. Servo
    It can draw over 1 A moving and up to about 2.5 A stalled. Power it from its own 4.8 to 6 V supply, not the Arduino 5 V pin. Join the grounds and add a 470 uF or larger capacitor.
  • The servo hums or gets hot at the end of travel. Servo
    The code asks for an angle past its range, so it pushes against the stop. Stay inside the real range, such as 10 to 170 degrees, and detach when it is not needed. Gears can strip when stalled.
  • The input reads random HIGH and LOW when the button is not pressed. Pushbutton
    A floating pin picks up noise. Add a 10 k pull-down or pull-up resistor, or use INPUT_PULLUP and wire the button between the pin and GND. Then pressed reads LOW.

Questions and answers

Will it feed twice if the clock sits on the meal minute?

No. The sketch remembers the day and minute of the last scheduled meal, so each meal time serves one portion however long that minute lasts.

How do I make the portions bigger or smaller?

Change PORTION_MS, how long the gate stays open (1.5 s here). OPEN_ANGLE sets how far it opens.

How do I set my own meal times?

Edit the MEALS list at the top of the sketch, as hour and minute pairs. The LCD always shows the next one.

Why does the servo have its own power supply?

An MG996R can pull over an amp when it moves, more than the Uno’s 5 V pin can give. A separate 5 to 6 V supply with the grounds joined keeps the board from resetting.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.