Chicken Coop Arduino Controller
When I started my chicken coop, I knew I wanted it to be technically advanced, but I didn’t really want it to *look* too high tech, and not too “country” either. So I just went for it and I’m pretty happy with the results. Being the chicken nerd I am, I loved every phase of combining technology with building a chicken coop and raising chickens. (I actually don’t think I’ll ever want to stop adding to it b/c it’s just too fun) I mean, why shouldn’t technology keep them safer, more comfortable, and healthier? Ok, and why shouldn’t *I* have more fun with it? =)
What was the most important part for me (like most of us chicken owners) is keeping the chickens safe, especially at night. So for the automation part, it was all about the door. Predators are strong, sneaky and relentless critters, so you have to really get this door part right. After a while, you realize that one of the biggest pains is opening and closing the door every morning and evening. We chicken owners can’t go out to dinner without worrying whether or not a raccoon or a fox has been eyeballing them all day, waiting for the sun to go down to get into the coop to have *their* dinner. I also installed a chicken cam for a little added comfort.
The Build
coming soon…
Parts List
(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.)
- Arduino Mega 2560 R3
- Real time clock
- L298N Motor Driver Dual H-Bridge
- 16 x 2 LCD
- 5 pin din male and female connectors
- RCA male and female connectors
- 12 V cooling fan
- Wire ties
- Wire (yellow, read, black & green)
- Tie downs
- Box
- Shrink tubing
- Bread board
- Resistors
- Relays
- Velcro
- 9v power supply
- 12v power supply
- 24 volt power supply
- USB connector
- Cable labels
The Arduino Chicken Coop Code
[callout font_size=”13px” style=”limegreen”]
I’m hoping that if you use or modify my code or ideas, you will share *your* coop project with me and the world (pictures, whatever) I’m big on sharing.
Cheers,
//D
Download The Arduino Automated Chicken Coop Code (zipped)
[/callout]
// libraries #include// load the SimpleTimer library to make timers, instead of delays & too many millis statements #include // load the onewire library for thermometer // #include // load the servo library #include // load the liquid crystal library // print debug messages or not to serial const boolean SerialDisplay = false; /* * Copyright 2016, David Naves (http://daveworks.net, http://davenaves.com) * * 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, see */ /* * 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 assignments // temperature chip i/o const int photocellPin = A0; // photocell connected to analog 0 const int thermometer = 3; // thermometer DS18S20 on digital pin 3 const int relayHeat = 5; // heat lamp relay set to digital pin 5 const int relayFan = 6; // exhaust fan relay set to digital pin 6 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 // const int relayElectricFence = 43; // heat lamp relay set to digital pin 43 const int relayInteriorLight = 45; // interior lights relay set to digital pin 45 // variables // 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 // SimpleTimer objects SimpleTimer coopPhotoCellTimer; // debounce delay long lastDebounceTime = 0; long debounceDelay = 100; // temperature check delay long lastTempCheckTime = 0; long TempCheckDelay = 600000; // 10 minutes // interior lights twighlight delay long lastTwilightTime = 0; long TwilightDelay = 300000; // 5 minutes // temperature chip i/o OneWire ds(thermometer); // thermometer on digital pin 3 // chicken cam servo // Servo chickenCamServo; // servo object to control chickenCam // int chickenCamServoPos = 0; // chickenCamServoPosition var // lcd LiquidCrystal lcd(38, 37, 36, 32, 33, 34, 35); // lcd pin assignments int backLight = 13; // pin 13 controls backlight /* LCD Pin > arduino Pin lcd pin 1 VSS > gnd arduino pin lcd pin 2 VDD > +5v arduino pin lcd pin 3 VO(contrast) > 330 ohm resistor to gnd arduino pin lcd pin 4 RS arduino pin 38 lcd pin 5 R/W arduino pin 37 lcd pin 6 Enable arduino pin 36 lcd pin 7 - lcd pin 8 - lcd pin 9 - lcd pin 10 - lcd pin 11 (Data 4) > arduino pin 32 lcd pin 12 (Data 5) > arduino pin 33 lcd pin 13 (Data 6) > arduino pin 34 lcd pin 14 (Data 7) > arduino pin 35 lcd pin 15 Backlight + > arduino pin 13 (built-in resistor) lcd pin 16 Backlight > arduino gnd pin */ // ************************************** the setup ************************************** void setup(void) { Serial.begin(9600); // initialize serial port hardware // welcome message if(SerialDisplay){ Serial.println(" Processes running:"); Serial.println(" Timer readPhotoCell every 10 minutes - light levels: open or close door"); } // coop hvac pinMode(relayHeat, OUTPUT); //set heat lamp relay output pinMode(relayFan, OUTPUT); //set exhaust fan relay output // 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 // 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 // interior lights relay pinMode(relayInteriorLight, OUTPUT); digitalWrite(relayInteriorLight, HIGH); // electric fence relay // pinMode(relayElectricFence, OUTPUT); // set electric fence relay as output // timed actions setup coopPhotoCellTimer.setInterval(600000, readPhotoCell); // read the photocell every 10 minutes // servo for interior chicken web cam // chickenCamServo.attach(11); // chickenCamServo on pin 11 } // ************************************** functions ************************************** // coop hvac void doCoopHVACHeat() { float temperature = getTemp(); // create temperature variable float tempF = (temperature * 9.0)/ 5.0 + 32.0; // convert celcius to fahrenheit if(SerialDisplay){ Serial.print(" Coop Temperature:"); // print out coop temperature Serial.println(tempF); // print out the temperature } if ((millis() - lastTempCheckTime) > TempCheckDelay) { // check temperature every 10 minutes // if cold, turn on heat lamps if (tempF <= 40) { // if temp drops below 40F turn on heat lamp(s) relay digitalWrite(relayHeat, HIGH); } else if (tempF > 40) { digitalWrite(relayHeat, LOW); // if temp remains above 40F turn off heat lamp(s) relay } } } // if hot, turn on cooling fans void doCoopHVACCool() { float temperature = getTemp(); // create temperature variable float tempF = (temperature * 9.0)/ 5.0 + 32.0; // convert celcius to fahrenheit if(SerialDisplay){ Serial.print(" Coop Temperature:"); // print out coop temperature Serial.println(tempF); // print out the temperature } if ((millis() - lastTempCheckTime) > TempCheckDelay) { // check temperature every 10 minutes if (tempF >= 83) { // if temp rises above 85F turn on cooling fan(s) relay digitalWrite(relayFan, HIGH); } else if (tempF < 83) { digitalWrite(relayFan, LOW); } } } // credit: bildr.org/2011/07/ds18b20-arduino/ // DS18S20 digital thermometer stuff float getTemp(){ //returns the temperature from one DS18S20 in DEG Celsius byte data[12]; byte addr[8]; if ( !ds.search(addr)) { //no more sensors on chain, reset search ds.reset_search(); return -1000; } if ( OneWire::crc8( addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return -1000; } if ( addr[0] != 0x10 && addr[0] != 0x28) { Serial.print("Device is not recognized"); return -1000; } ds.reset(); ds.select(addr); ds.write(0x44,1); // start conversion, with parasite power on at the end byte present = ds.reset(); ds.select(addr); ds.write(0xBE); // Read Scratchpad for (int i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); } ds.reset_search(); byte MSB = data[1]; byte LSB = data[0]; float tempRead = ((MSB << 8) | LSB); //using two's compliment float TemperatureSum = tempRead / 16; return TemperatureSum; } // operate the coop door // photocel to read levels of exterior light void readPhotoCell() { // function to be called repeatedly - per coopPhotoCellTimer set in setup photocellReading = analogRead(photocellPin); if(SerialDisplay){ Serial.print(" Photocel Analog Reading = "); Serial.println(photocellReading); } // set photocel threshholds if (photocellReading >= 0 && photocellReading <= 3) { photocellReadingLevel = '1'; if(SerialDisplay){ Serial.print(" Photocel Reading Level:"); Serial.println(" - Dark"); } } else if (photocellReading >= 4 && photocellReading <= 120){ photocellReadingLevel = '2'; if(SerialDisplay){ Serial.print(" Photocel Reading Level:"); Serial.println(" - Twilight"); } } else if (photocellReading >= 125 ) { photocellReadingLevel = '3'; if(SerialDisplay){ 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); if ((millis() - lastDebounceTime) > debounceDelay) { // delay 10ms for consistent readings bottomSwitchPinVal2 = digitalRead(bottomSwitchPin); // read input value again to check or bounce if (bottomSwitchPinVal == bottomSwitchPinVal2) { // make sure we have 2 consistant readings if (bottomSwitchPinVal != bottomSwitchState) { // the switch state has changed! bottomSwitchState = bottomSwitchPinVal; } if(SerialDisplay){ 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); if ((millis() - lastDebounceTime) > debounceDelay) { // delay 10ms for consistent readings topSwitchPinVal2 = digitalRead(topSwitchPin); // read input value again to check or bounce if (topSwitchPinVal == topSwitchPinVal2) { // make sure we have 2 consistant readings if (topSwitchPinVal != topSwitchState) { // the button state has changed! topSwitchState = topSwitchPinVal; } if(SerialDisplay){ 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(); if(SerialDisplay){ 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(); if(SerialDisplay){ Serial.print(" Coop Door open - danger!"); } } } // blink coop door red led if door is stuck // blink CoopDoorLedOpen (red) // void doCoopDoorLedError(){ // digitalWrite (coopDoorOpenLed, HIGH); // blinks coopDoorOpenLed // } // coop door status: red if open, green if closed, blinking red if stuck void doCoopDoorLed() { if (bottomSwitchPinVal == 0) { // if bottom reed switch circuit is closed digitalWrite (coopDoorClosedLed, HIGH); // turns on coopDoorClosedLed (green) digitalWrite (coopDoorOpenLed, LOW); // turns off coopDoorOpenLed (red) } else if(topSwitchPinVal == 0) { // if top reed switch circuit is closed digitalWrite (coopDoorClosedLed, LOW); // turns off coopDoorClosedLed (green) digitalWrite (coopDoorOpenLed, HIGH); // turns on coopDoorOpenLed (red) } // else if (topSwitchPinVal != 0) && if (bottomSwitchPinVal != 0) { // if bottom and top reed switch circuits are open // doCoopDoorLedError(); // blink the coopDoorOpenLed // } // } else { digitalWrite (coopDoorClosedLed, LOW); // turns off coopDoorClosedLed (green) digitalWrite (coopDoorOpenLed, LOW); // turns off coopDoorOpenLed (red) } } // turn on interior lights at dusk and turn off after door shuts void doCoopInteriorLightDusk() { if ((millis() - lastTwilightTime) > TwilightDelay) { // delay 5 mins readPhotoCell(); bottomSwitchPinVal = digitalRead(bottomSwitchPin); if (bottomSwitchPinVal == 1 && photocellReading >= 4 && photocellReading <= 120) { // if bottom reed switch circuit is open and it's twilight digitalWrite (relayInteriorLight, HIGH); if (SerialDisplay) { Serial.println(" Interior Light: On"); } } else if (bottomSwitchPinVal == 0) { digitalWrite (relayInteriorLight, LOW); if (SerialDisplay) { Serial.println(" Interior Light: Off"); } } } } // do the coop door 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 } } } } // chickenCamServo /* void doChickenCamServo() { for (chickenCamServoPos = 0; chickenCamServoPos < 75; chickenCamServoPos += 1) { // turns servo 0 to 75 degrees; 1 degree at a time chickenCamServo.write(chickenCamServoPos); // read chickenCamServoPosition variable chickenCamServoPos } for(chickenCamServoPos = 75; chickenCamServoPos>=1; chickenCamServoPos-= 1){ // return from 75 degrees to 0 degrees; 1 degree at a time chickenCamServo.write(chickenCamServoPos); // read chickenCamServoPosition variable chickenCamServoPos } } */ // lcd void doLcdMsg() { float temperature = getTemp(); // create temperature variable float tempF = (temperature * 9.0)/ 5.0 + 32.0; // convert celcius to fahrenheit pinMode(backLight, OUTPUT); // backlight pin set as output digitalWrite(backLight, HIGH); // backlight on lcd.begin(16,2); // columns, rows lcd.clear(); // start with blank screen lcd.setCursor(0,0); // set cursor to column 0, row 0 lcd.print("Coop Temp:"); // show "Temp" lcd.print (tempF) ; // show temperature of interior coop lcd.print("F"); // show "F" lcd.setCursor(0,1); // set cursor to column 0, row 1 lcd.print("Coop Door:"); // show "Coop Door" if (bottomSwitchPinVal == 0) { // if coop door bottom switch is closed lcd.print("Closed"); // display "Closed" } else if (topSwitchPinVal == 0) { // if coop door bottom switch is open lcd.print("Open"); // display "Open" } } // ************************************** the loop ************************************** void loop() { coopPhotoCellTimer.run(); // timer for readPhotoCell doCoopHVACCool(); doCoopHVACHeat(); doCoopDoor(); // doChickenCamServo(); doCoopDoorLed(); doCoopInteriorLightDusk(); doLcdMsg(); }
The Wiring Diagram
(Fritzing)
coming soon…
Lessons Learned
coming soon…
With respect !!!
cheers, mate!
merci beaucoup je vais en fabriquer une
je vous tiens au courant
chris
merci, chris! =)
Love the setup Dave, well done!
I will attempt to get your code controlling another hen-house in Holland 😉
Just FYI for you or anyone respectfully copying your code;
Whilst copying your code, cheating my own way into a nice palace for the ladies, i found out the latest SimpleTimer download in the library does not match your code anymore. I copied one i found on the arduino site from 2018, which looks like it does work…
Great effort again, respect haha!
Thanks for the updates and respect!
Cheers
Got it running Dave, still fiddling a bit, but i’ve added the following:
RTC and RGB LED strip with an Artificial sundown, after 16.00 hours stopping at 22.00 hours.
The PSU of the RGB gets powered by the equasions: time / light and bottompinvalue. (Also keeping your bottom pin val in place so they enter the palace first)
Traffic light, to ensure the chicken know they are clear to move in and out, or if the door is moving. 😉 They are chicken, you need to keep them in line…
Fantastic!
Thanks for sharing… post some pics somewhere so we can all see. =)
Hey Dave,
I found your chicken coop controller a couple months ago and automated my new chicken coop with my version of your HW & SW design. I am new to Arduino coding so this was a fun experience. Some changes I made:
I added code for an IR remote so that I can open or close the door with the remote, or turn on or off the automatic door operations. This came in really handy when debugging the operation of the door mechanics and timing.
I hard coded the length of time for the open and close rather than check the state of door switches. I thought this was a lot simpler. Then I realized I had a design flaw. When a power outage occurs and the Arduino resets, the state of the door is not know. I added in a bottom switch to check the state of the door.
In the design process I had the help of a HW engineer who suggested that I do the debounce in hardware rather than in software. A 10mF capacitor inline with the resistor seems to do the trick.
Thanks for sharing your designs!
Tony
Thanks for the notes…
IR remote…. great idea!
The state of the door is set above the setup. =)
Great idea to do the debounce within the hardware.
Thanks for sharing!
//D
We have a project study and searched about smart chicken coop. I’m glad that I clicked your blog site, it’s really helpful. Thank you very much! You’re awesome.
Thank YOU!
Just was wondering if anyone has been able to work on a fritzing for the whole controller yet? I have been trying to read the code in the program to make everything up. And wondered doe it matter on the breadboard where they connect as long as they do connect somewhere
Awesome article! Quick question, the more I analyze the wiring, the more it looks like a lesser gauge than 20. For example, the yellow wire going into the breadboard looks l lot less than 20. I am going to build a near clone but with a raspberrypi. Also, can you include a link to the RCA female box adapter? The one from before is a 404.
Howdy,
The wire gauge is actually 18. And here’s a link to the rca female chassis mounts: https://amzn.to/32AdLf3
Thanks for writing in!
I am hoping to do something like this in the near future. I am curious if you have had any issues with the heater or cooling fan turning on and off frequently?
The thermostats I have worked with always have a hysteresis band between the high and low limits. Heat will come on at 36degs and turn off at 40degs, Fan will come on at 85degs and turn off at 80degs.
Great question… yeah, the fans constantly go on and off (at that threshold) Probably drives the chickens nuts… but they’re chickens. =)
Thanks for writing in.
//D
Hi Dave,
Your ACCC is really great, I love it. I am veterinary doctor and I want to build automated chicken coop at our backyard and this is really wonderfull.
I know that you don´t have enough time, but …Is it possible publish Fritzing Diagram, please?
Thank you much, best regards! Andrej, Bratislava, Slovakia.
Thanks for the kind words, Andrej… much appreciated.
Yeah, I plan on creating Fritzing Diagrams for everything, but as you said, I’m just wicked-busy. I’ll keep everyone posted. 😉
Cheers!
Very cool design! Thank you! A couple of questions:
1) did you elect to just use stranded wire (what approx. gauge) for wiring up the headers on the Arduino board? Or are those prefabbed yellow / red / black jumper wires?
2) Any recommendations on the project box used to house everything? Did you make that, or buy one?
3) I have 9 VDC 600 mA power supply, and yours calls for 650 mA. Does it matter, or do do you recommend I still get a 650 mA power supply?
Thanks for the questions, Matt.
Answers in order:
1) I didn’t use stranded wire, but solid (20 gauge) Stranded, you’ll be fighting it. I was doing a bunch of projects at the time and bought quite a bit of wire like this spool: https://amzn.to/2Vik5Tt but you can also just get 20g jumpers for just a few bucks.
2) Great question. I finally ended up gutting/cutting/sanding an organizer box (kinda like this: https://amzn.to/2E5yBXH) then velcro/hot glued the elements to it. Then I inserted the entire thing (with a few screws) within an electrical panel, which sat inside the added enclosure to the coop. (iow, a box within a box within a box) It might seem like overkill, but after it sits there for a while, you’ll notice the dust and spiderwebs appearing… none of which are good for micro-electronics. =)
Looking forward to seeing/hearing about your coop, Bro!
Hello Dave,
Thanks for all that you’ve posted here. You’ve drawn in another Chicken Guy, that wants to become more of a Chicken Geek… Haven’t pulled the trigger on buying supplies yet, but getting close. This would be my first Arduino project, kind of excited about that.
Curious if you ever moved your code to GitHub or if there is a “latest” with the work that Mark Cummins or others have done? (I did see the repo from Will Vincent but that hasn’t been updated in years)
I’m looking to start with the Chicken Door but eventually might put an IR camera in for counting the number of girls to make sure they all made it in for the night. Want to see if I can post data to the cloud to do processing there such as looking at the image to count chickens.
Thanks,
Kent
Hi Kent,
Welcome, fellow chicken nerd!
In short, no I haven’t moved the code to GitHub… I just keep the latest here. (haven’t touched it in some time, nor have I added any of the work others have posted)
I’m planning on building an El Pollo Palace 2 in the coming years when I have more time. (and a new house)
Looking forward to seeing what you do with your coop. Please make sure to ping me when you do.
Cheers,
//D
Thanks Dave. I’m sure I’ll look at some of the code but also have some ideas of my own. Starting with a lot of your design ideas such as using the reed switches. But I do have thoughts on those of moving towards a system that lets me know if the motor is blocked (up or down) to help see If something blocked before getting to the full stop position.
I purchased a few wifi, so it will be neat to see how much I automation I’ll be able to do there.
Here’s my initial goals, I’ll update as I’m moving through them and will try to use them as the documentation of things I learn:
https://trello.com/b/6OaImpKP/cloud-rooster
And I’ll be putting my code here:
https://github.com/kfehribach/roosterlife
Idea is that I’ll have the coop automated, pushing data to the cloud, and an app that views that data and can send commands to the coop.
Great ambitions and a couple hundred dollars of worth of stuff I’ve never messed with before.
We’ll see.
Awesome, Kent. Love it.
Yeah, the only thing I did with the door sticking was a visual cue with the leds outside the coop:
Red: Open/danger
Green: Closed/no danger
Flashing Red: Door stuck
Looking forward to seeing the finished product.
Thanks for sharing!
Greetings from Dawson Creek, BC (where the Alaska Highway starts).
Nice work. There are a bunch of things I plan to build, a chicken tractor is early. I’m hoping I can get some Chantecler fertilized eggs to start from. I see mods for the incubator, and I now have three MH1210w controllers for heating. Seed germinating box uses 1 for controlling E26 screw-in IR heating elements. I was planning on another for chicken brooder and more of those IR heating elements. The chicken tractor, dog house (when I get dog), beehives (where I live has tons of flowers and bees), horse/cow/pig shelters all look to be built like an aircraft (or surfboard): styrofoam core, a skin of 1/8 baltic birch, and glass/epoxy on top of that. The birch is partially there for looks, partially to give me something a screw could start in. But I think in general you drill an oversize hole, fill with epoxy, and then drill for what fastener you use. The boat industry calls it potting (among other things).
In any event, I plan to mount controllers and sensors in the foam core, with some kind of access (probably to the outside). I may not get things into my tractor to begin with, but maybe I can use some dimensioning information from your plans to put in spaces for future work.
I think semi-permanent and larger structures need to have “routers” (running OpenWRT) and using mesh networking. Some of my land is way beyond line of sight, and trees could be a problem now and in the future (I am planting an orchard and other stuff).
For beehives and dog houses, I think having microphones inside is useful. Beehives apparently develop different sounds if they are going to swarm (about 2 week head start). For a doghouse, I think you might be able to pick off the dog’s heart rate. Now you can monitor for stress in the dog’s life. Maybe you can measure body temperature and look for illness. If your birds tend to go to the same places in your chicken coop, you might be able to do similar things to monitor heart rate.
There seem to be half a dozen or so chemical sensors which get mentioned in the arduino literature. I don’t think any of these sensors is as specific for the target chemical as they are sold for. So, a combination of sensors might be able to pick off things like ammonia which might be of interest to chickens. But, if you need a neural network or something to get an “ammonia” signal out of a number of other sensors, that isn’t going to run on an arduino.
Oh well, I better get to reading more of your site. Spring will be here too soon, and then planning time gets scarce.
Keep your stick on the ice.
Love it… all of it!
Cheers,
//D
Hi David,
I completed the fritzing with LCD, relay modul and a rotary switch, so I can open or close the coop door by hand. The top and bottom switches are limiting the way of the door.
In your code I added some outputs for the limiting relays switching together with the Coop Door Leds.
To your Email address I send the PDF and the code.
Best bregards
Herbert Gramsch
Awesome… thank you again. You obviously understand the meaning of the phrase “Pay it Forward.” Please feel free to post links to your assets from this page. =)
Cheers!
Hi Dave,
is it possible to get the fritzing diagram?
Thx
Howdy,
Yeah, still haven’t had time to do the diagram for the entire controller. (only the door) Just too many hours of labor right now. But I will and once I do, I’ll post.
Cheers!
Hi, I found your site, and want to build the arduino Coop controller —found most of the parts etc—but where to find the box, size etc,wiring diagram etc—must something more u can offer even though not finished —–
or where could i find this information as there is much more to building and assembling the parts, wired together —like loading the software for the CPU and then your program etc—and testing it out….lots of questions as this project is not a slam dunk from the info given thus far —so looking for help, if any can be provided —retired and have 6 girls
wanting me to make them an automatic door open and closer,
Yep, since I’m NOT retired, I did as much as I could while providing a living for my fam. (as I still am) Maybe YOU could complete it and post for the world. (part of the fun)
//D
Hey richard,
Have you been able to complete the fritzing of the complete controller for the automation of the coop ?
Hi Dave..
may i have this project’s flowchart? can you send it to my email
thanks.. 🙂
Howdy,
I’ve only completed the Fritzing chart for the door so far… just too busy with work. I’m going to post to the site asap.
Thanks!
i was wondering what box you are using?
Hi Chris,
Sorry for the late reply… too many projects going on.
If you’re talking about the enclosure, as I mentioned within the article, I just grabbed a plastic organizer and removed the dividers (like this one: https://goo.gl/3hCdku), then sprayed it with truck bed lining spray. (https://goo.gl/3cqaPb)
Hope that helps,
//D
Hi All,
I guess there has been some issue with copy and pasting the code, so I zipped up
the latest clean .ino for you here
Hay David,
I sent you an email the other day. I know you like to post things here but it contained personal info. I can post the code here if you like. I attached it to my email. I am rewriting the code to effect a different type of control. I would really prefer you to call me number is in my email.
Hi Mark,
Thanks for sharing everything here… lot’s of awesome stuff!
I’ve just been soooo busy with my web dev biz… barely any time to even answer these comments. (doing the best I can) I just don’t have the time to get on the phone to talk chicken coop code. (plus it doesn’t help our chicken nerd community to keep it offline) =)
Hope you feel better soon, brother.
Cheers,
//D
I’m planning to start my coop next year. And I’m also new to Arduino. I got few things tested out so far but not a lot.
I’m having a error while compiling your code:
‘getTemp’ was not declared in this scope
I have the library installed :
#include
I don’t know where the problem come from..
Hi,
Sounds like you haven’t installed the OneWire library correctly. Make sure to study this carefully:
https://www.arduino.cc/en/Guide/Libraries
Hi again,
I found out with a friend that when we copy-paste the code, sometimes (depends on computer) some characters change.. So.. and this code was my very first I saw…
I added some stuff like a bypass to open or close the door resulting in the led to flash as a alarm so I don’t forget to remove the bypass. It will be usefull in case I have to clean the coop or move it.. or in the winter (quebec winter is cold usually) in the case of the winter, to avoid having the led to continiully flash, I will add another switch to remove the alarm. I will change that over time because some cold tempterature breed do enjoy getting out in the winter…
I may add a SD card to store data on it, the RTC will be very usefull for that. But later on..
And also, like you did with the deer determent, I also plan to add a sound that announce that the door will close shortly.. like at little school..
I’d like to add a second temperature probe to get the exterior temp. I don’t know where to start with that thing Onewire… it sounds very nice but I got to try to understand how to add an other sensor… Onewire sounds like magical to me but also like a monster.. LoL
But right now, since I don’t have the parts and the time, I’m doing my strawberry tower automatic waterer system…
Love your commments, thank you!
If you need it, here’s a direct link to to a clean copy of my code:
http://davenaves.com/blog/wp-content/uploads/Dave_Naves_Chicken_Coop_Controller.zip
Cheers!
I’m getting the exact same problem with the getTemp not declared in this scope…
“exit status 1
‘getTemp’ was not declared in this scope”
I don’t understand what this means… i thought we were declaring this as a variable at this point?
Is it possible they’ve updated the library and getTemp is called something else now? If so, how do we search for that or find out what the fix is? I’ve been googling this for several hours so far today without any hint of success.
any suggestions or insights would be much appreciated!
Thanks,
joe
Hi again, Joe,
See if this clean copy works for you… it may indeed be a simple issue of copy/pasting & weird characters.
http://davenaves.com/blog/wp-content/uploads/Dave_Naves_Chicken_Coop_Controller.zip
Hi Carol,
Please try this clean copy:
http://davenaves.com/blog/wp-content/uploads/Dave_Naves_Chicken_Coop_Controller.zip
Cheers!
This is AMAZING!!! Exactly what I am looking to accomplish, except way more elegant than my analog ideas… which i guess now means that I will be trying to learn all about everything you did and attempt to hack something together that works 🙂
So on that note, any suggestions for getting from zero electronics/computer/programming knowledge to automated chicken coop wizard in the shortest time possible? I was looking at Arduino starter kits and books online, but thought ideally i should look for a kit with components that I will use in the project. I see that you used a “Mega” board and I’m wondering if you would choose the same product again if you were starting today? Seems like Uno R3 boards are maybe newer? I have no idea what i’m talking about, but the question is basically, if you were starting this project today would you recommend any different components? and if so, what would they be? I really liked Will’s remote monitoring/controlling features and would love to incorporate those as well if that factors into which board you might recommend.
Thanks again and I can’t wait to see more!
Cheers,
Joe
Hi Joe,
Thanks for the kind words…
Actually, I did quite a bit of testing (and learning by reading and breaking/frying things) =)
So what you see there (for the entire coop) ~is~ what I’d do if I did it all over again, As far as the Mega vs Uno… I chose the Mega simply b/c it hd more ports (to do all of the other functions I wanted)
Cheers!
I love this code snippet to flash the LED — after I researched it & learned it, I commented it up in my working copy of your code Dave:
Hey, cool!
Thanks for sending, Kris.
Cheers!
Dave, do you happen to have more pics of the build, looking at the code it talks about heat lamps/interior lights ect… did you add relays for this? And how does it read temp, I’m sure there is a themo. shield?
Hi Mark,
Ya know, when I first started building this, I was just racing to get it done… only thinking to start recording my efforts later. =( BUT, I do have more videos coming. (trying to find the time to edit)
What I have it documented here: (note each section has been separated out)
http://davenaves.com/blog/interests-projects/chickens/arduino-chicken-coop/
Hello again Dave.
In your photos you have a real-time clock module, but I see no reference to it in your code. Are you using it?
My build is coming along nicely, I’m looking forward to sharing it with you. I’ll have all the photos and write up on my G+ page, then will share a link here. =)
Thanks!
Hi Chris,
Great catch. In short, no. I haven’t needed it. I thought I was going to do some other functions based on time, but ended up using temp and light levels for everything. =)
Cheers!
Hey Dave, thanks for sharing this. It inspired me to do the same, though I was already considering some kind of automation before I ran across your site (about 7mo ago).. Finished up the electronics, and code yesterday, finally installing this weekend. I’ll see if I can wrangle up some photos while I do so.
In the meantime, all of my code, including code for a NodeJS server and AngularJS webapp, as well as the arduino code is available on github. It’s not pretty, and can likely be optimized some.. probably still one or two bugs to shake out as well, but it allows monitoring AND full remote control of the various coop functions from any internet connected device (mobile, laptop/desktop, tablet, etc) Had to do something to take things up a notch, right? 🙂
https://github.com/willvincent/chicken-coop
Hey, thank YOU for posting yours!
I’m definitely going to take a peek at all the remote control via web. (that was my next move… but just too busy to get the server stuff up and running, etc)
Really appreciate you taking the time!
And yes… show some pics!
Cheers,
/D
WOW Thank you Will! I think you just shared a wheel that I won’t have to re-invent! =)
After making sure all the Arduino-powered functions are installed and working as intended, my next step is to feed Arduino Serial output to a Raspberry Pi. On the Pi I figured I would do something with Python – parse the Arduino’s output and write into a web page hosted on the Pi, which will be connected to the local WiFi.
Goals on the Pi web page:
1. Live view inside the coop via the Raspberry Pi camera module
2. Temp & Humidity inside the coop
3. Light / Dark / Twilight status from the Arduino’s point of view
3. Coop Door opened / closed status
4. Exhaust Fan & Heat Lamp relay off / on status
Completely my pleasure, Kris… thanks for the kind words.
Love your plan. Make sure to share some links with us when you’re done!
Cheers!
Hi Dave!
I’m looking over your code – I plan to implement a lot of what you’ve done for a friend’s chicken coop. Thank you for sharing!
Quick question:
I was wondering why you are using 7-ish data lines to the LCD instead of using like a 2-wire I2C interface to it? I’ve never done either – this is my first LCD-on-Arduino experience.
Thank you!
Hi Kris,
Thanks for the question. Ya know, the simple answer is that when I first started reading/doing research, I just wanted to get it going as quickly as possible (because I’m impatient) and just jumped in, purchased and practiced on the 16×2 LCD I show in my plans (http://goo.gl/RmLCVi) Really no other reason.
=)
Post some pics when you’re done… would love to see it complete.
Cheers!
Dave – I wanted to give you an update since May of 2014 – when finding your project created a monster! I have been up and running for over a year now, pretty much flawlessly. As this automated coop project went on, I kept adding and modifying features like I have an addiction. Some of the things I have done include:
1) Converted from light based to time using an RTC and TimeLord. My chickens are quite regular, and I find it more reliable… just a preference really. Each morning at 12:01, it recalculates the door open and close times based upon the current sunrise and sunset. Only drawback at this point is that I need to adjust the code in the fall and the spring (until I figure out how to automate that as well).
2) Functioning exhaust fans for both the Arduino Case as well as the coop
3) I skipped heat – too concerned about conditioning them, then having them die off during a power outage in the winter. They produce enough body heat, and survived last winter just fine.
4) Went to a 4 line LCD for more information, and relocated the display outside the coop where it is easily monitored.
5) Relay board controlled interior LED lighting (red) as well as an externally controlled halogen floodlight in the run itself.
6) Manual switches for both lights, as well as door override switches (open and close the door on demand, such as when cleaning the coop to keep the girls out of the way).
7) Added an Adafruit CC3000 Wifi card and external TPLink Antenna, used in conjunction with Temboo and Twilio (Both free) to send SMS messages to my mobile devices to let me know when the door opens or closes successfully, or if it encounters an error when I am away from home.
8) External RGB Led visible from the house that stays RED when the door is open, GREEN when it is closed, and FLASHES RED when there is an error condition. It also turns blue when the internal exhaust vent fans are running as well.
As indicated, this winter I hope to figure out how to have the time auto adjust in the spring and fall, as well as institute an RFID option within the nesting boxes to find out who is giving us chicken fruit, and who is just eating my pellets in retirement!!
I would love to share my code for you and anyone else that might be interested, and wanted to ask you the best way to do so…
Thanks again for the inspiration…
Chris P.
NH
Wow! All of it sounds awesome! “Chicken fruit” aaaaaaaahahahaha! love it.
Any images you could share? Would love to see it.
I really appreciate you taking the time to share with all of us. (So please, by all means, post code, images, ideas etc etc.)
I’ve actually been thinking about adding in an additional cam pointed straight at the nesting boxes, so we could see who’s producing as well. (although at this point, I should probably be embarrassed that I know which chicken lays which egg) =) The one cam I have in there now can be navigated via the web, but it’s not straight at the boxes) http://davenaves.com/blog/live-chicken-cam/
http://davenaves.com/blog/wp-admin/edit-comments.php#comments-form
Thanks again and cheers!
I’ve not used it, but you should take a look at this library, it appears to support daylight saving time conversion natively:
https://github.com/JChristensen/Timezone
Thanks, Will. That’s cool.
I appreciate you posting this.
Cheers,
//D
Would like to have a look at Chris P. Code. I’m very interested in looking at it.
Thanks,
Chris D.
Nice!
Yeah, his stuff sounded pretty awesome.
Cheers
Just wondering if Chris P ever provided his code and pics?
Hi David.
I would like to ask if is gonna work with arduino uno as this is i got.
Thnaks.
Hi POL,
Thanks for the question.
Yes, if you’re just doing the door, the Uno should be fine. I did all my testing for the door with an Uno. I used the mega, because I needed more pots for everything else: http://davenaves.com/blog/interests-projects/chickens/arduino-chicken-coop/
Cheers!
Hi David,
Thanks for the question and pointing that out. I see that the mfg changed the product since I added it a while back. Here’s another one that will work just fine: http://amzn.to/1PONP0Z (with all 16 inputs =) )
Cheers!
Hello Dave
Ive spent hours on your website. Love alle the work you done. I have tried to follow in your foodsteps, but om having trouble. would you mind having a quick look at the sketch?
http://forum.arduino.cc/index.php?topic=328761.0
Thanks for the inspiration 🙂
No worries, its working. Now I just have to install it 🙂
ah… didn’t see your last comment. cool, man! post some pics when you’re done, i’d love to see it!
cheers
hi claus,
thanks for the kind words… i just checked over at the arduino forums and it looks as if you’re all good now?
Rather than trying to do everything at once, I plan to implement my improvements in stages, as time, understanding, and money permit.
With that in mind, would you recommend me using the later, more complete code (and remarking out the unused sections) or start with the more limited code (with fewer devices) and update along the way?
Thanks
Great notes, thanks, Paul.
I’d definitely use the entire code and just add hardware when you’re able (and you actually don’t even need to comment anything out… it won’t hurt to have it running there)
Cheers!
Hi Dave,
I am in the process of automating along the same lines as what you have done. Thank you for doing so much work and saving me so much time (lol)!
The sketch above seems to have more items (temp, lights, etc.) and details than the sketch you have on your website for the coop door (http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/).
I assume that the sketch on this page (above) is a later and updated version?
I did enjoy the Fritzing diagram on the door page and was wondering if you had a chance to complete it for the expanded code above?
Could you, possibly, list the sources for the libraries you used above?
I have a million questions, but I’ll have to wait, on those.
Thanks, again…
Hi Paul,
Thanks for the kind words… I appreciate it.
Yeah, the door sketch has been updated, but haven’t had a chance to do the diagram… it’s a lengthy process and I just haven’t had spare time with all of my web dev work. I plan to have the entire coop diagrammed in the next few months. Standby. =)
Yeah, I’ll post the sources for the libraries as well… I’ve been thinking about that lately.
I’ll post a comment when I have made some updates.
Cheers,
//D
This is an awesome idea which I am trying to incorporate to my coop to keep my chicks safe at night.
I know you have more important things do do with your time but I thought I would ask anyways as I am new to the arduino world. I purchased an arduino kit off of our local classifieds which came with a hand full of thing most of which I have been able to successful apply towards replicating your build I am having issues with two items the temp I have a Temp / Humidity sensor it is an AM2301 and a OLED SSD1306 128×64 spi.
Would you know how to incorporate these items into this build or know of some one whom may give assistance. I know they all work as I can get the to work individually just not when I plug them into your sketch.
Any ideas suggestion would be greatly appreciated.
else wise I will order the same LCD you have and temp sensor.
Thanks again
Thanks for writing in, Matt. And thanks for the kind words.
Ya know, I don’t have any experience with either of those sensors, but you might try posting (very specific) questions to the Arduino Forums. If you do some homework and are very specific with exactly what you want and any existing code, there are many great Arduino experts out there, ready to help. (I certainly did) =)
http://forum.arduino.cc/
Pleas keep us posted with your project!
//D
Just wanted to say thanks for sharing all of your hard work. Used this site to get my own coop door automated with Arduino! A couple helpful thoughts for others pursuing this project…
I used a door peephole to hold my photoresistor. It is the perfect size and already pre-made and weatherproof. Just put a dab of silicone in the back to seal it up.
I also added an override switch to allow me to manually open/close the door. (Added some babies to the flock, and they haven’t gotten the coop at night thing figured out yet). I just used a simple switch connected to an input and ground to toggle “normal” or “override” condition.
I am running mine off of a small 12V battery and a little solar panel. It can’t quite keep up during lower sunlight hours in the winter, so I have to drag a charger out every few weeks. I am looking into building my own small turbine next since we have plenty of wind here in Kansas.
wow.. sounds awesome, nate! i’ve been needing to do the same thing with the manual override. it would be awesome if you could post your normal/override code for everyone here. i’d certainly love to see how you did it. (if you’re ok with sharing)
yeah, the babies… it might help to put a little light inside right at dusk. it helped a few of the newbies this year.
thanks for writing in!
cheers,
//d
David thanks for putting the effort to publish your work. I am working on an automated chicken coop door and the code has been really useful in working out the best way to implement it.
so glad it’s helping, ralph… thanks for writing it!
please post some pics of your door when you’re done.
cheers!
Hi Dave,
UK reader here, firstly, thank you very much for this superb guide.
I’m building my first coop and really wanted to automate things and make a project out of it, the information you’ve provided has enabled me to do so!
Question, as I run a number of automation systems, I’ve become a little obsessed with seeing live data, and performing actions over web interface’s. Have you for example considered integrating something along the lines of an ESP8266 chip, and perhaps a simple web interface? Sadly this is beyond my skillset, but thought I’d put the idea out there!
hi mark,
thanks for writing in and the kind words…
yes, in fact i’m currently working on having everything posted to the web (all reports) i’m planning on just installing apache webserver, php/mysql and then write some scripts to pull messages from the arsuino serial port.
in addition to that, i’m going to build a web-based control panel to allow me to administer the functions via the web. (turn off lights, open door, etc etc)
when i’m done, i’ll make sure to post everything, so we can all have this and enjoy. =)
cheers,
//d
Greetings, Dave!
What a treasure trove of knowledge and learning you bring to your readers. It’s most appreciated. That said, and at the risk of sounding like a total moron, do you think it would be OK to use a Due microprocessor in lieu of the Mega2650? I know there’s the 3.3v concern with the Due (admit I don’t completely understand it), but I do have a Pololu Iten #2595 Logic Level Shifter that will hopefully solve the issue. Naturally, I have numerous more questions, some of which have been answered by reading other peoples’ posts to you, but they’ll keep for later.
Thanks much. This question, alone, will expose my lack of knowledge in this whole world of Arduino, but I have to admit that it’s the most fascinating thing since plastic drum heads and nylon tips!
jlw (The L is for Ludwig…….the absolute truth!)
Hey there, Joe,
I really appreciate the kind words… means a lot.
So in short, yes the due would be just fine. (and maybe I’m not quite understanding your point about the 3.3v, but the Due also has a 5v port. , so you’re all good!) =)
Just wanted to post a link to an image of the DUE so you can see the 5v (at the bottom)
http://arduino.cc/en/uploads/Main/ArduinoDue_Front.jpg
Keep the questions coming! (and post pics or vids so we can see your coop)
And wait… you’re a member of the Ludwig DRUM Family???
Cheers,
//D
Wanted to thank you for the time you have put in. Both for the arduino coding and the time to post picture on the blog. I have successfully test my automatic coop door based on your code and door design.
Hey thanks, Scott! Any pictures you could share with us? Would love to see it!
Cheers!
Here is a link with the really rough beginning design. Hopefully more redefined on to come
https://www.youtube.com/watch?v=dUJ31-HFTaI
LOVE IT
Thanks for sharing, Scott!
Hey Dave, As you know I am using a lot of your code for my coop controller and you and I have discussed loss of door control and reed switch De-bouncing techniques. I have mostly used 10 ms for De-bounce time. In studying this I wondered how much time a single pass of the loop code would take. So I setup a test using an unused output pin. I connected my oscilloscope to pin 46 and in the code I set that pin for output. Then at the beginning of the loop code I changed its output value. I am measuring about 45ms per pass of the loop code. This obviously will affect the De-bounce times if they depend on loop of the code. I think I have more code in my system then you, but not that much. What do you think? do you have an oscillscope?
I also note that every time my readTemp() function runs I get over a 2 second pause in pass times. I attribute that to the liberal use of the delay() function. A rewrite for that is now queued. I am thinking that moving critical control functions of the chicken door should be moved to an interrupt service routine. How do you see this?
I think you should remove as many, if not all the delays and use the unsigned long method, like i did:
if ((unsigned long)(millis() - lastTempCheckTime) > TempCheckDelay) { // check temperature every 10 minutes
lastTempCheckTime = millis();
// if cold, turn on heat lamps
if (tempF <= 40) { // if temp drops below 40F turn on heat lamp(s) relay digitalWrite(relayHeat, HIGH); } else if (tempF > 40) {
digitalWrite(relayHeat, LOW); // if temp remains above 40F turn off heat lamp(s) relay
}
if (SerialDisplay) {
Serial.print(" Coop Temperature:"); // print out coop temperature
Serial.println(tempF); // print out the temperature
Serial.println(" Coop Heater is on"); // print out Coop Heater is on
}
}
Works for me.
=)
Cheers!
Howdy,
No sir, don’t have an oscilliscope. I guess I never put that much thought into checking the entire loop time. My only concern about the millis() for the door at least, was how fast was the door going as it got near to each reed switch. (currently set to 100ms = 1/10 of a second)
But unless I’m thinking about this incorrectly here, millis() returns the number of milliseconds since the Arduino board started running the program and not since the loop was generated and repeated.
David I have a small problem that I am having trouble getting a handle on. Do you ever have problems with the top limit not stopping the door? It works most of the time. Just occasionally the door goes past it. I have installed an emergency limit switch that cuts power to the door motor. I have a LED and resistor connected to the switch so that it light up when the switch is closed. I have observed that the LED comes on when this issue occurs. So I think the reed switch is being activated by the magnet in the door.
Any ideas?
Mark
Yes, happened to me and drove me nuts!
For me, it was the light levels changing way too fast at dawn and dusk (read too many times by the photocel) The door would fwd/rev and sputter and then depending on the exact moment, would travel upward beyond the reed switch and then bind up, keeping the motor running on high in fwd motion. My solution was to only read the light levels every 10 minutes and boom… fixed!
I am liking your re-write. How much difference have you seen by taking out the delay() functions. Also I see you are going to try and use this for control of an electric fence. Is the intent to just turn it on or off? I got my system back running with Ethernet. Debugging the code now. It takes very detailed HTML code to run… what a pain. You are a web heavy know any ways to lighten the load?
Hi Mark,
thanks for the questions….
Huge difference in removing the delays. Essentially, functions weren’t working and I couldn’t figure out why (completely intermittent) But that was fairly early on when I had delays all over the place. I left the debounce delays in there since they worked just fine, but then I decided to do an overhaul and am glad I did.
The electric fence… yeah, just wanted to turn it on at night after the girls are inside. (didn’t want them getting zapped during the day, being as curious as they are) =)
Oh, cool… Ethernet. I haven’t yet tried it. As far as too much html and not seeing what you’re seeing, it’s kinda hard to tell, but I can tell you that you should see if there are html tables in there and hard-coded – in-line formatting within the tags. Often times these are depricated and can be cleaned up by using minimal divs and css.
Cheers!
Wow!! I just found this stream. It’s like another person called Mark Cummins that went on and on. I don’t remember what I was thinking then. Sorry Stroke does that. I sent you an email recently including my current code. All is running very well for almost a year. I include the current code here. I am rebuilding my coop emulator here in my home I will rewrite the code to remove the current way we control the door. I hope it will remove the desire to always control the door and some implied fail modes and I want to move the door sensor from the door. Currently the door position for the lock on the door to latch requires the motor to continue to run after the bottom switch is made. This causes several issues. I am working on them now.
This current code supports;
1. two temperature probes (inside, outside)
2. two access door detectors( main area, egg hatch)
3. two push button control panel ( green, red)
4. two LED (green, red) status panel
5. 4 relay outputs (main light, egg hatch light, inside heat, water heat)
6. one chicken access door
7. 16 x 2 LCD display
8. Enhanced debouncing on switch inputs
9. Long term integration of digital thermometer inputs (produces better door control)
10. Watchdog timer output once every two passes. (great debug tool to trouble shoot with)
11. Control panel control of auto of manual control of door ( press three times in three seconds to access)
12. Control USB console of coop status.
13. Very important to run console at highest speed to decrease pass time.
14. Nothing is done while the chicken door is moving except watch those limit switches.
Current code; (hope this is readable)
/*
CoopControl_V2.0.0 written by Mark Cummins
This code is for the “ChickenCoopControl” system that I have been building to use for my Son’s coop.
Part of this code came from a program with permission copyrighted 2013 by David Naves (http://daveworks.net, http://davenaves.com)
Also note the code to run the DS18S20 tempature came from with permission bildr.org/2011/07/ds18b20-arduino/
I have also used some code that is public domain to service some devices.
V2.0.0 takes V1.5.3 and adds Web Page Serving.
1. Added “listenForEthernetClients()” function
2. added new function for time reporting “reportTimeStr()” and “str2digits(int number)”
V2.0.1
1. convert rewrite coopDoor() add manual mode control implemented.
2. Rewrite PhotoCellInputAverageCtl() removed control from there. Cleared up
issue with LCD message reporting wrong sky conditions.
V2.0.2 rewrite reportTimeStr()
V2.0.3 add to web page
1. Version of software running
2. inside heater and water heate status on web page
3. Change trigger of photocell readings to variable takePCread time in miliseconds to sample photocell
V2.0.4 adds Status indications and logging to SD card.
1. adds alarmControlSys(), determines if door is moving and limit swithes are evaluated for “change” mode
2. fixed readTemp() added string field results vis dtostrf()
3. fixed lcdMsg() got rid of float issues with sprint()
4. added logSystem() logging system to SD chip on ethernet board added enable chip control
5. fixed chip enable issues with w5100 ethernet system… web page works
6. added suspension of operations of lcdMsg() and logSystem() when door is moving.
7. added disable lcdMsq when chicken door is moving.
V2.0.7 remove SD and Ethernet operations
*/
// libraries
#include // load the SimpleTimer library for supporting timer operation
#include // load the Wire library to support operation on the LCD system
#include // load the display library
#include // load the one wire library for the support of thermometer systems DS18S20
#include // load the time library to support RTC
#include // load the RTC library
// pins assignments
// i/o
const int photocellPin = A0; // photocell connected to analog 0
const int thermometerPin = 2; // thermometer DS18S20 on digital pin 2
const int enableCoopDoorMotorA = 5; // enable motor a – pin 5
const int greenPushButtonPin = 18; // Green push button on CMD panel(int.5)
const int redPushButtonPin = 19; // Red push button on CMD panel(int.4)
const int redLEDpin = 24; // Green led set to digital pin 24
const int greenLEDpin = 25; // Red led set to digital pin 25
const int topSwitchPin = 26; // top switch is connected to pin 26
const int bottomSwitchPin = 27; // bottom switch is connected to pin 27
const int mainDoorSwitchPin = 28; // main door switch entry is connected to pin 28
const int eggDoorSwitchPin = 29; // egg door switch enty is connected to pin 39
const int mainLightPin = 40; // main lamp relay set to digital pin 40
const int eggLightPin = 41; // egg lamp relay set to digital pin 41
const int insideHeatPin = 42; // inside heat lamp relay set to digital pin 42
const int waterHeatPin = 43; // water heat lamp relay set to digital pin 43
const int directionOpenCoopDoorMotorA = 44; // direction close motor a – pin 44
const int directionCloseCoopDoorMotorA = 45; // direction open motor a – pin 45
const int loopPassTImePin = 46; // digital output for loop pass timing on pin 46
// variables
// version of code
const String cccCode = “v2.0.7”;
// alarmControlSys
boolean chickenDoorMotorEngaged; // chicken door motor status flag
boolean doorMovingFlag; // flag when true means the door is moving
// Logging
unsigned long logLastTimeRun; // last time log made an output
const unsigned long logSystemPeriod = 60000; // how often to run a log of photocell
char bufLog[80];
boolean doorOpen;
// CMD operation
const long enterHold_time = 3000; // enter “hold mode” timer value in milliseconds
boolean goHoldRed = false; // “go hold” flag for red push button
boolean goHoldGreen = false; // “go hold” flag for green push button
boolean holdSkyControl = false; // flag for control of door. false = automatic “based on sky readings”. true = means freeze door operation.
boolean holdSkyControl_Last = true; // last value of “holdSkyControl” for determining if srtate has changed
boolean holdOpen; // true means door is in up position, false means down.
unsigned long first_RedButtonPressed = 0; // counter to hold time “First time Red was pressed in “enterHold_Time” frame
unsigned long first_GreenButtonPressed = 0; // counter to hold time “First time Red was pressed in “enterHold_Time” frame
int redPushButtonCount = 0; // counter to hold “How many times red button is pressed in “enterHold_Time” frame
int greenPushButtonCount = 0; // counter to hold “How many times green button is pressed in “enterHold_Time” frame
boolean CMDholdState = false; // flag to indicate current state of LED while in hold mode
// photocell
int photocellReading; // analog reading of the photocel
int photocellReadingLevel = 50; // photocel reading levels (dark(1)(Ascii49), twilight(2)(Ascii50), light(3)(Ascii51))
// since at start time the doors position is unknown set to 50 at system start or reset.
// photocell averaging
const int numReadingsPC = 1000; // number of photocell readings to average
int readingsPC[numReadingsPC]; // the readings from the analog input
int indexPC = 0; // the index of the current reading
unsigned long int totalPC = 0; // the running total
unsigned long int lastPCtime; // time last photocell reading was made
int takePCread = 10; // time interval in milliseconds to take reading of photocell
// all switches
const int debounce_count = 10; // number of millis/samples to consider before decllaring a debounced input.
// top switch
int topSwitchCounter; // how many times we have seen new value
int topSwitchReading; // main door switch current value reading input pin.
int topSwitchCurrent_State = HIGH; // main door switch Debounced input value
long topSwitchTime = 0; // last time the main door was sampled
// bottom switch
int bottomSwitchCounter; // how many times we have seen new value
int bottomSwitchReading; // main door switch current value reading input pin.
int bottomSwitchCurrent_State = HIGH; // main door switch Debounced input value
long bottomSwitchTime = 0; // last time the main door was sampled
// Main Door Switch
int mainDoorCounter; // how many times we have seen new value
int mainDoorReading; // main door switch current value reading input pin.
int mainDoorCurrent_State = HIGH; // main door switch Debounced input value
long mainDoorTime = 0; // last time the main door was sampled
int flagMainDoorLight;
// Egg Door Switch
int eggDoorCounter; // how many times we have seen new value
int eggDoorReading; // main door switch current value reading input pin.
int eggDoorCurrent_State = HIGH; // main door switch Debounced input value
long eggDoorTime = 0; // last time the main door was sampled
int flagEggDoorLight;
// Green Command Switch
int greenCMDCounter; // how many times we have seen new value
int greenCMDReading; // main door switch current value reading input pin.
int greenCMDCurrent_State = HIGH; // main door switch Debounced input value
boolean greenCMDChange_State = HIGH; // true means state has changed
long greenCMDTime = 0; // last time the main door was sampled
// Red Command Switch
int redCMDCounter; // how many times we have seen new value
int redCMDReading; // main door switch current value reading input pin.
int redCMDCurrent_State = HIGH; // main door switch Debounced input value
boolean redCMDChange_State = HIGH; // true means state has changed
long redCMDTime = 0; // last time the main door was sampled
int burpTimebegin;
// light status var
int cmdLEDgreen; // status var to indicate current LED condition, “0” means LED is on,
// “1” means LED is off, “-1_” means door is intransition
int cmdLEDred; // status var to indicate current LED condition, “0” means LED is on,
// “1” means LED is off, “-1_” means door is intransition
// temperature sensor variables
OneWire ds(thermometerPin); // OneWire buss on pin 2
#define MAX_DS1820_SENSORS 2 // declare two temprature sensors
byte addr[MAX_DS1820_SENSORS][8]; // setup byte array 2 by 8 bytes
int HighByte; // word buffer for temp store high byte
int LowByte; // word buffer for temp store low byte
int TReading; // word buffer to build complete data word from device
float tempFah0; // result location for outside temperature sensor
float tempFah1; // result location for inside temperature sensor
char tempFahStr0[6];
char tempFahStr1[6];
// heating demand variables
float insideHeatTrig = 45.0; // trigger temperature for inside heating demand
int insideHeatStatus;
float waterHeatTrig = 36.0; // trigger temperature for outside water heating demand
int waterHeatStatus;
// RTC var
char bufTime[21];
// only need 1 SimpleTimer object
SimpleTimer timer;
// loop pass timing vars
boolean loopPassTImevalue = false;
const boolean testLoopTime = true; // TRUE turns on loop timme measuing
// LCD variables
#define BACKLIGHT_PIN 3 // Define Backlight pin for LCD
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7); //LCD support and declations
char buf0[17];
char buf1[17];
int long lcd_Disp_Inteval = 1000; // time in milliseconds
int long lcd_Disp_Last; // time of last LCD update
// ************************************** the setup **************************************
void setup (void) {
lcd.begin(16, 2); // setup 16 character by 2 line display
lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE); // setup backlight interface
lcd.setBacklight(HIGH); // turn on backlight in display
Serial.begin(115200);
reportTimeSerial();
Serial.print(“**************************Running Setup********************************”);
Serial.println (cccCode);
// test output to measure pass times
pinMode (loopPassTImePin, OUTPUT); // out pin to sample pass times externally
digitalWrite(loopPassTImePin, loopPassTImevalue); // initialize
// chicken coop door motor
pinMode (enableCoopDoorMotorA, OUTPUT); // enable motor pin = output
pinMode (directionCloseCoopDoorMotorA, OUTPUT); // motor close direction pin = output
pinMode (directionOpenCoopDoorMotorA, OUTPUT); // motor open direction pin = output
// chicken coop door switches
// bottom switch
pinMode(bottomSwitchPin, INPUT); // set bottom switch pin as input
digitalWrite(bottomSwitchPin, HIGH); // turn on the internal pull up 10K resistor
readDebounceBottomReedSwitch(); // read bottom switch and set state
// top switch
pinMode(topSwitchPin, INPUT); // set top switch pin as input
digitalWrite(topSwitchPin, HIGH); // turn on the internal pull up 10K resistor
readDebounceTopReedSwitch(); // read top switch and set state
// Stop servo system abd Init door operation
stopCoopDoorMotorA();
// Setup CMD push buttons
pinMode (redPushButtonPin, INPUT); // set pin for input
digitalWrite(redPushButtonPin, HIGH); // enable pull up resistor
pinMode (greenPushButtonPin, INPUT); // set pin for input
digitalWrite(greenPushButtonPin, HIGH); // enable pull up resistor
holdSkyControl = false; // set mode to automatic
holdSkyControl_Last = false; // inverse last state to initate first pass run
// setup main and egg room lights and detection switches
pinMode(mainLightPin, OUTPUT);\
pinMode(eggLightPin, OUTPUT);
pinMode(mainDoorSwitchPin, INPUT);
pinMode(eggDoorSwitchPin, INPUT);
// heating demands
pinMode(insideHeatPin, OUTPUT); // set inside heating relay output
digitalWrite(insideHeatPin, HIGH); // turn off heat lamp relay (“off” = HIGH)
pinMode(waterHeatPin, OUTPUT); // set outside water heat relay output
digitalWrite(waterHeatPin, HIGH); // turn off heat lamp relay (“off” = HIGH)
// setup CMD panel LEDs
pinMode(greenLEDpin, OUTPUT); // HIGH means on, LOW means off
pinMode(redLEDpin, OUTPUT); // HIGH means on, LOW means off
// temperature sensor setup
if (!ds.search(addr[0])) // see if outside temp device is there
{
reportTimeSerial();
Serial.println(“Outside temp sensor not found”); // status host message to indicate outside device is not there
ds.reset_search(); // reset OneWire buss get attension of all devices
delay(250); // wait for power to stabilize
return;
}
else
{
reportTimeSerial();
Serial.println(“Outside temp sensor found”); // also send to host
}
if ( !ds.search(addr[1])) // see if inside device is there
{
reportTimeSerial();
Serial.print(“Inside temp sensor not found”); // status host message to indicate inside device is not there
ds.reset_search(); // reset OneWire buss
delay(250); // wait for power to stabilize
return;
}
else
{
reportTimeSerial();
Serial.println(“Inside temp sensor found”); // also send to host
}
// timed actions setup
readTemp(); // get first reading
timer.setInterval(60000, readTemp); // setup timer to read the temperature sensors once a minute
setHeating(); // set fist reading controls
timer.setInterval(60000, setHeating); // setup timer to read the temperatures and contol heat demands
timer.setInterval(600, doCMDledHold); // setup timer to handle CMD LEDs state change
// initialize all the photocell readings to 0:
for (int thisReadingPC = 0; thisReadingPC logSystemPeriod) { // is it time to run?
memset(bufLog, 0, sizeof(bufLog));
reportTimeStr(); // get current time and build bufLog topSwitchCurrent_State
sprintf(bufLog, “%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s\r”, bufTime, photocellReading,topSwitchCurrent_State,bottomSwitchCurrent_State,doorOpen, holdSkyControl, holdOpen,
!mainDoorCurrent_State, !eggDoorCurrent_State, insideHeatStatus, waterHeatStatus, tempFahStr0, tempFahStr1 );
Serial.println(bufLog);
logLastTimeRun = millis();
} // end of logLastTimeRun
} // end of !doorMovingFlag
} // end of logSystem()
void loopPassTesting() { // function to measure loop pass timing via ditital output pin
if (testLoopTime) { // can we do testing?
digitalWrite(loopPassTImePin, loopPassTImevalue); // yes, write new state
loopPassTImevalue = !loopPassTImevalue; // reverse state for wave form generation.
}
/*
Loop pass time base is about 5 microseconds
*/
} // end of loopPassTesting() function
void alarmControlSys() { // function to set alarm and status variables
if (topSwitchCurrent_State == 1) { // is top limit switch open(“1”)?
if (bottomSwitchCurrent_State == 1) { // is bottom limit switch open(“1″)?
if (!chickenDoorMotorEngaged) { // is door motor not engaged?
doorMovingFlag = LOW; // set door moving flag to LOW
// digitalWrite(onBoardLEDStatusPIN, LOW);
} else { // else
// digitalWrite(onBoardLEDStatusPIN, HIGH);
doorMovingFlag = HIGH; // set door moving flag to HIGH
}
}
}
if (topSwitchCurrent_State == 0) {
if (bottomSwitchCurrent_State == 1) {
doorMovingFlag = LOW;
doorOpen = true;
// digitalWrite(onBoardLEDStatusPIN, LOW);
}
}
if (topSwitchCurrent_State == 1) {
if (bottomSwitchCurrent_State == 0) {
doorMovingFlag = LOW;
doorOpen = false;
// digitalWrite(onBoardLEDStatusPIN, LOW);
}
}
} // end of alarmControlSys()
void PhotoCellInputAverageCtl() { // function to to input and average photocell readings
if (millis() – lastPCtime >= takePCread) {
totalPC = totalPC – readingsPC[indexPC]; // subtract the last reading:
readingsPC[indexPC] = analogRead(photocellPin); // read from the sensor:
totalPC = totalPC + readingsPC[indexPC]; // add the reading to the total:
indexPC = indexPC + 1; // advance to the next position in the array:
if (indexPC >= numReadingsPC) // if we’re at the end of the array…
indexPC = 1; // …wrap around to the beginning:
photocellReading = totalPC / numReadingsPC; // calculate the average:
if (photocellReading >= 0 && photocellReading =40 && photocellReading = 275) {
photocellReadingLevel = ‘3’; // day time
}
lastPCtime = millis();
}
} // end of PhotoCellInputAverageCtl()
void readCMDinput() {
readDebounce_greenCMDSwitch(); // fetch read of push button
if (greenCMDChange_State == HIGH) { // has there been a change in input?
if (greenCMDCurrent_State == LOW) {
if (greenPushButtonCount == 0) { // if the press count time = 0 then this is a new hold time frame
first_GreenButtonPressed = millis(); // set first green button pressed time in milliseconds
greenCMDChange_State = LOW;
}
if (greenPushButtonCount == 1) {
greenCMDChange_State = LOW;
if (millis() – first_GreenButtonPressed > enterHold_time)
{
greenPushButtonCount = 0; // reset counter of green button pressed events
goHoldGreen = false;
}
}
if (greenPushButtonCount == 2) { // is this the third time(count 0 to 2) red button is pressed?
greenCMDChange_State = LOW;
if (millis() – first_GreenButtonPressed enterHold_time)
{
redPushButtonCount = 0; // reset counter of green button pressed events
goHoldRed = false;
}
}
if (redPushButtonCount == 2) { // is this the third time(count 0 to 2) red button is pressed?
redCMDChange_State = LOW;
if (millis() – first_RedButtonPressed enterHold_time) { // reset red pressed count if hold time is exceeded
redPushButtonCount = 0; // exceeded so reset
}
}
if (goHoldGreen == true) { // has the hold door status control been signaled by the green push button?
holdSkyControl = !holdSkyControl; // revert state of automatic operation of the door
holdOpen = true; // door should be in the open or up position
greenPushButtonCount = 0; // reset the counting of the red push button actuations
goHoldGreen = !goHoldGreen; // reset the flag indicating a hold operation change by the green push button
}
else { // No change loop execution
if (millis() – first_GreenButtonPressed > enterHold_time) {// reset red pressed count if hold time is exceeded
greenPushButtonCount = 0; // exceeded so reset
}
}
if (holdSkyControl != holdSkyControl_Last) { // has holdSkyControl state changed?
reportTimeStr();
Serial.print(bufTime);
//reportTimeSerial();
Serial.print(” holdSkyControl state changed, “); // yes send status message
if (holdSkyControl == true) { // is the door control status in the hold state?
if (holdOpen == true) { // should the door be up?
Serial.println(” Held door set open, ‘Manual Mode'”); // Yes… print status
}
else { // No… print Status
Serial.println(“Held door set closed, ‘Manual Mode'”);
}
}
else { // Not in hold state… run automatically
Serial.println(“Hold control is off, ‘Auto mode'”); // status message
}
holdSkyControl_Last = holdSkyControl; // update last value flag
}
} // end of execCMDControl()
void lcdMsg() {
if (!doorMovingFlag) { // do not run if door is in motion
if ((millis() – lcd_Disp_Last) >= lcd_Disp_Inteval) {
//Serial.print(“LCD”);
memset(buf0, 0, sizeof(buf0));
memset(buf1, 0, sizeof(buf1));
if (photocellReadingLevel == ‘1’) {
sprintf(buf0, “%sNight I:%s”, holdSkyControl ? “Man ” : “Auto “, tempFahStr0 );
}
else if (photocellReadingLevel == ‘2’) {
sprintf(buf0, “%sTwili I:%s”, holdSkyControl ? “Man ” : “Auto “, tempFahStr0 );
}
else if (photocellReadingLevel == ‘3’) {
sprintf(buf0, “%sDay I:%s”, holdSkyControl ? “Man ” : “Auto “, tempFahStr0 );
}
if (topSwitchCurrent_State == 1) {
if (bottomSwitchCurrent_State == 1) {
sprintf(buf1, “Change %s%s0:%s”, insideHeatStatus ? “H ” : ” “, waterHeatStatus ? “W ” : ” “, tempFahStr1 );
}
}
if (topSwitchCurrent_State == 0) {
if (bottomSwitchCurrent_State == 1) {
sprintf(buf1, “Open %s%s0:%s”, insideHeatStatus ? “H ” : ” “, waterHeatStatus ? “W ” : ” “, tempFahStr1 );
}
}
if (topSwitchCurrent_State == 1) {
if (bottomSwitchCurrent_State == 0) {
sprintf(buf1, “Closed %s%s0:%s”, insideHeatStatus ? “H ” : ” “, waterHeatStatus ? “W ” : ” “, tempFahStr1 );
}
}
//lcd.setCursor(0, 0);
lcd.clear();
lcd.print(buf0);
lcd.setCursor(0, 1);
lcd.print(buf1);
lcd_Disp_Last = (millis());
} // end of time to run
} // end of door flag
} // end of lcdMsg()
void reportTimeStr() { // routine to read and create string object of current TOY from RTC module
memset(bufTime, 0, sizeof(bufTime));
tmElements_t tm;
if (RTC.read(tm)) {
sprintf(bufTime, “%02d/%02d/%02d %02d:%02d:%02d”, tm.Day, tm.Month, tmYearToCalendar(tm.Year), tm.Hour, tm.Minute, tm.Second );
}
} // end of reportTimeStr()
void reportTimeSerial() { // routine to read and print current TOY from RTC module
tmElements_t tm;
if (RTC.read(tm)) {
print2digits(tm.Day);
Serial.write(‘/’);
print2digits(tm.Month);
Serial.write(‘/’);
Serial.print(tmYearToCalendar(tm.Year));
Serial.print(” “);
print2digits(tm.Hour);
Serial.write(‘:’);
print2digits(tm.Minute);
Serial.write(‘:’);
print2digits(tm.Second);
Serial.print(” “);
} else {
if (RTC.chipPresent()) {
Serial.println(“The DS1307 is stopped. Please run the SetTime”);
Serial.println(“example to initialize the time and begin running.”);
Serial.println();
} else {
Serial.println(“DS1307 read error! Please check the circuitry.”);
Serial.println();
}
delay(4000);
}
} // end of reportTimeSerial()
void print2digits(int number) {
if (number >= 0 && number < 10) {
Serial.write('0');
}
Serial.print(number);
} // end of print2digits()
void setHeating() { // set heating demands based on temperatures derrived from
if (tempFah1 <= insideHeatTrig) { // deal with inside temp and heating outlet
digitalWrite(insideHeatPin, LOW); // turn on heat outlet relay
insideHeatStatus = HIGH; // set inside heating outlet status
}
else
{
digitalWrite(insideHeatPin, HIGH); // turn off heat lamp relay
insideHeatStatus = LOW; // set inside heating outlet status
}
if (tempFah0 <= waterHeatTrig) { // deal with outside temp and water heater outlet
digitalWrite(waterHeatPin, LOW); // turn on heat outlet relay
waterHeatStatus = HIGH; // set water heater status
}
else
{
digitalWrite(waterHeatPin, HIGH); // turn off heat lamp relay
waterHeatStatus = LOW; // set water heater status
}
} // end of setHeating()
void readTemp() { // read two sensors and return reading in "tempFag0" and "tempFah1"
byte i, sensor; // local byte var pointer to counting (i), and the current sensor
byte present = 0; // local byte var to indicate sensor is present set to zero to start with
byte data[12]; // local 12 byte var to hold data that is read from sensor unter test
for (sensor = 0; sensor < MAX_DS1820_SENSORS; sensor++) // start scanning sensors start with the first one
{
if ( OneWire::crc8( addr[sensor], 7) != addr[sensor][7]) // check that we read and generate a valid CRC
{
reportTimeSerial();
Serial.println("CRC is not valid"); // status message to LCD
return;
}
if ( addr[sensor][0] != 0x10) // check to see if it is the correct device type
{
reportTimeSerial();
Serial.println("Device is not a DS18S20 family device.");
return;
}
ds.reset(); // reset buss
ds.select(addr[sensor]); // select sensor
ds.write(0x44, 1); // start conversion, with parasite power on at the end
delay(100); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
present = ds.reset();
ds.select(addr[sensor]); // reselect sensor
ds.write(0xBE); // tell selected device we want to read the conversion from the selected device's scratchpad
for ( i = 0; i < 9; i++) // 9 step read of data from device
{ // we need 9 bytes
data[i] = ds.read(); // read in 9 bytes to array "data(12) using first 9 bytes
}
LowByte = data[0]; // word "LowByte" = first byte
HighByte = data[1]; // word "HighByte" = second byte
TReading = (HighByte < 0?
&& bottomSwitchCounter > 0) {
bottomSwitchCounter –; // yes then decrement counter value
}
if (bottomSwitchReading != bottomSwitchCurrent_State) { // is current reading different then known current state?
bottomSwitchCounter ++; // yes so increment counter
}
if (bottomSwitchCounter >= debounce_count) { // have we reached a decision state?
bottomSwitchCounter = 0; // yes so reset counter
bottomSwitchCurrent_State = bottomSwitchReading; // declare
}
bottomSwitchTime = millis(); // set last change time
}
} // end of readDebounceBottomReedSwitch()
void readDebounceTopReedSwitch() { // de-bounce top reed switch cof hicken door
if (millis() != topSwitchTime)
{
topSwitchReading = digitalRead(topSwitchPin); // read the state into local variable
if (topSwitchReading == topSwitchCurrent_State // is there any change in state and a counter value > 0?
&& topSwitchCounter > 0) {
topSwitchCounter –; // yes then decrement counter value
}
if (topSwitchReading != topSwitchCurrent_State) { // is current reading different then know current state?
topSwitchCounter ++; // yes so increment counter
}
if (topSwitchCounter >= debounce_count) { // have we reached a decision state?
topSwitchCounter = 0; // yes so reset counter
topSwitchCurrent_State = topSwitchReading; // declare
}
topSwitchTime = millis(); // set last change time
}
} // end of readDebounceTopReedSwitch()
void readDebounceMainDoorSwitchPin() { // de-bounce main door reed switch
if (millis() != mainDoorTime)
{
mainDoorReading = digitalRead(mainDoorSwitchPin); // read the state into local variable
if (mainDoorReading == mainDoorCurrent_State // is there any change in state and a counter value > 0?
&& mainDoorCounter > 0) {
mainDoorCounter –; // yes then decrement counter value
}
if (mainDoorReading != mainDoorCurrent_State) { // is current reading different then know current state?
mainDoorCounter ++; // yes so increment counter
}
if (mainDoorCounter >= debounce_count) { // have we reached a decision state?
mainDoorCounter = 0; // yes so reset counter
mainDoorCurrent_State = mainDoorReading; // declare
}
mainDoorTime = millis(); // set last change time
}
} // end of readDebounceMainDoorSwitchPin()
void readDebounceEggDoorSwitch() { // debounce egg door reed switch
if (millis() != eggDoorTime)
{
eggDoorReading = digitalRead(eggDoorSwitchPin); // read the state into local variable
if (eggDoorReading == eggDoorCurrent_State // is there any change in state and a counter value > 0?
&& eggDoorCounter > 0) {
eggDoorCounter –; // yes then decrement counter value
}
if (eggDoorReading != eggDoorCurrent_State) { // is current reading different then know current state?
eggDoorCounter ++; // yes so increment counter
}
if (eggDoorCounter >= debounce_count) { // have we reached a decision state?
eggDoorCounter = 0; // yes so reset counter
eggDoorCurrent_State = eggDoorReading; // declare
}
eggDoorTime = millis(); // set last change time
}
} // end of readDebounceEggDoorSwitch()
void readDebounce_greenCMDSwitch() { // debounce green CMD push button switch
if (millis() != greenCMDTime)
{ //
greenCMDReading = digitalRead(greenPushButtonPin); // read the state into local variable
if (greenCMDReading == greenCMDCurrent_State // is there any change in state and a counter value > 0?
&& greenCMDCounter > 0) {
greenCMDCounter –; // yes then decrement counter value
}
if (greenCMDReading != greenCMDCurrent_State) { // is current reading different then current state?
greenCMDCounter ++; // yes so increment counter
}
if (greenCMDCounter >= debounce_count) { // have we reached a decision state?
greenCMDCounter = 0; // yes so reset counter
greenCMDCurrent_State = greenCMDReading; // greenCMDCurrent_State is debounced condition of switch
greenCMDChange_State = true; // set flag indicating a change in greenCMDCurrent_State
} else {
greenCMDChange_State = false;
}
greenCMDTime = millis(); // set last change time
}
} // end of readDebounce_greenCMDSwitch()
void readDebounce_redCMDSwitch() { // debounce red CMD push button switch
if (millis() != redCMDTime)
{
redCMDReading = digitalRead(redPushButtonPin); // read the state into local variable
if (redCMDReading == redCMDCurrent_State // is there any change in state and a counter value > 0?
&& redCMDCounter > 0) {
redCMDCounter –; // yes then decrement counter value
}
if (redCMDReading != redCMDCurrent_State) { // is current reading different then current state?
redCMDCounter ++; // yes so increment counter
}
if (redCMDCounter >= debounce_count) { // have we reached a decision state?
redCMDCounter = 0; // yes so reset counter
redCMDCurrent_State = redCMDReading; // redCurrent_State is debounced condition of switch
redCMDChange_State = true; // set flag indicating a change in greenCMDCurrent_State
} else {
redCMDChange_State = false;
}
redCMDTime = millis(); // set last change time
}
} // end of readDebounce_redCMDSwitch()
void setMainDoorLight() { // set main light to current state of main door state
digitalWrite (mainLightPin, !mainDoorCurrent_State);
} // end of setMainDoorLight()
void setEggDoorLight() { // set egg access light to current state of main door state
digitalWrite (eggLightPin, !eggDoorCurrent_State);
} // end of setEggDoorLight()
void stopCoopDoorMotorA() { // stop the coop door
digitalWrite (directionCloseCoopDoorMotorA, LOW); // turn off motor close direction
digitalWrite (directionOpenCoopDoorMotorA, LOW); // turn on motor open direction
digitalWrite (enableCoopDoorMotorA, LOW); // enable motor, 0 speed
chickenDoorMotorEngaged = 0; // sete motor on flag to off
} // end of stopCoopDoorMotorA()
void closeCoopDoorMotorA() { // close the coop door
digitalWrite (directionCloseCoopDoorMotorA, HIGH); // turn on motor close direction normally HIGH
digitalWrite (directionOpenCoopDoorMotorA, LOW); // turn off motor open direction
digitalWrite (enableCoopDoorMotorA, HIGH); // enable motor, full speed
chickenDoorMotorEngaged = 1; // sete motor on flag to on
if (bottomSwitchCurrent_State == 0) { // if bottom reed switch circuit is close
stopCoopDoorMotorA();
}
} // end of closeCoopDoorMotorA()
void openCoopDoorMotorA() { // open the coop door
digitalWrite(directionCloseCoopDoorMotorA, LOW); // turn off motor close direction
digitalWrite(directionOpenCoopDoorMotorA, HIGH); // turn on motor open directionnormally HIGH
digitalWrite(enableCoopDoorMotorA, HIGH); // enable motor, full speed
chickenDoorMotorEngaged = 1; // sete motor on flag to on
if (topSwitchCurrent_State == 0) { // if top reed switch circuit is closed
stopCoopDoorMotorA();
}
} // end of openCoopDoorMotorA()
void coopDoor() {
if (holdSkyControl == true) { // are we in manual mode?
if (holdOpen == true) { // yes, are we in hold open state
readDebounceTopReedSwitch(); // read and debounce the limit switches
readDebounceBottomReedSwitch(); // read and debounce the limit switches
openCoopDoorMotorA(); // yes, so opend the chicken door
} else { // else
readDebounceTopReedSwitch(); // read and debounce the limit switches
readDebounceBottomReedSwitch(); // read and debounce the limit switches
closeCoopDoorMotorA(); // close the coop door
}
} else {
if (photocellReadingLevel == ‘1’) { // is it dark?
readDebounceTopReedSwitch(); // read and debounce the limit switches
readDebounceBottomReedSwitch(); // read and debounce the limit switches
closeCoopDoorMotorA(); // close the door
}
if (photocellReadingLevel == ‘2’) { // is it twilite?
stopCoopDoorMotorA(); // close the door
}
if (photocellReadingLevel == ‘3’) { // is it daylight?
readDebounceTopReedSwitch(); // read and debounce the limit switches
readDebounceBottomReedSwitch(); // read and debounce the limit switches
openCoopDoorMotorA(); // open the door
}
}
} // end of coopDoor()
void coopLights() { // set lights in coop based on door switches and sky conditions
readDebounceMainDoorSwitchPin();
setMainDoorLight();
//flagMainDoorLight;
readDebounceEggDoorSwitch();
setEggDoorLight();
//flagMainDoorLight;
} // end of coopLights()
void setLEDLights() { // function to control CMD LEDs when not in hold mode
if (holdSkyControl == false) { // are we not in hode mode?
if (topSwitchCurrent_State == 1) { // is top door switch open?
if (bottomSwitchCurrent_State == 1) { // and bottom doorswitch is open then door is in motion
cmdLEDred = -1; // status flag for usb messages meaning in motion
digitalWrite(redLEDpin, LOW); // turn off red LED
cmdLEDgreen = -1; // status flag for usb messages meaning in motion
digitalWrite(greenLEDpin, LOW); // turn off green LED
}
}
if (topSwitchCurrent_State == 0) { // is top switch closed?
if (bottomSwitchCurrent_State == 1) { // and bottom switch open?
cmdLEDred = 1; // status flag for usb messages meaning red LED is on
digitalWrite(redLEDpin, LOW); // turn on red LED
cmdLEDgreen = 0; // status flag for usb messages meaning green LED is off
digitalWrite(greenLEDpin, HIGH); // turn off green LED
}
}
if (topSwitchCurrent_State == 1) { // is top switch open?
if (bottomSwitchCurrent_State == 0) { // and bottom switch closed?
cmdLEDred = 0; // status flag for usb messages meaning red LED is off
digitalWrite(redLEDpin, HIGH); // turn off red LED
cmdLEDgreen = 1; // status flag for usb messages meaning green LED is on
digitalWrite(greenLEDpin, LOW); // turn on green LED
}
}
}
else
{
if (holdOpen == true) { // Is hold mode open?
digitalWrite(greenLEDpin, CMDholdState); // change state of green LED every seconf
digitalWrite(redLEDpin, LOW);
}
else { // holdOpen is false so door is held down
digitalWrite(redLEDpin, CMDholdState);
digitalWrite(greenLEDpin, LOW);
}
}
} // end of setLEDLights()
void doCMDledHold() { // timer function to control LEDs while doors are in hold mode
CMDholdState = !CMDholdState;
} // end of doCMDledHold)
error on last post via the past puffer
#include // load the SimpleTimer library for supporting timer operation
#include // load the Wire library to support operation on the LCD system
#include // load the display library
#include // load the one wire library for the support of thermometer systems DS18S20
#include // load the time library to support RTC
#include // load the RTC library
Wow… you have been BUSY. When I have more time, I’ll take a peek at all of the stuff you’ve added.
Looks awesome!
Having trouble with the paste buffer not putting everything in your editor for a post. Look at the #include line in the code I emailed you versus what got posted here. What I posted here is missing the library files to include.
Also about the watchdog timer connected to an oscilloscope, you can substitute using a powered PC speaker connected to the output pin for the code. This will give you and audio indication of pastimes. The higher the pitch the faster the pastime and you can hear when the code changes or does not make passes in the code. It is an eye opener while troubleshooting code. It was how I discovered all the times/ways that the door was moving and the code failed to see the limit switch being closed to stop the motor.
The reason for the request for a call has to do with how long it takes me to communicate using typing. A stroke is a thief in the night.. I can not endure the time to type right now and there is so much I want to pass on to you. There is a basic problem with how we are implementing the control that I am fixing in version 3.0 of my code. I have spent about an two hours just typing and correction this message.
Sorry, I will get better but the doctors say this could be permanent or may clear up in the next couple of years.
Hey Mark,
So sorry to hear about the stroke and the attendant pains it comes with… especially communication. I’ve been trying to keep my head above water with all of my web dev work in addition to having a kid graduating high school, blah blah. I’ll take a close look at your cool code and give you a call when I come up for air!
Take care, my friend.
Other things;
I use an 80K resistor instead of 10K inline with the photocell. Gives me more more precise control at sunrise and sunset. Look closely at the averaging code I use. No false triggers in the last year.
version three will control two doors, one from the coop to the chicken run. the second to give access from the run to the fenced back yard.
This type of control is always trying to move the door , only stopped by the limit reed switches. Also the motor always get driven by the servo amp with a pwm output of about 3% full on. Feel your motor when the door is not moving while in the up position. I suspect you will feel a slight vibration in the motor and the LEDs on the servo will be slightly on. I am rewriting the control in version three of my code.
Many things cause the pass times to go long. All my failures were because the limit switches failed to be sensed in time to control things. Things that caused lone pass times include the writing times to the LCD, USB (use the highest baud rate). In previous versions I had Ethernet running with a web operation, while using a logging system to the SD card. I gave up on them because of intermittent pass time issues. Remember to only do things when the door is not being moved. I have a section called an alarm system that signals to all high demand non critical control code, to not run when I need to measure changes in the limit switches.
More later
Mark
Ahhhhh 80k resistor… great idea!
Man, you are seriously tearing this stuff apart and building it for the better… Love it!
Again, I’ll give you a call when I come up for air. (I seem to be only able to even check this blog once or twice a month now)
Cheers!
Dave,
I have absolutely no technological experience with the Arduino controller or any coding experience. what I do have is lots of design and building experience and ideas that I want to incorporate into my coop design. How easily will I be able to translate what you have created here for your coop into my design. Many of the commands I reviewed in your code above are goals that I would like to achieve as well. I would like to incorporate an interior light timing device so that the girls can get the necessary light amount in the winter months, as we live in Indiana and experience some pretty short natural light days.
Thanks,
recker
Howdy, Recker…
Thanks for the questions.
Essentially, you can just copy and paste my code into an Arduino “sketch”, (upload it) wire it up as shown (although I haven’t done a Fritzing wiring diagram for everything within the coop yet, but the pins are numbered, so you should be able to follow along) and it should work for you. If you purchased the same gear (like the Arduino Mega: http://goo.gl/udJZOp, resistors, etc etc) and do a bit of studying, you’ll be able to nail it fairly quickly. (I like this Arduino book best: http://goo.gl/OIT5On) I really have done most of the heavy lifting (including troubleshooting) for you. It took me over a year (in between working web projects) to figure it out… and I still am adding features ( including a mini-light system – not like what you want, but lights to turn on at dusk and off when the door shuts)
Again, if you’re like me, just jump in and start. And if you have questions, just ask. (typically most folks like to help those how have tried and struggled first and not just answer blanket questions like “how do i do it?”) =)
Hope that helps,
//D
Again, all I ask is that you share what you’ve done with the rest of us (post comments, links here in my blob comments) We’re all in this together as far as I’m concerned. If you have specific questions along the way, most of the other folks posting here are more than happy to help. (including me)
Love your build. I’ve ordered the components for our coop. Should be here tomorrow. Thanks so much for sharing your arduino sketch. This will be incredibly helpful! Just curious though…why did you choose the photo cell rather than the time method?
Hey Ryan,
Thanks for the kind words and your question.
Ya know, for me, the photocell was for a couple of reasons. 1) It was much easier for me to understand and 2) If found that the chickens’ schedules seem to be dictated by light and not necessarily time. (although Timelord follows sunrise/sunsets) I do notice that on darker days, they like to stay in… so I went with the light solution. (pun intended) =)
Cheers!
Hi Dave,
I have purchased most of items on your list to automate my Chickens coop door. One of my questions would be wanting to know the size and type of wire you used. like stranded 22awg? Also, what size Leds did you use for coop door status 5mm?
I have worked with breadboards before but, I’m use to solid single strand wire for breadboard. but that wouldn’t work well for this project. Any chance we as in the community could get you to elaborate on the build of the coop door specifically. Like rough dimensions and hardware used. Any tricks or stumbling blocks involved would be Nice.
Thanks,
Chris
howdy,
just want to make sure you saw all of the images and note within the door page itself:
http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/
as i mentioned within the post, i didn’t do a great job of the exact process (i was racing and didn’t give much thought to documenting everything) however, the overall dimensions are:
overall frame: 14″ w X 30″ h
door itself: 12″ w X 14″ h
door opening: 10″ s X 10.5″ h
as time permits, i’ll go back and maybe even draw up some plans… i just started to, but i’m tire and it looks like cr@p. =)
hope that helps at least a little bit,
cheers,
//d
Hi Dave,
I have purchased most of items on your list to automate my Chickens coop door. One of my questions would be wanting to know the size and type of wire you used? Also, what size Leds did you use for coop door status 5mm?
I have worked with breadboards before but, I’m use to solid single strand wire for breadboard. but that wouldn’t work well for this project.
Thanks,
Chris
hi chris,
thanks for the question. (can’t believe i forgot to insert that element within the website) for the interior of the coop, i was lucky enough to find some killer wire that was used for wells. (it was a 5 strand 20g, with 2 wraps of awesome foil shielding and a very tough rubber/plastic coated exterior… completely meant to live under water) for the controller, i used just the standard hook up wire (22g) (as you know, you can get this stuff anywhere, but here’s my amazon affiliate link, just in case: http://amzn.to/1yMbZ6w)
the leds were 5mm (red/green) here’s another amazon affiliate link to the assorted pack i purchased: http://amzn.to/1Epp896 (pretty cheap)
thanks again for the great questions.
//d
Dave – Great write up. You’ve given me lots of ideas for my own build.
I have a couple questions for you:
First, how did you mount the components inside the control box? It doesn’t look like you are using pcb standoffs.
Second, what made you decide to use DIN cables (5 pin) in some places and RCA cables in others? Also, I didn’t see the RCA female jacks on your Amazon parts list, so if you have a recommendation for those I’d appreciate it.
I appreciate your response and will be sure to give you credit when I blog about my own set up.
Thanks,
Derek
Hi Derek,
Thanks for the notes and kind words…
Inside the box, I sprayed the whole thing with Rustoleum Rubber Spray (http://amzn.to/1vssjcK) and then hot glued Velcro to hold the pieces in. It helped me while trying to organize the components. (I moved them around a bit to get it to fit correctly)
Some of the components needed more conductors that others, so I used the 5 Pin DINs, while others needed fewer, hence the RCAs. To be honest, the DINS were a complete PAIN to solder because the pins were tiny and so close in proximity to each other. (and I also have big hands and am not the most experienced solderer. =) Thanks for letting me know about the female RCAs. I used the Female Jack Chassis Mount: http://amzn.to/1B50wiS
Thanks again for writing in and I’m looking forward to seeing your coop project!
Cheers,
//D
I’m with you Sam, I have noticed that on the red board listed on this site has three control wires going to it but it seems as though the link shown that controls two motors that look like the ones listed on the page and in my had have different configurations and labels that what’s described here. What’s more looking at the two motor system, there appears to be only two control wires for each motor. This Chicken door only runs one so I would think that only two control wires are needed yet on the wiring diagram there seems to be three. On my board there are EnA, 5V, 5v, EnB on the top header and INA, INB, INC, IND on the bottom of the header where the top pins are shorted to the their respective 5V pins. Any help how to translate your wiring diagram into the pinouts that are contained on the board recommended would be greatly appreciated.
Hi Ed,
As I told Samuel, 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)
The fritzing diagram showing all connections is right on the coop door page http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/ (just scroll down a bit) it shows the exact connections.
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… and as always, show us your coop when you’re done. Would love to see it.
Cheers,
David –
This is amazing! As I began to research how I could automate my coop with my Mega, I stumbled across your page – and it is EXACTLY what I want to do. Tons of time saved in the sketch. The Fritz diagram is a nice addition. I wonder if you have a fritz of your finished product? I will be doing a bunch of the same things with mine, and I also would like the LED indicator for open, closed, and flashing error (probably use an RGB LED?)…
I don’t see your changes in the sketch for the led’s, and was wondering if you had that as well.
Thanks again – I cannot wait to get started on this project. I have been wanting an automatic door for 2 years now, and finally said “it’s time!”.
Hi Chris,
Thanks for the kind words… sorry for the late reply, just super busy.
I don’t have the full Fritzing Diagram yet, but once I have a bit more, I will complete a diagram for each section of the coop and record a video for each as well. If only there were more hours in the day!
=)
Cheers
Hello dave,
I recently purchased this stepper motor board:
http://www.amazon.com/NEOMART-Original-Quality-Stepper-Controller/dp/B00E58EA90/ref=sr_1_3?ie=UTF8&qid=1397095472&sr=8-3&keywords=L298N+Motor+Driver+Dual+H-Bridge
I am very new to circuitry, and i would love it if you could show me how to connect this board to the arduino and the motor. This is the board you listed on your website that you said you bought, but from the pics, it doesn’t look like it.
If you could provide a wiring diagram for this board and the arduino and breadboard, i would be thankful. Plus, you know what you’re doing and i dont want to burn down my coop here 🙂
hi samuel…
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 item with different layouts)
the fritzing diagram showing all connections is right on the coop door page http://davenaves.com/blog/interests-projects/chickens/chicken-coop/arduino-chicken-door/ (just scroll down a bit) it shows the exact connections.
here’s an image of another l298n that might also help you: https://www.ez-robot.com/uploads/motor-634669130571562500.jpg
(but note, he’s running 2 motors off of his)
show us all some pics when you’re done.
cheers,
//d