Simple chicken door with normal motor and H-bridge

Hi everyone!

This is my second post, and I want to share my project. It is a simple chicken door that works with a normal motor. I decided to share because I found a lot of projects that work with stepper motors, but I could’t find any that works with a normal motor. I hope that this post will help someone in the future!

Here I go! (And please, if someone finds something that I should edit, please tell it. I only want to contribute the best I can)

1. The problem

I have chickens, and I have to open and close them the door every day. So, why don’t make them a smart door?

Conditions:

  1. It is mandatory for this door to work every day and every night. It can’t be left open any night.
  2. Chikens don’t have a decent internet conection, so this project should be able to work without any internet conection
  3. The least component it takes, the cheaper it results!

2. The microcontroller

The first decision was choosing a microcontroler. Because of contidion #2, I should choose a microcontoler with a decent wifi antenna. So, I choose an ESP32 cam.

This microcontroler has a built-in antenna, but it also has a IPEX connector for a more powerfull one, so this was a good point. To do this, I had to change the small resistor near the IPEX connctor. I followed this guide, it is very well explained:

Now I have a controller with a few GPIO and a good wifi connection. It was time to think about the electronic design.

3. Other components

As I mentioned on the title, I also used a DC motor, one H-bridge, two limit switches, a buck converter and a DS1307 RTC module. This RTC was included because of condition #1 and #2, just in case of internet communication failure.

Here are the BOM. Note that links are only posted for reference, I already had all this stuff at home. Please search for a better price!
1x ESP32 CAM

1x DC Motor

1x DRV8871 H bridge

1x LM2596 Buck converter
https://www.pixelelectric.com/electronic-modules/voltage-regulator/buck-converter-step-down/lm2596-dc-dc-buck-converter-step-down-power-module/
1x DS1307 RTC module

2x Limit switch ME-8107

3. Electromechanic design

Before I begin, I must say that I am a mecanical engeneer. Usually, we aren’t very friendly to electronic designs, so my plan was to connect things together with wires, and maybe a resistor or two, and let them make the work. But it is working, so I’m happy with it :blush:

#3.1 Power design

At first, I wanted to power this door with a 5V 3A power supply, and a boost converter. But I had brownout problems, and thanks for the community advice, I changed to a 12V 4A power supply. I power the ESP through a Buck converter, and now it works like a charm.

Here is the link to my original post, if someone is curious:

3.2 ESP GPIOs

On the microcontroller side, I needed 2 GPIO for switches and 2 GPIO for binary sensors. In order to avoid any straping pins warnings, I choosed this ones:

  • Open door → 13
  • Close door → 33
  • Door openned → 14
  • Door closed → 4
  • I2C SDA → 1
  • I2C SCL → 3

Important note: I choosed this set because I tried others (2, 12, 15, 13, 16…) and I got problems, so I suggest this ones

Important note 2: In order to safely use GPIO 4, you should remove the built-in flash led for the camera.

Important note 3: GPIO33 is not easily accesible. You have to weld either on the 9th module pad or on the possitive side of the led. Here are the schematics:


I suggest to weld on the microcontroller pad. It has a little more space and weld seems stronger.

3.3 Circuit design

For safety reasons, I decided to route the connection between the ESP and the H-bridge through the limit switch. Doing this ensures that the motor will stop when it reaches any limit switch postion, so the door protects itself.

The rest of the connections are really simple:

  • ESP switch open door → Limit switch #1 NC → H bridge IN1
  • ESP switch close door → Limit switch #2 NC → H bridge IN2
  • ESP 3V3 source → Limit switch #1 NO → ESP sensor door open
  • ESP 3V3 source → Limit switch #2 NO → ESP sensor door closed
  • ESP SDA → RTC SDA
  • ESP SCL → RTC SCL

(I am working on a “formal” schematic. Now I only can post this draft I draw by hand. The RTC is not shown here):

Note: On my design I included two pull-down resistors because I wasn’t aware of INPUT_PULLUP. I think that they can be eliminated with anoter configuration, but this was my make :sweat_smile:

4. The code

I wanted the door to open when sun rises and to coles when it falls. So, I needed a time component, a sun component and a cover component. Here is mi configuration:

esphome:
  name: portagali
  friendly_name: Porta Galineiro
  on_boot:
    then:
      # read the RTC time once when the system boots
      ds1307.read_time:

i2c:
  sda: 1
  scl: 3
  scan: true
  id: bus_a

time:
- platform: homeassistant
  id: hora_homeassistant
  timezone: "Europe/Madrid"
  on_time_sync:
      then:
        # ... and update the RTC when the synchronization was successful
        ds1307.write_time:
