Raspberry Pi Coop Automation

jthornton

Crowing
Aug 30, 2017
3,946
7,339
472
Poplar Bluff, MO
My Coop
This thread is to show how I did my coop automation. I'm going to start as basic as I can. I have tried Arduino's and ESP8266 and other control devices and finally settled in with the Raspberry Pi 3B as my control of choice. The programming is in Python which to me is a bit easier to read than C which you must use for the Arduino and other devices that support Arduino code.

Some things to know up front, I do all my programming on a Linux PC. If you connect a keyboard, mouse and monitor to the Raspberry Pi you can program directly on the Rpi (Raspberry Pi). The Rpi uses a Linux Operating System, nothing to be afraid of, it just works better. The Rpi needs a connection to the Internet at bootup to get the current date and time, the Rpi doesn't have an onboard real time clock or battery/capacitor backup for date and time. The Rpi is a SBC (Single Board Computer), yes it's a fully functioning PC with USB ports, HDMI monitor connection and 40 pins that are used for I/O (Input/Output), these are use to connect the Rpi to the real world. You use the I/O to run your motor, turn lights on and off, get input from limit switches etc. The Rpi has some special pins, I2C or One Wire which can connect to things like temperature sensors (you can connect more than one as they have a unique address). The Rpi I/O is 3.3vdc so you need to be careful and select 3vdc relays, while 5v relays may work it's better to use the 3v versions.
pi3_gpio.png

Python is a programming language not the snake. The most simple program you could run is howdy.py
Python:
#!/usr/bin/python3
print("Howdy")
The first line is the shebang line that tells the system what to use to run the code.
The second line is a print statement that does what it looks like it should do.
To run the program the executable permission must be set. The easy way is to right click on the file in the file manager and select permissions then check off executable.
Then open a terminal in the same directory and type in ./howdy.py the ./ is needed otherwise the file will not be found.
Screenshot at 2020-10-30 08-25-25.png

You can also test snippets of code in a terminal without creating a file and I do that all the time to just test syntax and see my results. To start a Python session just type in python3 and press enter. Then you can test your code snippet.
Screenshot at 2020-10-30 08-29-15.png

Time to start my day, next up is the event loop and you will need one...

Got ahead of myself...

JT
 
Last edited:

jthornton

Crowing
Aug 30, 2017
3,946
7,339
472
Poplar Bluff, MO
My Coop
When you get a Raspberry Pi 3B you need to flash the Micro SD card with the Operating System. I usually get the CanaKit Raspberry Pi 3 B+ (B Plus) with 2.5A Power Supply and Heat Sinks. I have a tutorial for flashing the Rpi with the OS and instructions on setting up the OS to make it user friendly. If you don't have a way to flash the Micro SD card fear not, simply put it in an envelope with a stamped return envelope and mail it to me. This is one occasion I use PM's for, just PM me for my address and I'll be happy to flash the Micro SD card and return it to you.

@veedabowlu you can ask your questions in this thread. I've developed a much better code for my door and will be discussing it here and share it on my GitHub site.

Note: I do not have an associate account with Amazon and receive no kickback if you follow the link like most do. I only link to products that I have purchased for my own use with my money.

JT
 
Last edited:

jthornton

Crowing
Aug 30, 2017
3,946
7,339
472
Poplar Bluff, MO
My Coop
Ok time for the event loop. An event loop is a loop that runs every interval set by the code. The reason you need and even loop is to check to see if something needs to be done based on some reason typically it's time of day but in this example it will be the minute being even. This example is coop3a on my github account repository chicken-coop coop3.

Python:
#!/usr/bin/python3

import sys, time, signal
from datetime import datetime
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QTimer

