AI is making waves everywhere, but what excites us most is how effortlessly it can now be incorporated into everyday devices. In fact, why should your backyard farm miss out on this revolution? If you're passionate about raising chickens but want to streamline your daily chores with cutting-edge technology, a DIY Smart Coop powered by AI and IoT is the perfect project for that.
Impact Statement
The AI Smart Coop empowers backyard farmers by integrating AI and IoT for streamlined, sustainable chicken care. This project automates key tasks—like door management, predator alerts, and feeding schedules—allowing users to enjoy the benefits of traditional farming with modern convenience. By blending technology with homesteading, the Smart Coop reduces labor, enhances safety, and adapts to unique needs, offering a smarter, more efficient way to manage chicken coops.
Components Required
1) Arduino Uno R4 x 1
2) Huskylens - An Easy-to-use AI Camera - Vision Sensor x 1
3) Nema 17 Stepper Motor x 1
4) L298 Motor Driver x 1
5) Mini 360 Step-Down Buck Converter Power Module x 1
6) LM10UU 10 MM Linear Motion Bearing x 4
7) 500 MM long Chrome Plated Smooth Rod Diameter 10 MM x 1
8) GT2 Aluminum Pulley (Without 20 teeth) 5mm Bore for 6mm Belt x 1
9) 1M GT2 Width 6mm Black Open Timing Belt x 1
10) GT2-6mm Belt Width 20 Teeth 5mm Bore Timing Pulley x 1
11) SG90 Continuous Rotation 360 Degree Servo Motor x 2
12) Standard 12V 5A 60W Power Supply x 1
13) DC Power Female Plug Jack Adapter Connector x 1
14) Silicon Wire
15) Acrylic Sheet
16) MDF 8 ft x 4 ft x 3/4 inch
17) Assorted Screw Kit (M3, M4)
To see the full demonstration video, click on the YouTube Video below.
The Vision Behind The DIY Smart Coop
Backyard farming is all about sustainability and the joy of raising chickens for fresh eggs and natural pest control. However, managing a chicken coop can be a lot of work, from early morning door openings to late-night predator checks. The Smart Coop changes all that, using AI-driven automation to make chicken care easier. With features like SMS alerts for predators and an automated door that opens and closes on a schedule, you can rest easy knowing your chickens are well cared for.
AI and IoT take it further, allowing for full control over key aspects of the coop. The door opens and closes automatically in the morning and evening, and you can customize feeding schedules or trigger instant feeding when needed. It's not just about convenience—it’s about blending the best of technology with tradition to give you peace of mind.
Why Build the DIY Smart Coop? This project goes beyond simple automation. AI and IoT empower you to create a high-tech, self-sustaining coop that’s tailored to your unique needs. Here’s why it’s worth building:
Reduce Your Workload: Automate key tasks like opening and closing the door, feeding your chickens, and monitoring for predators.
Enhance Safety with AI: Receive SMS alerts when predators are detected, ensuring your flock is protected even when you're away.
Stay in Control: Schedule the door to open and close, and take instant action from anywhere via your phone.
Customize Feeding: Set feeding times according to your schedule, or use instant feeding options to give your chickens a treat at the push of a button.
Adapt to Your Needs: Whether you're managing a large flock or a small coop, you can adjust the system to fit your specific requirements.
General Design
Our journey started with designing the coop in Fusion 360. This essential step involved carefully crafting a 3D model using accurate measurements, enabling us to visualize each component before construction. Using CAD software significantly reduces errors during the design process, allowing for precise measurements and modifications. This capability ensures that components fit together accurately and helps identify potential issues before construction, ultimately saving time and resources.
Micro Controller
The controller used in the project is the Arduino UNO R4 WiFi. It is a powerful microcontroller board designed around the 32-bit RA4M1 microcontroller from Renesas, offering improved performance and processing power compared to its 8-bit predecessor. It features an ESP32 module that provides both Wi-Fi and Bluetooth connectivity, making it ideal for IoT applications. With increased memory, including 32 KB of SRAM and 512 KB of flash memory, it can handle larger programs and more data. The board also boasts more general-purpose input/output (GPIO) pins, enhancing its capability to connect with multiple sensors and actuators simultaneously.
Its built-in USB-C port allows for convenient power and programming, and the higher clock speed of up to 48 MHz ensures faster data processing and communication for real-time applications. Additionally, the R4 WiFi incorporates advanced power management features, hardware support for PWM, ADC, and DAC, and enhanced security for wireless communication. It can be powered via USB-C or an external battery, providing flexibility for deployment in various projects. Maintaining compatibility with existing Arduino libraries and shields, the R4 WiFi benefits from extensive community support, making it an excellent choice for both beginners and experienced developers looking to create advanced IoT solutions.
Front Door Mechanism Setup
This split door system utilizes 10mm metal rods, a Nema 17 stepper motor, and a GT2 timing belt, pulley and all supported by linear ball bearings. The mechanism works by pushing one door while simultaneously pulling the other when the motor is engaged, allowing for smooth and synchronized movement. This design optimizes space while ensuring secure access, perfectly catering to the automated needs of the coop. We designed this mechanical system in Fusion 360 and 3D printed the required parts for building the system.
As the front door we used the 2mm orange acrylic sheet which is laser cut in the nearby laser cutting shop.
A single Nema 17 motor, driven by an L298 motor driver and controlled via the stepper.h library powers the entire mechanism. This setup is energized by a 12V 3A power supply, while the Arduino is powered using a power bank, making it an effective test configuration.
Before connecting the motor to the module, you need to identify the phases of the motor you plan to use. The best way to do this is to check the motor’s datasheet.
Then we connected everything to a waste wood to test the mechanism and ran the below test code.// Include the Arduino Stepper Library
#include <Stepper.h>
// Number of steps per output rotation
const int stepsPerRevolution = 200;
// Create Instance of Stepper library
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
void setup()
{
// set the speed at 40 rpm:
myStepper.setSpeed(40);
// initialize the serial port:
Serial.begin(9600);
}
void loop()
{
// step one revolution in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(4000);
// step one revolution in the other direction:
Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(4000);
}
The images below show the arrangement of the parts of the split door mechanism.
Feeder Mechanism & Electronic Enclosure
Creating an efficient and reliable feeder mechanism is crucial for maintaining a consistent feeding schedule for the chickens. We designed a dual-feeder setup using an Archimedes screw mechanism powered by a continuous servo motor, ensuring that food is dispensed smoothly and effectively.
Predator Detection With Husky Lens
Protecting your chickens from predators is a top priority when managing a coop, especially in a farm-to-table setup where the quality and safety of your livestock directly impact your food supply. Husky lens is used here to solve that issue.
HuskyLens is an AI-powered vision sensor that can recognize objects, faces, colors, lines, and tags. It's designed to be easy to use, with a user-friendly interface and a built-in screen that allows you to see what the sensor is detecting in real time. HuskyLens is based on machine learning and can be trained to recognize specific objects or creatures, making it an ideal tool for predator detection in a chicken coop. Follow these steps to set up HuskyLens for predator detection
To train the HuskyLens for predator detection, begin by powering it on. Then Navigate through the menu to select object recognition mode. Next, introduce the HuskyLens to various predators, such as raccoons, foxes, and stray dogs, either in a controlled environment or by using images and videos. Point the HuskyLens at the predator and press the "learn" button to teach it the animal’s specific features. For better accuracy, repeat this process from different angles and under varying lighting conditions. Once trained, test the HuskyLens by showing it images or videos of both predators and non-threatening animals like cats or squirrels, ensuring it can correctly differentiate between threats and non-threats. If the HuskyLens struggles to distinguish animals, fine-tune the training by adjusting the learning settings.
Once trained, the HuskyLens connects to the Arduino UNO R4 WiFi using the I2C protocol, ensuring smooth communication between the sensor and the controller. This setup allows the system to process and act on predator alerts in real time, keeping your chickens safe.
To place the Husky lens in the coop we have 3d printed this case for the sake of convenience.
Remaining Electronics And Enclosure
12V 3A power supply is used here as the main power source. However, the Husky lens and the Sg90 servo motor work at 5V, so we used the Mini 360 Buck converter to solve the issue.
The Arduino UNO R4 WiFi is powered directly from the 12V through the Vin pin.
Additionally, we developed a protective case for the electronic components housed within the coop, ensuring they are secure and shielded from the elements.
Housing & Painting
We constructed the housing using 3/4 inch MDF wood for the main structure, ensuring a strong and stable build. To achieve a precise fit, we used 1/2 inch MDF for the top section, which we tapered to give the project a retro aesthetic
The side panels were securely attached to the base with one-inch screws, while the door was fitted using 1/4-inch screws for the hinges. Before attaching the top portion, we primed the inner surface to streamline the finishing process, focusing on the outer surfaces for the final touch.
Then later we painted all the surfaces before getting into the final assembly.
Final Assembly
Then we started fitting the electronic and mechanical parts to the main coop. Primarily we attached the door portion by perfectly measuring the distance from the front face other the door mechanism would not operate as expected.
After that, we prepared the two feeder boxes by attaching the servo motors to them. Parallely we placed the electronic components in the box one by one by pulling out the wires for the components which is residing outside.
The husky lens was secured to the front portion with a piece of double-sided tape.
The two feeder portions were attached to a side adjacent with the help of drywall screws.
Two long wires are connected to the female DC power jack for powering up the coop.
You can find the entire assets for the replication in the GitHub repo.
Companion App
The app’s interface is built with HTML, CSS, and JavaScript, offering a responsive and user-friendly experience. It integrates Firebase JS for communication, enabling real-time updates and synchronization with the smart coop’s operations.
Twilio for SMS Alert
Twilio is a cloud communications platform that provides a set of APIs (Application Programming Interfaces) for building and integrating communication services into applications. It allows developers to add messaging, voice, and video capabilities to their applications without having to build or maintain complex infrastructure.
Here we are using Twilio to send SMS alerts if there are any predators detected.
Follow these steps carefully for integrating Twilio
1) Signup for Twilio, if you don't have an account
2) Get a Twilio Phone number, this phone number will be used for sending the SMS alert to the concerned person.
3) Then note the account info such as the Account SID, Auth Token and the generated Twilio number, this should need to be added in the code.
Smart Coop Is Ready For Action
Simply plug in your smart coop, and it’s ready to handle all your chicken care needs. From automated feeding and secure door control to real-time predator detection, this fully finished smart coop has everything set up for you. Just sit back and let your coop do the work!
For all the code, follow the GitHub link below:
#include <Arduino.h>
#include <WiFiS3.h>
#include <FirebaseClient.h>
#include <WiFiSSLClient.h>
#include <Servo.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <Stepper.h>
#include "HUSKYLENS.h"
HUSKYLENS huskylens;
#define FIREBASE_HOST "https://xxxxxx-xxxxx-default-rtdb.firebaseio.com/"
#define WIFI_SSID "<SSID>"
#define WIFI_PASSWORD "<PASSWORD>"
// Defines the number of steps per rotation
const int stepsPerRevolution = 350;
// Pins entered in sequence IN1-IN3-IN2-IN4 for proper step sequence
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
Servo servo;
WiFiSSLClient ssl;
DefaultNetwork network;
AsyncClientClass client(ssl, getNetwork(network));
FirebaseApp app;
RealtimeDatabase Database;
AsyncResult timer, feed;
NoAuth noAuth;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 19800);
String stimer;
String Str[] = {"00:00", "00:00", "00:00"};
int i, feednow = 0;
String oldDoorStatus;
bool status;
// Twilio credentials
const char* accountSid = "AC04883791bxxxxxxxxxxf51b1ffd1e7db6";
const char* authToken = "7ac85229c7a1xxxxxxxxxx11085859d1";
// Twilio API endpoint
const char* twilioUrl = "api.twilio.com";
const int httpsPort = 443;
// Recipient phone number
const char* toNumber = "<toNUMBER>";
// Message body
const char* messageBody = "Predator Detected!";
WiFiSSLClient cclient;
void printError(int code, const String &msg)
{
Serial.print("Error, msg: ");
Serial.print(msg);
Serial.print(", code: ");
Serial.println(code);
}
void setup()
{
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
Wire.begin();
/*while (!huskylens.begin(Wire))
{
Serial.println(F("Begin failed!"));
delay(100);
}*/
timeClient.begin();
// Initialize Firebase
initializeApp(client, app, getAuth(noAuth));
app.getApp<RealtimeDatabase>(Database);
Database.url(FIREBASE_HOST);
// Set async result
client.setAsyncResult(timer);
client.setAsyncResult(feed);
// Attach servo to pin D5
servo.attach(D3);
oldDoorStatus = Database.get<String>(client, "/doorStatus");
myStepper.setSpeed(30); //setting speed for the stepper motor
}
void sendTwilioMessage() {
if (WiFi.status() == WL_CONNECTED) {
// Connect to Twilio server
if (!cclient.connect(twilioUrl, httpsPort)) {
Serial.println("Connection to Twilio failed!");
return;
}
// Create the HTTP POST request
String postData = "To=" + String(toNumber) + "&Body=" + String(messageBody);
String auth = String(accountSid) + ":" + String(authToken);
String encodedAuth = "N2FjODUyMjljxxxxxxxxxxxxxxyNzllMDExMDg1ODU5ZDE=";
cclient.println("POST /2010-04-01/Accounts/" + String(accountSid) + "/Messages.json HTTP/1.1");
cclient.println("Host: " + String(twilioUrl));
cclient.println("Authorization: Basic " + encodedAuth);
cclient.println("Content-Type: application/x-www-form-urlencoded");
cclient.println("Content-Length: " + String(postData.length()));
cclient.println();
cclient.println(postData);
// Read the response
while (cclient.connected()) {
String line = cclient.readStringUntil('\n');
if (line == "\r") {
break;
}
}
// Print response body
String responseBody = cclient.readString();
Serial.println("Response:");
Serial.println(responseBody);
} else {
Serial.println("WiFi not connected");
}
}
void openDoor()
{
// Rotate CCW quickly at 10 RPM
myStepper.step(-stepsPerRevolution);
delay(1000);
}
void closeDoor()
{
// Rotate CW slowly at 5 RPM
myStepper.step(stepsPerRevolution);
delay(1000);
}
void loop()
{
huskylens.request();
HUSKYLENSResult result = huskylens.read();
if (result.ID > 0){
sendTwilioMessage();
}
String doorStatus = Database.get<String>(client, "/doorStatus");
if (doorStatus == "Open" && oldDoorStatus =="Close"){
//status = Database.set<String>(client, "/doorStatus", "Close");
Serial.println("Door Opening");
openDoor();
oldDoorStatus = "Open";
}
else if (doorStatus == "Close" && oldDoorStatus == "Open"){
//status = Database.set<String>(client, "/doorStatus", "Open");
Serial.println("Door Closing");
closeDoor();
oldDoorStatus = "Close";
}
else{
timeClient.update();
String currentTime = String(timeClient.getHours()) + ":" + String(timeClient.getMinutes());
String openingTime_str = Database.get<String>(client, "/OpeningTime");
String openingTime = openingTime_str.substring(9,14);
String closingTime_str = Database.get<String>(client, "/ClosingTime");
String closingTime = closingTime_str.substring(9,14);
if (currentTime == openingTime){
openDoor();
}
else if (currentTime == closingTime){
closeDoor();
}
}
feednow = Database.get<int>(client, "/feednow"); //feed.to<int>();
Serial.println(feednow);
if (feednow == 1) // Direct Feeding
{
servo.writeMicroseconds(1000); // rotate clockwise
delay(700); // allow to rotate for n milliseconds, you can change this to your need
servo.writeMicroseconds(1500); // stop rotation
feednow = 0;
bool status = Database.set<int>(client, "/feednow", feednow);
Serial.println("Fed");
}
else // Scheduling feed
{
for (i = 0; i < 3; i++)
{
String path = "timers/timer" + String(i);
stimer = Database.get<String>(client, path);//timer.to<String>();
Str[i] = stimer.substring(9, 14);
}
timeClient.update();
String currentTime = String(timeClient.getHours()) + ":" + String(timeClient.getMinutes());
if (Str[0] == currentTime || Str[1] == currentTime || Str[2] == currentTime)
{
servo.writeMicroseconds(1000); // rotate clockwise
delay(700); // allow to rotate for n milliseconds, you can change this to your need
servo.writeMicroseconds(1500); // stop rotation
Serial.println("Success");
delay(60000);
}
}
Str[0] = "00:00";
Str[1] = "00:00";
Str[2] = "00:00";
}