Home » #Technology » IoT Connected Pet Feeder with Arduino: Tracking Feeding Data via API

IoT Connected Pet Feeder with Arduino: Tracking Feeding Data via API

With over 18 years of experience in the tech industry, I can confirm that IoT has transformed the way we stay connected to the devices we use daily. One prime example is the connected pet feeder, a perfect solution for pet owners to ensure their pets are well-fed, even when they’re away. In this tech concept, I will show how to build a smart pet feeder using an Arduino that can automate feeding times, track feeding activity, and send data to a cloud-based Java API. This project will also involve storing feeding history in a MySQL database for easy retrieval and analysis, allowing you to monitor feeding patterns and ensure that your pet gets the proper care at the right time.

Prerequisites

Hardware:

  • Arduino (Uno or Nano)
  • Servo motor (to control the pet feeder’s dispensing mechanism)
  • Weight sensor (optional, to measure the amount of food dispensed)
  • Wi-Fi module (ESP8266/ESP32 for wireless communication)
  • Jumper wires and breadboard
  • Power supply
  • Pet feeder setup (can be a DIY or commercial feeder connected to the servo motor)

Software:

  • Java (for API development)
  • MySQL (to store feeding data)
  • Arduino IDE (to program the Arduino)
  • Postman (for testing the API)

Step 1: Setting Up Arduino for Pet Feeder Control

The first step is to set up the Arduino to control the feeder using a servo motor. The servo motor will dispense food based on a predefined schedule or a remote trigger via the Java API.

Basic Arduino understanding before coding:
  • VCC of the servo connects to the 5V pin on Arduino.
  • GND of the servo connects to the GND pin on Arduino.
  • Signal of the servo connects to Pin 9 on the Arduino.
Arduino Code to Control Feeder and Send Data:

This code controls the servo to dispense food and sends feeding data to a Java-based API endpoint.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Servo.h>

const char* ssid = "your-SSID";
const char* password = "your-password";
const char* apiEndpoint = "http://your-server.com/api/pet-feeder";  // Java API endpoint

Servo feederServo;
int servoPin = 9;
int feedDuration = 1000;  // Time to activate feeder in milliseconds

void setup() {
  Serial.begin(115200);
  feederServo.attach(servoPin);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  // Simulate a feeding event triggered every 6 hours
  if (millis() % (6 * 60 * 60 * 1000) == 0) {
    dispenseFood();
    sendFeedingData();
    delay(60000);  // Prevents multiple feedings within the same minute
  }
}

void dispenseFood() {
  feederServo.write(180);  // Activate servo to dispense food
  delay(feedDuration);
  feederServo.write(0);  // Return servo to initial position
}

void sendFeedingData() {
  HTTPClient http;
  WiFiClient client;

  String postData = "status=dispensed&time=" + String(millis());

  http.begin(client, apiEndpoint);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  int httpCode = http.POST(postData);  // Send POST request with feeding data

  if (httpCode > 0) {
    String response = http.getString();
    Serial.println("Server response: " + response);
  } else {
    Serial.println("Error sending data to server");
  }

  http.end();
}

This code activates the servo motor to dispense food and sends the feeding event data (status and timestamp) to the Java API.

Step 2: Building the Java API to Receive Feeding Data

we will create our API using Spring Boot, A Java API that will accept feeding data from the Arduino, store it in a MySQL database, and provide endpoints to retrieve feeding history. Here’s how to build a simple RESTful API using Java and MySQL.

Java API Code (Spring Boot Example):
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;

import java.sql.*;

@RestController
@RequestMapping("/api/pet-feeder")
public class PetFeederController {

    @Autowired
    private FeedingService feedingService;

    @PostMapping
    public ResponseEntity<String> logFeeding(@RequestParam String status, @RequestParam String time) {
        feedingService.saveFeedingData(status, time);
        return ResponseEntity.ok("Feeding data received and stored");
    }

    @GetMapping("/history")
    public ResponseEntity<List<FeedingLog>> getFeedingHistory() {
        List<FeedingLog> history = feedingService.getFeedingHistory();
        return ResponseEntity.ok(history);
    }
}

// Service Class
@Service
public class FeedingService {

    private final String url = "jdbc:mysql://localhost:3306/pet_feeder";
    private final String user = "username";
    private final String password = "password";

    public void saveFeedingData(String status, String time) {
        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            String query = "INSERT INTO feeding_log (status, time) VALUES (?, ?)";
            PreparedStatement stmt = conn.prepareStatement(query);
            stmt.setString(1, status);
            stmt.setString(2, time);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<FeedingLog> getFeedingHistory() {
        List<FeedingLog> history = new ArrayList<>();
        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            String query = "SELECT * FROM feeding_log ORDER BY time DESC";
            PreparedStatement stmt = conn.prepareStatement(query);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                FeedingLog log = new FeedingLog(rs.getString("status"), rs.getString("time"));
                history.add(log);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return history;
    }
}

// Feeding Log Model
public class FeedingLog {
    private String status;
    private String time;

    public FeedingLog(String status, String time) {
        this.status = status;
        this.time = time;
    }

    // Getters and Setters
}

This code defines a simple API that accepts feeding data from the Arduino and stores it in a MySQL database. It also provides a GET endpoint to retrieve feeding history.

Step 3: Setting Up MySQL Database

Create a MySQL database to store the feeding data. Each feeding event will be logged with a status and timestamp.

SQL Schema for MySQL:
CREATE DATABASE pet_feeder;

USE pet_feeder;

CREATE TABLE feeding_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    status VARCHAR(255) NOT NULL,
    time VARCHAR(255) NOT NULL
);

This schema creates a table named feeding_log to store the status (e.g., “dispensed”) and the time of the feeding event.

Step 4: Testing the Java API

Use Postman to test the API before integrating it with the Arduino. You can simulate sending feeding data and retrieve the history of feeding events.

  1. Sending Feeding Data:
  • Method: POST
  • URL: http://localhost:8080/api/pet-feeder
  • Body: status=dispensed&time=1634567890123
  1. Retrieving Feeding History:
  • Method: GET
  • URL: http://localhost:8080/api/pet-feeder/history

This will return a JSON array of feeding events from the database.

For pet lovers who want peace of mind while away, This tech concept is the perfect solution. This easy-to-build IoT project allows you to automate feeding and monitor your pet’s routine from a distance. I’ve kept the concept focused strictly on programming for data streaming. For more detailed information on Arduino, check out the numerous YouTube tutorials available. With the flexibility of this setup, you can add features like scheduling, manual feed triggers via an app, or even weight-based control for precision feeding.

#AskDushyant
#TechConcept #IoT #Java #API #MySQL 
Note: The example and pseudo code is for illustration only. You must modify and experiment with the concept to meet your specific needs.

Leave a Reply

Your email address will not be published. Required fields are marked *