class main():
    def __init__(self):
        #exit the program when ctrl c is pressed
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        # Set date on startup
        self.today = datetime.today().date()
        #initialize the self.done variable to False at start up
        self.done = False

        # Setup the heartbeat timer to run the update function every 100ms
        # 1 second has 1000 milliseconds
        updateTimer = QTimer()
        updateTimer.timeout.connect(self.update)
        updateTimer.start(100)

    def printMinute(self, m):
        print(f'The current even minute is {m}')

    def update(self):
        # this example shows a way to do something one time when an event happens
        # store the current minute in a local variable
        minute = datetime.now().minute
        # if the remainder of minute / 2 is equal to 0 and self.done is not True
        if minute % 2 == 0 and not self.done:
            # call the printMinute function and pass the minute to it
            self.printMinute(minute)
            # now set self.done to True so it only happens once
            self.done = True
        # else if the remainder of minute / 2 is not equal to 0 set self.done to False
        elif minute % 2 != 0:
            self.done = False

if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = main()
    sys.exit(app.exec_())
So when you run this code the update function is ran every 0.1 second and tests to see if the current minute is even if so the printMinute function is ran one time. This is important to grasp how this works. To exit the running program press Ctrl c.

Screenshot at 2020-10-30 18-07-48.png

Not to fancy but you gotta start with the basics... now that you have a program that has an event loop you can test for what ever you want and execute a function based on the result of that test.

Next up do something at sunrise...

JT
 

veedabowlu

In the Brooder
Sep 15, 2020
54
14
31
Southern Florida
@jthornton
I appreciate what you are doing... this is "python3 101"...
1) " #!/usr/bin/python3"
No such file or directory...
So I guess I have to make a new directory...how?
2) I did bounce into your coop3 GitHub...
Requirements...
Touch screen or monitor and keyboard and mouse.
is VNC ok?

Remember not a coder here... pullet steps.
 

jthornton

Crowing
Aug 30, 2017
3,946
7,339
472
Poplar Bluff, MO
My Coop
1) " #!/usr/bin/python3"
No such file or directory...
I need more information on what you have and what you did. Keep in mind that I do all my Python programs on Linux based Operating Systems. Python does work on Winddoze but I don't use it there. Every modern Linux based OS comes with Python 3.

When you run an executable file from a terminal in Linux the shebang refers to the characters "#!" when they are the first two characters in an interpreter directive as the first line of a text file. In a Unix-like operating system, the program loader takes the presence of these two characters as an indication that the file is a script, and tries to execute that script using the interpreter specified by the rest of the first line in the file. You might try #!/usr/bin/env/python3 if your on some strange Linux OS.

Well we are at chick steps now, no feathers yet... so I need to know what OS your using, what you did exactly.

I don't use VNC for anything anymore so I don't know.

If you have a PC running some flavor of Linux you can use SSH to connect to the Rpi and do most of the programming with that.

If your not using any kind of GUI (Graphical User Interface) in your program you can do everything over SSH.

Did you setup the Rpi per my tutorial?

JT
 
Last edited:

jthornton

Crowing
Aug 30, 2017
3,946
7,339
472
Poplar Bluff, MO
My Coop
The first step to getting astral information on the Rpi is to install the astral library on the Rpi. There are a couple of ways you can do this. With a monitor, keyboard and mouse connected to the Rpi and the Rpi connected to your LAN (Local Area Network) so it has access to the Internet or from another Linux based PC on your LAN using SSH (Secure Shell). The SSH protocol is a method for secure remote login from one computer to another. My Rpi setup tutorial explains how to enable SSH on the Rpi.

Either connect to the Rpi via SSH or open a terminal on the Rpi and do the following.

Code:
sudo apt install python3-pip
sudo pip3 install astral
In the SSH terminal or the terminal on the Rpi we can test the installation. In this screenshot I've connected to Coop3 using SSH then started the Python 3 interpreter and tested the installation of the libraries. Notice how the prompt changes as I log in to the Rpi and as I start the Python 3 interpreter.
Screenshot at 2020-10-31 06-22-00.png

After starting the Python 3 interpreter I loaded the libraries I needed with the following lines. You don't type in the >>> that is the Python prompt.
Python:
>>> from datetime import datetime
>>> from astral import LocationInfo
>>> from astral.sun import sun, daylight
>>> import pytz
Next I define a couple of constants, one for my time zone and one for my location.
Python:
>>> PBTZ = pytz.timezone('US/Central')
>>> PBMO = LocationInfo("Poplar Bluff", "Midwest", "US/Central", 36.873512, -90.488008)
Next I get the astral information for my location and time zone.
Python:
todaySun = sun(PBMO.observer, date=datetime.today(), tzinfo=PBTZ)
Once I have the astral information in the variable todaySun I can get sun event times.
Python:
>>> todaySun['dawn'].strftime('%I:%M %p')
'06:58 AM'
>>> todaySun['sunrise'].strftime('%I:%M %p')
'07:25 AM'
>>> todaySun['sunset'].strftime('%I:%M %p')
'06:04 PM'
>>> todaySun['dusk'].strftime('%I:%M %p')
'06:32 PM'
So now that we have the time of sun events we can compare that to the current time and decide on what to do. Just a note about what that .strftime('%I:%M %p') gobbly gook is that it returns a string formatted by the '%I:%M %p'. The %I is hour, the %M is minute and %p is am/pm. To compare datetime objects you must not convert it to a string.

Python:
>>> dawn = todaySun['dawn']
>>> dawn
datetime.datetime(2020, 10, 31, 6, 58, 16, 592413, tzinfo=<DstTzInfo 'US/Central' CDT-1 day, 19:00:00 DST>)
>>> dawn.strftime('%I:%M %p')
'06:58 AM'
To make typing easier I assigned the dawn event to a variable called dawn.
You can see the datetime object has a lot of information in it that the string does not have.

Python:
>>> datetime.now(PBTZ) < dawn
True
>>> datetime.now(PBTZ) > dawn
False
>>> datetime.now(PBTZ) <= dawn
True
>>> datetime.now(PBTZ) >= dawn
False
>>> datetime.now(PBTZ) == dawn
False
Making comparisons in Python < is less than, > greater than, <= less than or equal to, >= greater than or equal to, and lastly == equal to. So when I compare the current time in my time zone to dawn I can see the results. Doing this in a terminal line by line helps to understand what each statement does.

Rambling on done for now, chicken chores coming up soon.
JT
 
Last edited:

veedabowlu

In the Brooder
Sep 15, 2020
54
14
31
Southern Florida
@jthornton
You are flying right past me...
I am using VNC via windows accessing terminal and, as far as I can tell it works.
I can tell you the OS I have installed is ""Raspbian GNU/Linux 10 (buster)"
I originally did not follow your tutorial because I already had OS installed.
Now I'm looking at your tutorial, SSH, 1Wire, Remote GPIO (check)
your step 1&2 (check)
step 3 .xsessionrc is where I am stuck!!
 

veedabowlu

In the Brooder
Sep 15, 2020
54
14
31
Southern Florida
Raspbian 10...step by step would be totally awesome, as I'm trying to learn this, and I appreciate you not, just giving it but teaching it!

Little background about me.
I never have been book smart, but rather hands on smart (taking things apart) I remember my mother telling me stories of buying me a toy, her coming into my room mid day, seeing whatever toy in 50+ pieces, and by the time she came to get me for dinner the toy was reassembled, so she never yelled at me! Hence my current profession. I am also a science nut and understand experiments (how/why) things work. Math, other than simple functions (-+X % ÷)... Algebra forget it...I CANT grasp polynomials...as I can't touch feel it, although I can hold something somebody else created with one...
I give you mad props taking on this experiment trying to teach me python/Linux/Rpi


I googled some of the keywords such as the "PMBO..." (to learn by examples OR get an explanation) and the third link I get is YOU in/on a Chinese programmers page...DUDE your international :thumbsup
 

New posts New threads Active threads

Top Bottom