Introduction: Automatic Chicken Coop Door

Picture of Automatic Chicken Coop Door

I wanted a small door to open automatically (via Arduino - morning/night) to the outside world. Doing this would relieve us from worrying if the chickens were safe at night and to be able to leave the house when we wanted) This door will be located on the side of the coop and will slide open (vertically) so the girls can up & down their ladder about 18″ to the ground level. (although ladders are really not needed as my chickens can fly straight up to the door without trouble)
I’ve lived with the chickens and the coop for some time now and have learned quite a bit… especially about their habits. This is important, because no matter how much I’d like to automate this coop via my El Pollo Palace Networks Operations Center or the E.P.P.N.O.C. = ) (Arduino Controller) the chickens will ultimately dictate how it’s made and how it will operate.

Step 1: Videos of the Arduino Chicken Coop Door

The Installed Arduino Chicken Door

How I built the Automated Chicken Coop Door

Testing the door with the Arduino

Step 2: The Photocell

Picture of The Photocell

Note: for a nicer view of the images, parts, diagrams and code, please visit:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

When I first started this coop project I wanted to use a real-time clock and an Arduino library called Time Lord, but since I was a newbie to Arduino and struggled with the implementation of Time Lord I decided to go with using a photocell resistor instead. I’m actually glad I did since chickens come home to roost based on light, (not time) and with a photocell I won’t have to worry about a real time clock resetting due to power outages or battery failure, I think it will be less prone to problems.

Photocell application and installation
I first soldered the photocellto my cable, applied heat shrink tubing and encased the connection within a 1/4 inch plastic audio connector case. I filled the casing with silicone and capped the very tip with clear plexiglass to project the photocell from the elements. then I simply drilled a hole above the coop door monitor, and finished the outside with a brass grommet.

Step 3: The Door Construction

Picture of The Door Construction

Note: for a nicer view of the images, parts, diagrams and code, please visit:

http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

As you can see, the door construction is fairly straightforward. I began framing out the door with 2 x 2s, capped with 2x4s and screwed everything together with 1/2 inch galvanized deck screws. The door itself is a 1/8 inch birch, sandwiching in OSB plywood door locks ~and in the pictures (below)~ is the 1/8th inch acrylic. Note: I have since swapped out the acrylic with more 1/8 inch birch because I cracked the acrylic… being too rough with all the testing. =(

I cut 1/2 inch grooves into the backsides of the 2x2s so the door could slide easily. I gave myself enough room for 1/4″ of play. You can see in the pictures I’ve also rubbed a bar of soap over the edges all moving parts to ensure that they will move freely. If you’re taking on this project I’m assuming you have basic carpentry skills and can simply take a look at the pictures below to come up with similar ideas to build your own. ( which of course is my way of saying I didn’t do a great job documenting this exact process with plans or dimensions) =)

Step 4: The Door Reed Switches

Picture of The Door Reed Switches

Note: for a nicer view of the images, parts, diagrams and code, please visit:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

At first I was going to use micro switches for this build, but after testing them I felt they would wear out over time, being mechanical-type switches. So instead I chose to use Reed Switches, which are essentially magnets that when you get close in proximity throw an electromagnetic field thereby becoming a switch with open or closed values. ( high/low | 0/1)

Step 5: The Chicken Door Motor

Picture of The Chicken Door Motor

Note: for a nicer view of the images, parts, diagrams and code, please visit:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

I chose a 25 RPM model, but you can certainly buy a different speed (just not *too* fast)

That main images is the motor I purchased. Here’s a saved search of a DC 24V 25 RPM 6mm Dia Shaft Magnetic Gearbox Electric Motor 37mm at Amazon

Step 6: The Chicken Door Installation

Picture of The Chicken Door Installation

Note: for a nicer view of the images, parts, diagrams and code, please visit:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

Step 7: Parts Used for the Arduino Automated Chicken Door

Picture of Parts Used for the Arduino Automated Chicken Door

Note: for a nicer view of the images, parts, diagrams and code, please visit:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

(my affiliate links)


Arduino MEGA 2560 Board R3 - by Arduino

(The Arduino Micro Controller to control the entire coop, including the door)

NEOMART L298N Stepper Motor Driver Controller Board Module - by Tontec

(The board that controls the motor)

DFGB37RG-136i Cylinder Shape DC 24V Speed 20 RPM Geared Motor - by Amico