- platform: ds1307
  timezone: "Europe/Madrid"
    # repeated synchronization is not necessary unless the external RTC
    # is much more accurate than the internal clock
  update_interval: never      


esp32:
  board: esp32cam
  framework: 
    type: arduino

# Enable logging
logger:
  level: DEBUG 

debug:
  update_interval: 1min

# Enable Home Assistant API
api:
  encryption:
    key: "It is a secret :)"

ota:
  password: "This is another secret :)"

wifi:
  #fast_connect: True #So vale cunha soa network
  networks:
  - ssid: !secret wifi_ssid2
    password: !secret wifi_password2
    # O 3 é Cacharrada
  - ssid: !secret wifi_ssid3
    password: !secret wifi_password3
  manual_ip:
    static_ip: 192.168.1.11
    gateway: 192.168.1.1
    subnet: 255.255.255.0
    dns1: 192.168.1.1
    dns2: 8.8.4.4
  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Galineiro Fallback Hotspot"
    password: "Galiñeiro"

captive_portal:

web_server:
  port: 80
 
text_sensor:
  - platform: debug
    device:
      name: "Dispositivo"
    reset_reason:
      name: "Ultimo reinicio por"
  - platform: wifi_info
    ip_address:
      name: Direccion IP
    ssid:
      name: Nome da rede
    scan_results:
      name: Redes Dispoñibles

sensor:
  - platform: sun
    type: elevation
    name: Elevación solar
    id: ElSol
  - platform: debug
    loop_time:
      name: "Tempo de bucle"


#Controladores, cara o drv do motor. Pines 13 e 33
switch:
- platform: gpio
  pin: GPIO13 #12 #GPIO2
  name: "Abrir galiñeiro"
  id: abrir_gali
  interlock: cerrar_gali
  internal: True
- platform: gpio
  pin: GPIO33 #15
  name: "Cerrar galiñeiro"
  id: cerrar_gali
  interlock: abrir_gali
  internal: True



# Sensores, desde o final de carrera NO. Cando a porta chega ao final de carrera, accionase, e desde o com chega unha señal que fai que pare. Ao mesmo tempo, o final de carrera desconecta o abrir.
binary_sensor:
- platform: gpio
  pin: GPIO14 #1 #4 2 no va, 13 no va, 16 no carga. Quitar o led 
  name: Galiñeiro Aberto
  id: gali_aberto
  #Estes controles son para actualizar o estado. Non andar a tocar os finales de carrera, por favor
  on_press:
    then:
    - cover.control:
        id: PortaGali
        position: 100%
- platform: gpio
  pin: GPIO4
  name: Galiñeiro Cerrado
  id: gali_cerrado
  #Estes controles son para actualizar o estado. Non andar a tocar os finales de carrera, por favor
  on_press:
    then:
    - cover.control:
        id: PortaGali
        position: 0%


sun:
  latitude: 42
  longitude: -8
  id: sol
  on_sunrise:
    # Primeiro, a condicion de abrir. Se todo vai ben, abrese e detectase polo final de carrera
    - elevation: 0.5°    
      then:
        - switch.turn_on: abrir_gali
        - logger.log: "Gali abrindo automatico"
    # Se o final de carrera non detectou, entonces baixamos un pouquiño, esperamos e volvemos a subir. Se non vai, repetimos. Para eso está o while
    - elevation: 0.8°    
      then:
        - while:
            condition:
              not:
                binary_sensor.is_on: gali_aberto
            then:
              - cover.control:
                  id: PortaGali
                  position: 90%
              - delay: 5s
              - switch.turn_on: abrir_gali
              - delay: 5s
              - logger.log: "Apertura fallida. Reabrindo..."
  on_sunset:
    # O mesmo para cerrar. Á noite, cando empece a faltar claridade, cerramos. Se todo vai ben, non facemos mais
    - elevation: -2°    
      then:
        - switch.turn_on: cerrar_gali
        - logger.log: "Gali cerrando automatico"
    # Pero se o fdc peta, temos un while moi majo que nos abre un chisco e nos volve cerrar        
    - elevation: -2.3°
      then:
        - while:
            condition:
              not:
                binary_sensor.is_on: gali_cerrado
            then:
              - cover.control:
                  id: PortaGali
                  position: 10%
              - delay: 5s
              - switch.turn_on: cerrar_gali
              - delay: 5s
              - logger.log: "Peche fallido. Recerrando..."

cover:
  - platform: endstop
    name: "Porta Gali"
    id: PortaGali
    open_action:
      - switch.turn_on: abrir_gali
    open_duration: 30s
    open_endstop: gali_aberto
    close_action:
      - switch.turn_on: cerrar_gali
    close_duration: 30s
    close_endstop: gali_cerrado
    stop_action:
      - switch.turn_off: abrir_gali
      - switch.turn_off: cerrar_gali

Change the wifi, home assistant, and encriptation setting according to your setup. Probably you should also edit sun location and cover times. And probably you can get rid of the debug component and debug text sensor. But this code works.

(Sorry for the coments. They are written in Galician, because at first I didn’t think on sharing my project. If someone needs help, tell it to me)

Note: Someone might notice the two Whiles inside the sun component. They have a reason. Sometimes, the door closes properly, but the limit switch doesn’t send the signal to the ESP. These whiles moves the door a little up or down and closes or opens it again. It is only for sensor purposes.

And here is the result. The last 144 hours it worked like a charm (now it is summer and the days here are longer than the nigths):
imaxe

And here is the door itself:

  • All the electronics is inside the sealed box on the top
  • The frame is built with a recicled window frame :rofl:.
  • The limit swithches are triggered with a long screw:
  • The motor is supported with a 3D printed support and a 3D printed pulley. If someone is interested, I can put the 3D files on thingiverse.
  • Pulleys are recicled clothes rope pulleys
  • The orange cables are 4-wire signal cable. They are connected to the ESP throug a screw connector
  • The rightest top black swich is a completely manual switch. It manually activates the H-bridge just in case the ESP dies.

And there is all! I hope this post will help someone in the future!

Thank you for reading!!! Greetings from Galicia!!!

3 Likes

Very nice! That was a very detailed and well written guide.

I looked at those limit switches you used and linked to. They were 40$ each? I hope not! If it were me, I would have used something else cheape and smaller. I found similar ones on amazon that were 2 for 10$.

Personally, I would use reed switches if I made it. They are very relaible, small, and some come sealed(waterproof). Most importantly they dont use a long mechanical arm for a switch. That long arm can get snagged, break, or allow exteral factors toggle the switch and cause false positives.

If your the type of person who likes a challenge, I have one for you!

So, the door closes at sunset? How does it know all the chickens are inside before closing? What stops it from closing on a chicken and potentially harming it or your components? What happens if a scenario like, 2 chickens get left out but, walk up to the closed door attempting to get in? How can you allow them in?

That is my challenge I propose to you!

Here are a couple resources that will help if you accept.

Hi @Fallingaway24!

Of course not! I originally planned to use normal endstops, like those that are on a 3D printer. But one relative saw me, and gave me four endstops of that kind. So, they come me at cost 0 :sweat_smile:

But I will take note of your idea. For now, I will install this door, and if I see any problems, I will replace them. Thank you so much!

:smirk:
Yes, I know that this project lacks many things that I would like to include. In fact, as I am using an ESP cam, I would like to install a camera and see how many chickens do I have in. This camera would take a picture when the sun goes below horizon, and if I don’t see enough chickens, I would have to open then. Maybe in a future I could add some cool stuff like machine vision or something like that, but now I wanted it to work.

On the other hand, as I saw that the ESP was a little “overwhelmed”, I didnt want to charge it too much with another tasks. But now, having solved the brownout problems, I think that I could make it a little more complex.

I have already though on counting chikens, as I have already some laser barriers like this:
imagen
https://es.aliexpress.com/item/1005004991523717.html
And now, thanks to your video I know how to use them :smiling_imp: Thank you again!

And finally, the last thing I wanted to add were two load cell sensors, one for food and another for water.
imagen

The main problem for adding all of these cool things is that I run out of GPIOs :rofl:

So, the most probable option is that I will add a second ESP to manage all this things. I am pretty sure that the ESP cam probably can manage all of this, but I think that it is a little safer to use two separate ESPs. Please, tell me if I’m wrong

Oh, and I don’t have any answers for the poor chicken outside. But I will think about it.(Probably I will last a little to answer, because now I have an old fridge to resurrect :rofl:)

Oh, well if its free that changes things. Your definitely off to a good start and you can always add things later on too. Speaking of which, its always a good idea to plan for expansion and leave yourself gpios, or for example you wanted to add lights, you can always add the relay or mosfet it there and then when you have the lights to install, your in a gpod position because you already have it mostly done.

Running out of gpios? Oh no! Thats not a real thing… you can slap a variety of gpio expanders onto a project and add as many gpios as you want, that should never be a constraint on your project.

If you do use them, just make sure you do your due diligence becsuse some can only be used for general I/O and some can be used for I/O amd PWM.

For stuff like this, you can most definitely keep it all on 1 esp board and it wont even break a sweat from it.