The motor it self (make sure to pick a motor that isn't too fast. I chose the 20rpm model)

White Inbuilt Type Alarm Contacts Door Window Reed Switch - by Amico

(The Reed Switches (magnetic) which signals when to start/top the motor)

20pcs Photo Light Sensitive Resistor Photoresistor Optoresistor 5mm GM5539 5539 - by sunkee-E

(The Photocell that continually reads light levels. In this project, it's instructed to read ever 10mins)

10k Ohm Resistors - 1/4 Watt - 5% - 10K (25 Pieces) - by E-Projects

(10k resistors for the photocell and the reed switches - refer to wiring diagram)

BB830 Solderless Plug-in BreadBoard, 830 tie-points, 4 power rails - by BusBoard Prototype Systems

(To connect all devices and wiring. Tip: apply hot glue to wired connections on breadboard once set)

Polycom SoundPoint IP Universal AC Power Supply 24V DC - by Polycom Inc.

(power supply for 24v motor)

Wall Adapter Power Supply - 9V DC 650mA - by NKC Electronics

(power supply for arduino)

Acrylic Sheet, Transparent Clear, 0.08" Thickness, 12" Width, 24" Length - by Small Parts

(To cover door's internal workings...prevents dust, shavings, feathers, etc.)

Step 8: Chicken Coop Door Status LED

Picture of Chicken Coop Door Status LED

I wanted to give myself a quickie visual aid on the exterior of the coop so I could just take a peek outside and see if the coop door was open or closed.

Pretty simple:

I just used 2 LED (1- red, 1- green) and inserted them into the little globe of one of my extra motion sensors. Filled it with silicone and installed on the exterior of the coop:

Drilled 3/4" hole

Chiseled out the square part edge

Wired it up

Coded it up

Voila... insta-visual aid!

Arduino Chicken Coop Door LEDs Status:

Green: indicating the door is closed and chickens are safely inside. This is what I see when I look outside at the coop.

Red: indicating danger: the door is open and chickens are out.

Red: (flashing) indicating danger: the door is stuck and open. Essentially, the code checks to see if both topSwitch and bottomSwitch circ

Arduino chicken coop door status LED (red, indicating danger: the door is open and chickens are out)

uits are open and if so, blink.

Step 9: Wiring Diagram for the Automatic Chicken Coop Door

Picture of Wiring Diagram for the Automatic Chicken Coop Door

Note: for a nicer view of the images, parts, diagrams and code, please visit:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

Notes about wiring of the L298N Stepper Motor Driver Controller Board Module to the Motor:

The board is indeed the l298n (the one in the pic might look different b/c i broke a couple of them while testing – but it’s definitely the same model… sometimes suppliers send the same product but with different layouts)


There are actually 8 wires in total to make the board/motor work (I used only 1 motor – motor b)

On mine:

5v (from arduino)

gnd (from arduino)

enab (to enable the motor b)

int1 (direction 1 – up)

int2 (direction2 – down)

24 v in to l298n board (vms)

24v gnd in to l298n board (gnd)

motor b out + (24 volts to motor)

motor b out – (gnd)

Here’s a closeup of the fritzing diagram:http://davenaves.com/blog/wp-content/uploads/Arduino-Automatic-Chicken-Coop-Door-Fritzing-Project1-1024×997.png

Hope it helps

Step 10: The Arduino Code for the Automatic Chicken Coop Door

Picture of The Arduino Code for the Automatic Chicken Coop Door

Note: for a nicer view of the images, parts, diagrams and code, please visit:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

Insider info
To hopefully save you some time, I’ll let you in on the trick that FINALLY got this door to work with the light levels, debouncing the switches and *the chickens*. (as you’ll see in the code) Check the light levels every 10 minutes to avoid the readings bouncing back and forth between dark/twilight/light during those dawn/dusk minutes. Then, when “dark” is reached (for me i chose >= 0 && <= 3 based on when my chickens actually went & stayed in the coop) enable motor dir down > debounce the switches > stop. Then do the opposite for morning. I’m sure there are different, maybe more efficient methods, but this code has been running flawlessly for a while now and I’m feeling confident enough to go out at night without worrying about predators. Although I still somehow find a reason to check the ChickenCam from time to time. (currently waiting for my new servo motors and night vision web cam to arrive in the mail)

// libraries
<p>// libraries<br> 
</p><p>#include < SimpleTimer.h >    // load the SimpleTimer library to make timers, instead of delays & too many millis statements<br>  #include < OneWire.h >        // load the onewire library</p>/*
(before running the sketch, remove spaces before and after the above ">" "<" characters -  the instructables editor wouldn't publish the includes unless i added those spaces)
*/
 
/*
* Copyright 2013, David Naves (http://daveworks.net, <a rel="nofollow"> http://davenaves.com)
</a>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 
* 02110-1301, USA. 
 
*/
 
 /*
* I'm hoping that if you use/modify this code, you will share your
* coop project with me and the world (pictures, whatever)
* I'm big on sharing.
* Cheers,
* //D
*/
 
//pins
  const int photocellPin = A0;                 // photocell connected to analog 0  
  const int enableCoopDoorMotorB = 7;          // enable motor b - pin 7
  const int directionCloseCoopDoorMotorB = 8;  // direction close motor b - pin 8
  const int directionOpenCoopDoorMotorB = 9;   // direction open motor b - pin 9
  const int bottomSwitchPin = 26;              // bottom switch is connected to pin 26
  const int topSwitchPin = 27;                 // top switch is connected to pin 27
 
// vars
 
// photocell
  int photocellReading;                        // analog reading of the photocel
  int photocellReadingLevel;                   // photocel reading levels (dark, twilight, light)
 
// reed switches top and bottom of coop door
 
// top switch
 
  int topSwitchPinVal;                   // top switch var for reading the pin status
  int topSwitchPinVal2;                  // top switch var for reading the pin delay/debounce status
  int topSwitchState;                    // top switch var for to hold the switch state
 
// bottom switch
 
  int bottomSwitchPinVal;                // bottom switch var for reading the pin status
  int bottomSwitchPinVal2;               // bottom switch var for reading the pin delay/debounce status
  int bottomSwitchState;                 // bottom switch var for to hold the switch state
 
// just need 1 SimpleTimer object
  SimpleTimer coopTimer;
// ************************************** the setup **************************************
 
void setup(void) {
  Serial.begin(9600);
 
// welcome message
  Serial.println(" Checking doCoopDoor: every 10 minutes for light levels to open or close door");
  Serial.println();
 
// coop door  
 
// coop door motor
  pinMode (enableCoopDoorMotorB, OUTPUT);            // enable motor pin = output
  pinMode (directionCloseCoopDoorMotorB, OUTPUT);    // motor close direction pin = output
  pinMode (directionOpenCoopDoorMotorB, OUTPUT);     // motor open direction pin = output
 
// coop door switches
// bottom switch
  pinMode(bottomSwitchPin, INPUT);                   // set bottom switch pin as input
  digitalWrite(bottomSwitchPin, HIGH);               // activate bottom switch resistor
 
// top switch
  pinMode(topSwitchPin, INPUT);                      // set top switch pin as input
  digitalWrite(topSwitchPin, HIGH);                  // activate top switch resistor  
 
  // timed actions setup
  coopTimer.setInterval(600000, readPhotoCell);      // read the photocell every 10 minutes
 
}
 
// functions
 
// operate the coop door
 
// photocel to read levels of exterior light
 
 void readPhotoCell() { // function to be called repeatedly - per cooptimer set in setup
 
    photocellReading = analogRead(photocellPin);
      Serial.print(" Photocel Analog Reading = ");

      Serial.println(photocellReading);
 
//  set photocel threshholds
        if (photocellReading >= 0 && photocellReading <= 3) {
        photocellReadingLevel = '1';
        Serial.print(" Photocel Reading Level:");
        Serial.println(" - Dark");
      }  else if (photocellReading  >= 4 && photocellReading <= 120){
         photocellReadingLevel = '2';
         Serial.print(" Photocel Reading Level:");
         Serial.println(" - Twilight");
      }  else if (photocellReading  >= 125 ) {
         photocellReadingLevel = '3';
         Serial.print(" Photocel Reading Level:");
         Serial.println(" - Light");
       }
     }
 
//debounce bottom reed switch
 
  void debounceBottomReedSwitch() { 
 
    //debounce bottom reed switch
    bottomSwitchPinVal = digitalRead(bottomSwitchPin);        // read input value and store it in val
    delay(10);
    bottomSwitchPinVal2 = digitalRead(bottomSwitchPin);       // read input value again to check or bounce
 
      if (bottomSwitchPinVal == bottomSwitchPinVal2) {        // make sure we got 2 consistant readings!
        if (bottomSwitchPinVal != bottomSwitchState) {        // the switch state has changed!
          bottomSwitchState = bottomSwitchPinVal;
        }
        Serial.print (" Bottom Switch Value: ");             // display "Bottom Switch Value:" 
        Serial.println(digitalRead(bottomSwitchPin));        // display current value of bottom switch;
      }
    }
 
 // debounce top reed switch
  void debounceTopReedSwitch() {
 
    topSwitchPinVal = digitalRead(topSwitchPin);               // read input value and store it in val
    delay(10);
    topSwitchPinVal2 = digitalRead(topSwitchPin);              // read input value again to check or bounce
 
      if (topSwitchPinVal == topSwitchPinVal2) {               // make sure we got 2 consistant readings!
        if (topSwitchPinVal != topSwitchState) {               // the button state has changed!
          topSwitchState = topSwitchPinVal;
        }
        Serial.print (" Top Switch Value: ");                // display "Bottom Switch Value:" 
        Serial.println(digitalRead(topSwitchPin));           // display current value of bottom switch;
      }
    }
 
// stop the coop door motor
  void stopCoopDoorMotorB(){
    digitalWrite (directionCloseCoopDoorMotorB, LOW);        // turn off motor close direction
    digitalWrite (directionOpenCoopDoorMotorB, LOW);         // turn on motor open direction
    analogWrite (enableCoopDoorMotorB, 0);                   // enable motor, 0 speed
  }
 
// close the coop door motor (motor dir close = clockwise) 
  void closeCoopDoorMotorB() {  
    digitalWrite (directionCloseCoopDoorMotorB, HIGH);       // turn on motor close direction
    digitalWrite (directionOpenCoopDoorMotorB, LOW);         // turn off motor open direction
    analogWrite (enableCoopDoorMotorB, 255);                 // enable motor, full speed 
      if (bottomSwitchPinVal == 0) {                         // if bottom reed switch circuit is closed
        stopCoopDoorMotorB();
        Serial.print(" Coop Door Closed - no danger");
      }
    }
 
  // open the coop door (motor dir open = counter-clockwise)
  void openCoopDoorMotorB() { 
    digitalWrite(directionCloseCoopDoorMotorB, LOW);    // turn off motor close direction
    digitalWrite(directionOpenCoopDoorMotorB, HIGH);    // turn on motor open direction
      analogWrite(enableCoopDoorMotorB, 255);           // enable motor, full speed
      if (topSwitchPinVal == 0) {                       // if top reed switch circuit is closed
          stopCoopDoorMotorB();
          Serial.print(" Coop Door open - danger!");
      }
    }
 
  void doCoopDoor(){
 
      if (photocellReadingLevel  == '1') {              // if it's dark
        if (photocellReadingLevel != '2') {             // if it's not twilight
          if (photocellReadingLevel != '3') {           // if it's not light 
            debounceTopReedSwitch();                    // read and debounce the switches
            debounceBottomReedSwitch();
            closeCoopDoorMotorB();                      // close the door
          }
        }
      } 
       if (photocellReadingLevel  == '3') {             // if it's light
        if (photocellReadingLevel != '2') {             // if it's not twilight
          if (photocellReadingLevel != '1') {           // if it's not dark 
            debounceTopReedSwitch();                    // read and debounce the switches
            debounceBottomReedSwitch();
            openCoopDoorMotorB();                       // Open the door
          }
        }
      }
    }
 
// ************************************** the loop **************************************
void loop() {
  //  polling occurs
  coopTimer.run();
  doCoopDoor();
 
}

Lessons Learned

What I've learned about the door, Arduino, light and construction:
  • Best to check the light levels every 10 minutes to avoid the readings bouncing back and forth between dark/twilight/light during those dawn/dusk minutes
  • Test your door with your chickens to see if any of them like to hang outside after hours
  • Testing the actual light values outside is very important (many variables involved: light from neighbor's house, clouds, internal/external coop lights etc.)
  • Debouncing of your switches within your Arduino code is important (door will jump around and fail as electronic readings vary greatly by the millisecond)
  • Reach out for help on the Arduino Forums before pulling out your hair. (be nice, do your homework and ask very specific questions)
  • I changed from micro-switches to reed switches (magnets) because I didn't want the mechanics of the micro-switches to fail over time
What I've learned about the chickens:
  • Keeping on a light within the coop can keep chickens outside longer (I think b/c the ambient light shines outside) And that's important when it comes to automating this door, so they won't get accidentally locked out.
  • They can jump and fly (high and far)
  • They love to roost in safety at night, but want nothing more than to get OUT as soon as it's light out

Comments

BenjaminB41 (author)2017-02-23

Can anyone help me, what should I do to solve this problem?

dhnaves (author)BenjaminB412017-02-23

Hi Benjamin,

Read the error ~very~ closely... it tells you exactly what's wrong. (one of the beauties of Arduino)

This is also one of the requirements within DIY. (getting frustrated with the errors and doing some research to fix - We all do!) ;^ )

And to be a little helpful, here's a clue after you've read the error:
http://playground.arduino.cc/Code/SimpleTimer

Cheers,
//D

actuonix (author)2016-12-22

This is an awesome project! For those who may want something a little less involved, I think you could accomplish a similar effect with this setup. Though it's based on light rather than a clock.

https://www.youtube.com/watch?v=mp6cbTtiQzU

dhnaves (author)actuonix2016-12-23

Thanks for the vid..

Yeah, actually if you were to watch the last video I created, (https://www.youtube.com/watch?v=1qq0KlYfJbo&t=308s) this is exactly what I used (photo resistors) and not Timelord as I mentioned in one of the other vids

Cheers,
//D

actuonix (author)dhnaves2016-12-25

Missed that one! Fantastic job on the coop!

JoeW98 (author)2016-08-27

This is a great tutorial I am in the process of building my coop now. Mine wont be as pretty as yours because I am on a real tight budget so I am building it with whatever scrap material I find and people give me. But it will actually be nice I think for a Junkyard build LOL. My chickens when they were smaller had a smaller cage and like clock work every night same time the would automatically go in but they started to get bigger and I think a little upset with my tardiness to let them out, Sometimes it would be almost 9 am before I got up or around to letting them out. and they were not happy LOL. So I tried making a bigger cage but they seemed to just hate it and never would go in. Probably because same issue me not letting them out soon enough. So about a few months ago they started sleeping on my patio furniture and I had to chase each one down every night to put in there cage. because they just destroyed the furniture with all the pooping they do. I swear how can suck a small animal poop so much they must have one small hose from the stomach to but or something. So Now I got all the materials together motor H bridge motion detectors ect nice shelf I got for free that makes a perfect coop for them to rest in nice and wide and high off the ground. Anyway so since I banned them from ever comming on to my patio again with a fence and few squirts from the hose every time they try to get on it, and even though I just started on the coup 2 days ago and almost finished they automatically went into the coup tonight. Just gotta let them out early and get this program up and running for the auto doors. But I am gonna try to make a few changes I am gonna skip the Fan and Heater don't need them winters are warm summers are hot and a fan does nothing but make it hotter. I have plenty of shade around the yard and a mist-afire I turn on for them to cool of in the day. I also plan to make the visual check of the temperature ect wireless. I prefer to see what the temp is outside from the comforts of my AC LOL, So I have a NRF2401L transmitters I think might work for that , or 433khz transmitters and receiver that I know will work.and is way easier to get programmed and does not have power issues like the NRF does but on the other hand the 433 does not communicate like a Network. because I have other Ideals I would like to try around the house eventually and I would like to be able to monitor them or control them from one spot. So that is gonna be a challenge. I've only been playing around with Arduino for about 4 months now so I am like a 3 year old learning to speak I have learned to say yes and no but man I am a long ways from forming a sentence if you know what I mean LOL But you really have help me get pointed into the right direction and I thank you for that. If I mange to get it all working like I want I will be glad to share the Code with you. Thanks

grasmachien (author)2015-01-27

WAW! I absolutely love your project (and the way you explained it, you would be the greatest teacher ever, thanks!). I'll try to build it, but my chickens are a bit chalenging: they like to hang out in front of their door at night. In fact, this is what happens: one goes in, and stays right in front of the door opening (they always sleep on the floor). The others nicely line up, waiting for the first one to move (which Madame refuses of course). After a while, it gets too dark for them to see anything, and they end up sleeping in front of their coop. So I often have to push them all through the door opening before closing it. So, I'm thinking of adding something (PIR? does that detect fluffy creatures?) indicating chicken presence in front of the door. I don't want the door to automatically open again when that is the case, because I don't want predators to trigger the system. So maybe I'll just add a warning light to indicate I have to go rescue them? Or I could leave the door open as long as there are chickens in front of it? Or leave a light on in their coop as long as they're not all indoors? Has anyone perhaps got a better idea or any experience? Perhaps a way to detect how many chickens are actually IN the coop?

dhnaves (author)grasmachien2015-01-27

howdy!

thanks for the kind words... i really appreciate it. =)

great notes...

yes, i had that problem for a while as well. (door blocking) and was thinking about some of those very possibilities. but ultimately, it has worked out. what i actually did was install star lights on the interior of the coop (no laughing... they were my kids' and they outgrew them.. and i can't throw anything away when it comes to possibly going in the coop) =)

Here's a pic:
http://goo.gl/MDSTVW

Here's a live shot. (i pointed the camera up - looks best at night)
http://davenaves.com/blog/live-chicken-cam/

anyway, the reason for *these* lights is they throw enough light to be of interest from the outside to go in the coop, but not enough light to throw out of the coop, giving them a reason to stay outside past dusk. (plus it doesn't push much heat - i have heat handled within another Arduino project) ;^ )

i've just written the code to turn off the lights the second the door closes, (via the bottom reed switch) but haven't had time to install/test it) as soon as i do, i'll post it within my site: http://davenaves.com

thanks again for taking the time to comment... makes it worth it for me to connect with fellow chicken nerds. =)

cheers!

grasmachien (author)dhnaves2015-01-28

The little lights are a good idea indeed! I have some old led christmas lights lying around, I'll try with that. I don't have electricity in the coop though, so I'll have to hook everything on a battery. Let's hope the whole thing doesn't drain my batteries in no time. They'll indeed have to be switched of as soon as the door is closed. I love the webcam too! It's a good way to see whether all ladies are inside. Right now, we are often shining around in our own garden with a flashlight, to be sure we didn't miss one. The neighbours probably thinkwe're having some mental issues... :-)

KoenigB (author)grasmachien2016-05-17

Im looking to build this project but need this to run on battery power. Did you have any success with Batteries ? or battery life ?

dthomasjr2me made it! (author)2016-05-07

Dave,

Tried to build and program exactly as you had and failed. I put that on me. This was my first ever attempt to use an Arduino, and first ever attempt to really use C++.

I had some of the same problems with the reed switches/photocell readings as others have commented. Went in a totally different direction, and used most of your code to control door opening and closing with a real time clock. Finally got some success! While I probably re-invented the wheel, I learned a lot along the way. So, it was time well spent.

I think I know why some people are having trouble with getting the motor to stop.
In “closeCoopDoorMotorB()” you have “if (bottomSwichPinVal == 0)”
and
“openCoopDoorMotorB()” you have “if (topSwitchPinVal == 0)”
I’m a noob. But, shouldn’t these values to a digital pin be “LOW” instead of “0”?

I changed the statement to “if (digitalRead(bottomSwitchPin) == LOW)” and if (digitalRead(topSwitchPin) == LOW) respectively. I know that this would negate how you debounced the reed switches, but I also totally dropped the debouncing of the reed switches, and things seem to be working. Besides, I figured that a false value would be negated the next loop cycle anyway.

I’ll post the altered code below (with lots of notes), for anyone who want to try this with a real time clock

// This code and associated libraries are running on an Arduino MEGA 2560 purchased from Amazon

// ARDUINO A000067 DEV BRD, ATMEGA2560, ARDUINO MEGA 2560 R3

// https://www.amazon.com/gp/product/B0046AMGW0/ref=...

//

// Most of this code and much of the component build is based on the following sources:

// http://davenaves.com/blog/interests-projects/chic...

// https://www.instructables.com/id/Automatic-Chicken...

// Thanks Dave, you were the inspiration!

// However, I had to go to an real time clock (RTC) because I just couldn't get the photocell readings right :(

// It may have been getting the photocell reading delay just right that threw me...

// I'm also too much of a noob to get Dave's "debounce" to work. I'll work on it. But, it doesn't seem to be necessary???

// Used Dave's wiring diagram w/o photocell for reed switches and step motor

// http://davenaves.com/blog/wp-content/uploads/Ardu...

//

// DS3231 RTC codes are thanks to library and examples by Moja Sodaq //https://github.com/SodaqMoja/Sodaq_DS3231

// There is a ton of libraries out there. Some are easier to get the time from. But, found this one to be the most "useable".

// Date and time functions using RX8025 RTC connected via I2C and Wire lib

// Used a Donop DS3231 AT24C32 IIC module precision Real time clock memory module Arduino from Amazon

// https://www.amazon.com/gp/product/B00HCB7VYS/ref=...

// wiring: https://cdn.instructables.com/FGZ/INFJ/HIXCJMB0/FG...

// Note: on the MEGA 2560 SDA is pin 20 and SCL is 21

//

// I also used a RioRand® LCD Module for Arduino 20 x 4, White on Blue from Amazon

// I need four lines for all of the feedback I want. I don't like the serial monitor that comes with the Arduino software.

// https://www.amazon.com/gp/product/B00GZ6GK7A/ref=...

// wiring: http://www.learningaboutelectronics.com/images/Ar...

#include <Wire.h> //Included with Arduino

#include "Sodaq_DS3231.h" //https://github.com/SodaqMoja/Sodaq_DS3231

char weekDay[][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

#include <LiquidCrystal.h>

// Init the LCD

LiquidCrystal lcd(12,11,5,4,3,2);

// variables

// temperature chip i/o

//const int photocellPin = A0; // photocell connected to analog 0

const int enableCoopDoorMotorB = 7; // enable motor b - pin 7

const int directionCloseCoopDoorMotorB = 8; // direction close motor b - pin 8

const int directionOpenCoopDoorMotorB = 9; // direction open motor b - pin 9

const int bottomSwitchPin = 26; // bottom switch is connected to pin 26

const int topSwitchPin = 27; // top switch is connected to pin 27

const int coopDoorOpenLed = 40; // led set to digital pin 40

const int coopDoorClosedLed = 41; // led set to digital pin 41

// Time Settings

int integerTime; // will need to take RTC reading and converted to an integer

int whatTime; // what time of day is it? too early (1), too late (2), just right, egg time (3)

int openTime = 600; // time to open door - 24 hour clock format, do not use ":"

int closeTime = 2200; // time to close door - 24 hour clock format, do not use ":"

//***************************The Set Up - Runs Once********************************

void setup (void)

{

Serial.begin(9600);

Wire.begin();

rtc.begin();

lcd.begin(20,4); // set LCD columns and rows

// coop door

// coop door motor

pinMode (enableCoopDoorMotorB, OUTPUT); // enable motor pin = output

pinMode (directionCloseCoopDoorMotorB, OUTPUT); // motor close direction pin = output

pinMode (directionOpenCoopDoorMotorB, OUTPUT); // motor open direction pin = output

// coop door leds

pinMode (coopDoorOpenLed, OUTPUT); // enable coopDoorOpenLed = output

pinMode (coopDoorClosedLed, OUTPUT); // enable coopDoorClosedLed = output

digitalWrite(coopDoorClosedLed, LOW);

digitalWrite(coopDoorOpenLed, LOW);

// coop door switches

// bottom switch

pinMode(bottomSwitchPin, INPUT); // set bottom switch pin as input

digitalWrite(bottomSwitchPin, HIGH); // activate bottom switch resistor

// top switch

pinMode(topSwitchPin, INPUT); // set top switch pin as input

digitalWrite(topSwitchPin, HIGH); // activate top switch resistor

}

uint32_t old_ts; // ??? from Sodaq RTC "Now" sample. Purpose to be investigated...

//***********************************************Functions***************************************************

void doClock() { // All DS3231 RTC functions. This replaces photocell readings.

//DS3231 RTC information

DateTime now = rtc.now(); //get the current date-time

uint32_t ts = now.getEpoch();

if (old_ts == 0 || old_ts != ts) {

old_ts = ts;

}

rtc.convertTemperature(); //convert current temperature into registers

//Date time and temp to LCD Display

lcd.clear();

lcd.setCursor(0, 0);

lcd.print("Date: ");

lcd.print(weekDay[now.dayOfWeek()]);

lcd.print(", ");

lcd.print(now.month(), DEC);

lcd.print("/");

lcd.print(now.date(), DEC);

lcd.print("/");

lcd.print(now.year(), DEC);

lcd.setCursor(0, 1);

lcd.print("Time: ");

lcd.print(now.hour(), DEC);

lcd.print(":");

lcd.print(now.minute(), DEC);

lcd.print(":");

lcd.print(now.second(), DEC);

lcd.setCursor(0, 2);

lcd.print("RTC Temp: ");

lcd.print(rtc.getTemperature());

lcd.print(" C");

// convert RTC time to integer because you can't compare a string!

integerTime = ((now.hour()*100) + now.minute());

// determine "whatTime" - modification of Dave's "doReadPhotoCell()". Modified to be simple. No need for 10 minute delay.

// what time of day is it? too early (1), too late(2), just right (3, egg time)

if (integerTime < openTime){

whatTime = 1; // too early to open

}

else if (integerTime >= closeTime){

whatTime = 2; // to late to be open

}

else if ((integerTime >= openTime) && (integerTime < closeTime)){

whatTime = 3; // it's time to open

}

}

// stop the coop door motor

void stopCoopDoorMotorB() {

digitalWrite (directionCloseCoopDoorMotorB, LOW); // turn off motor close direction

digitalWrite (directionOpenCoopDoorMotorB, LOW); // turn on motor open direction

analogWrite (enableCoopDoorMotorB, 0); // enable motor, 0 speed

}

// close the coop door motor - Changed Dave's reed switch readings from 1/0 to HIGH/LOW

void closeCoopDoorMotorB() {

if (digitalRead(bottomSwitchPin) == LOW) { // if bottom reed switch circuit is open

digitalWrite (directionCloseCoopDoorMotorB, HIGH); // turn on motor close direction

digitalWrite (directionOpenCoopDoorMotorB, LOW); // turn off motor open direction

analogWrite (enableCoopDoorMotorB, 255); // enable motor, full speed

lcd.setCursor(0, 3); // lcd message

lcd.print(" Door Closing ");

}

if (digitalRead(bottomSwitchPin) == HIGH) { // if bottom reed switch circuit is closed

stopCoopDoorMotorB(); // stop the motor

lcd.setCursor(0, 3); // lcd message

lcd.print(" Door Closed ");

digitalWrite(coopDoorClosedLed, HIGH); // turn on door closed led

digitalWrite(coopDoorOpenLed, LOW); // turn off door open led

}

}

// open the coop door - Changed Dave's reed switch readings from "1/0" to "HIGH/LOW"

void openCoopDoorMotorB() {

if (digitalRead(topSwitchPin) == LOW) { // if top reed switch is open

digitalWrite(directionCloseCoopDoorMotorB, LOW); // turn off motor close direction

digitalWrite(directionOpenCoopDoorMotorB, HIGH); // turn on motor open direction

analogWrite(enableCoopDoorMotorB, 255); // enable motor, full speed

lcd.setCursor(0, 3); // lcd message

lcd.print(" Door Opening ");

}

if (digitalRead(topSwitchPin) == HIGH) { // if top reed switch circuit is closed

stopCoopDoorMotorB(); // stop the motor

lcd.setCursor(0, 3); // lcd message

lcd.print(" Door Open ");

digitalWrite(coopDoorClosedLed, LOW); // turn off door open led

digitalWrite(coopDoorOpenLed, HIGH); // turn on door open led

}

}

// do the coop door "whatTime" replaces Dave's photocell readings, also changed (simplified for me) some of the logic

void doCoopDoor() {

if ((whatTime == 1) || (whatTime == 2)) { // if it's "too early" or "too late"

// debounceTopReedSwitch(); // read and debounce the switches

// debounceBottomReedSwitch(); //not ready for this, disabled.

closeCoopDoorMotorB(); // close the door

}

if (whatTime == 3) { // if it's "egg time"

// debounceTopReedSwitch(); // read and debounce the switches

// debounceBottomReedSwitch(); //not ready for this, disabled.

openCoopDoorMotorB(); // Open the door

}

}

//******************************************The loop*****************************************

void loop() {

doClock();

doCoopDoor();

}

dhnaves (author)dthomasjr2me2016-05-12

Hi Don,

Thanks for the questions/comments and code. (I'm pasting in the same answers from the blog post comments)

For me, debouncing was essential. AND the light readings as I inserted them had to be done, b/c right around dusk and dawn, the light readings were all over the place, thereby giving me completely unreliable readings by the millisecond (and stuttering the door… even making it jump ahead and jamming) So I delayed the readings, made sure the readings were consistently either dark or light (and nowhere in between) and it hasn’t skipped a beat in years.

But if your stuff is working… awesome!

Cheers,
//D

P.S. Here's a direct link to a zipped up .ino file, in hopes to avoid copy/paste issues:

http://davenaves.com/blog/wp-content/uploads/Dave_Naves_Chicken_Coop_Controller.zip

PeterRP (author)2016-04-21

Excellent tutorial! I will try making this for our chickens in the near future!

dhnaves (author)PeterRP2016-04-21

Hey thanks. Peter... I'd love to see some pictures when you're done!

Cheers!

robbotherobot (author)2016-01-25

Hi Dave, nice project.

I am well down the physical production of the hardware connections. Can you advise me as to why you have 10k resistors in series with the micro switch for both open and shut switches. I have read in other places where they should be pull-up resistors to +5volts. Cheers John aka robbotherobot

dhnaves (author)robbotherobot2016-01-25

Hey John,

Thanks for the question... I feel honored you're taking the time to build this out.

As far as "in series" maybe I'm still too much of a resistor noob, but I don't think I did? (meaning they aren't daisy-chained) If you take a look at the Fritzing diagram,they are separate circuits.

Other folks have asked about what I used the 10k / 1/4 watt and I've been giving somewhat layman's answers. (mainly to protect the switch(es) based on what I calc'd the potential voltage would be) But there is a great answer within the comments section of my website from "fabelizer " on http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/ (he obviously knows his stuff when it comes to resistors and was nice enough to pick up where my knowledge left off)

Hope that helps at least a little.

Cheers,
//D

derek white (author)2015-05-24

G'day mate

Thanks for posting. As i'm a little techno illiterate, would it be possible to in corporate an electric window mechanism into the door and have that controlled via the arduino cpu. Where do you find out the capabilities and uses for arduino units?

Cheers Derek

dhnaves (author)derek white2015-05-25

G'day backatcha, Derek!

Absolutely possible to put in a mechanical window (great idea)

As far as capabilities, the sky is the limit. There are literally thousands of pages of ideas and projects available. (obviously this site, arduino.cc, youtube, etc etc) Here's just a quickie search for ya:
https://goo.gl/xWIsBc

Best of luck and thanks for writing in,

Cheers,
//D

caranicolelogan (author)2014-10-24

I am engineering a coop door just like this for school! It was would be extremely helpful to get some tips with the arduino setup. What technology to accompany the arduino were needed for this and how much would the overall cost be?

dhnaves (author)caranicolelogan2014-10-25

Howdy,

Thanks for the questions. I tried to be as thorough as possible within the Instructable with everything that was included in building the door. (including all parts, costs, ((parts are linked to Amazon)) code and assembly) If you read thoroughly (either here on Instructables,com or on my website http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/ (check all links within) you should be able to find every question answered,

Cheers,
//D

Robotix_au (author)2014-10-15

AWESOME!!!.... I just sub'd to your channel and I am going through your vids. I got chickens and I am pretty nifty with Arduino prototyping. However I am yet to build anything outdoor that is robust enough to last for months without tweaking and I am sure your vids will come in handy!

dhnaves (author)Robotix_au2014-10-15

hey, thanks much for the kind words... hope the info comes in handy.

i have more coming. (air/heat water feeders, alarms, etc) =)

cheers!

Robotix_au (author)dhnaves2014-10-16

Mate I look forward to it!

Mike6158 (author)2014-05-09

#include // load the SimpleTimer library to make timers, instead of delays & too many millis statements

#include

#include but there is nothing after #include?

dhnaves (author)Mike61582014-05-09

shoot...

thanks, mike... looks like the instructables html editor commented that part out. (and i didn't check closely enough - my bad) it should read:

// libraries

#include < SimpleTimer.h > // load the SimpleTimer library to make timers, instead of delays & too many millis statements
#include < OneWire.h >
(remove spaces before and after the "<" and ">")

here's a better view over here:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/

i'll try to see if there's a workaround to get that code in there. really appreciate you point that out.

cheers,
//d

Mike6158 (author)dhnaves2014-05-09

No worries. I checked out the link to your site after posting this and I found it. If I had thought before I typed I would've realized what was missing. Nice work and thanks.

dhnaves (author)Mike61582014-05-13

no prob... i appreciate that you found the commented code.

cheers!

and keep me posted with your coop project(s)

dufus2506 (author)2014-05-05

You know why a chicken coop has two doors?

Because if it had four doors, it would be a chicken sedan...

dhnaves (author)dufus25062014-05-07

aaaaaahahaha! snare/crash! =)

ejsilver26 (author)2014-05-03

Nicely done. I have a coop (and will be re-building it this summer), and I agree that going out and closing the door does put a cramp on the staying late anywhere. This would definitely solve that problem. I will still need to figure out something with the ducks (they don't always come back as early at the chickens). I might have to modify the system if I build one for them. Nice 'ible. I'll let you know if I use this when I re-build it.

dhnaves (author)ejsilver262014-05-03

hey, thanks for the kind words... much appreciated.

ducks... cool. i know nothing about them. do they roost as well? come in around dark? friendly with the chickens?

yes, please do share your re-build... would love to see it.

cheers,
//d

ejsilver26 (author)dhnaves2014-05-05

They don't really "roost", depending on the breed. Some do, some don't. Mainly they find something to hide in. They will come in, but I find my chickens are in well before the ducks. Sometimes I need to go and round them up to get them to go in. Yes, you can herd ducks. They are in the same coop as the chickens at the moment, but I plan to make them their own area (with pond/pool) and coop.

Smelter_uk (author)2014-05-05

Nice Instructable. I'm still new to using my Arduino, so could you show the wiring of the LCD for me and fellow newbies to see how it fits in with your gizmo and code ;-)

dhnaves (author)Smelter_uk2014-05-05

hey, thanks for the nice words!

yes, i am actually going to be doing a separate instructable for each of the components within el pollo palace. it's just going to take some effort on my part (fritzing diagrams can be fairly time consuming and i have many projects going on right now)

BUT the good news is, i have the code for the entire coop already published (with numbers referenced for the lcd within. starting at line 90) so in the meantime this might get you by:

http://davenaves.com/blog/interests-projects/chickens/arduino-chicken-coop-controller/

cheers,
//d

About This Instructable

43,753views

351favorites

Bio: About the Author: Hi, I'm Dave Naves. I'm a daddy, hubby and currently live in Auburn California with (1) wife, (2) children, (1 ... More »
More by dhnaves:Automatic Chicken Coop Door
Add instructable to: