Automation: Watering the Plants

With the physical and digital monitoring system setup, we can now start automating the process so that the plants will be watered based on moisture readings.

***WARNING*** You will be working with electrical components so please be very careful. You take on any and all risks and liabilities in case of failure (fire, electrocution, etc.) if you try to implement steps from a guide written by some random guy on the internet. I am not liable for what you do. Don’t be stupid. Also, these instructions are for myself in the United States, so think EXTRA CAREFUL if you try to apply this outside the states because it may not apply. ***YOU HAVE BEEN WARNED***

Components

To start with, you'll need the following additional components:

STEP 1: INSTALL THE RELAY HAT/SHIELD

HATs or Shields are custom boards that sit on top of the Raspberry Pi to give them additional capabilities, like Relay control in our case. Unfortunately that means you will need to remove the pin connections on the raspberry pi placed so far as the Relay HAT will use and replace those pins for the existing connections. Be careful to remember the exact locations of the pins as you will need to place them on the HAT pins in the same location after the shield is installed. Take a couple of pictures close up of the exact pin connections and far back of the wires as a whole to help. I am going to defer to the wiki for the installation guide as that is all you should need. It’s pretty plug and play as long as you put it on straight.
RELAY HAT INSTALLATION INSTRUCTIONS
With the HAT installed, reinstall all of the pins exactly where they were before (your pictures will help here). Boot up the raspberry pi and make sure the website updates with new data after 15 minutes (go for a quick walk to clear your head after installing and reinstalling everything). If you have new measurements everything has been properly reinstalled and you are good to continue. If you are not getting reads, triple check that all of the wiring is connected properly and keep trying until you get new measurements continuing.

STEP 2: TEST THE RELAY

Before powering off the device and installing the pump cables, we should test the HAT relays to make sure they are properly functioning. Create a text file named RelayTest.py with the following code:

import time
import datetime
from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(31,GPIO.OUT)
GPIO.setup(33,GPIO.OUT)

try:
    print(str(datetime.datetime.now())+' on\n')
    GPIO.output(31,GPIO.HIGH)
    sleep(10)
    print(str(datetime.datetime.now())+' off\n')
    GPIO.output(31,GPIO.LOW)
    sleep(10)
    print(str(datetime.datetime.now())+' on\n')
    GPIO.output(33,GPIO.HIGH)
    sleep(10)
    print(str(datetime.datetime.now())+' off\n')
    GPIO.output(33,GPIO.LOW)

finally:
	GPIO.cleanup()

Connect to the device via WinSCP and drop the file into the folder where you are keeping scripts. Connect via PuTTY to terminal on the device and navigate to the folder where the test file was dropped then enter the following command to run the test script:

python3 RelayTest.py

The terminal should have messages showing on and off as the first 2 relays on the device click on and off. Each relay has a light red light that will light up during the test to show that the connection is active. If everything checks out, you can power down the device. Remember to ‘sudo shutdown now’ command in terminal before turning off the device power to ensure everything shuts down properly.

STEP 3: INSTALL THE ELECTRICAL CABLE TO THE RELAY

Preparing the spliced cables

After installing the HAT and reinstalling the pins, to connect the spliced electric cables to the Relay 4 Zero 3V 4 Channel Relay Shield, we now need to prepare and install the pump electrical cable to the relay HAT. In the electric cable you will see there are 2 sub cables connected to the plug with 2 different sized prongs. With the pump electrical cable unplugged, you want to identify the sub cable attached to the wider electric plug. See the green in the image below:

You will want to follow the cable connected to the wide plug about 1.5 to 2 feet away from the plug then make a cut only to the wide plug cable. DO NOT CUT BOTH CABLES. You will have a bad time if you cut both cables because at that point you either need to reconnect both and try again or buy another pump. So don’t cut both cables. Learn from my fail. Anyway, with the wide plug cable cut, you can peel back both sides from the other cable about 1-2 inches to give you room to work with. Grab your wire cutter and carefully select the size of cut on the cables which will remove the outer plastic but not cut the inner copper. On my cutter it was the second circle. You can test on the very end of one of the 2 flat plug cables to be sure. Once confident measure out maybe 1/4 of an inch from the end, cut, then while still holding the cut carefully remove the plastic from the wire. Repeat this on the other flat plug wire. Twist the bare wire ends gently so that they are easier to work with in the relay.

Identify the Relay Terminals

The Relay hat in my project has 4 relays available (the black boxes above). Each relay contains 3 terminals (the green boxes) with labels highlighted in purple:

  • (COM) Common: The other side of the line going to the relay

  • (NC) Normally Closed: The side of the line coming from the outlet where electric current is expected to be off while the plug is in. Not our use case.

  • (NO) Normally Open: The side of the line coming from the outlet where electric current is expected to be on while the plug is in. We are using this.

Locate the Common (COM) and Normally Open (NO) terminals on the top relay (furthest from in the HDMI port). Untighten the terminal screws using the tiny screwdriver for the COM and NO ports.

Connect the Cables

Connect one end of the spliced cable to the COM terminal and the other end to the NO terminal. You will probably need to sort of loop the other part of the pump cable similar to the above photo to make the connection work. If you are extra motivated, you can solder on some additional wires to the wide plug cable ends, heat-shrink them in plastic for safety, then connect the longer wire ends to the relay. I was lazy. Either way, once each end of the cable is in the relay, tighten the relay screws and make sure the connection is snug.

STEP 4: TEST THE WIRED RELAY AND SETUP PUMP

With both wires snugly installed into the COM and NO terminals of the relay, we can now write finally test the pump. Using the relay test script in step 2 and repeating the step by running RelayTest.py. Check to see if the pump turns on while relay 1 is being tested. You can do this with or without water. If the pump turns on, you are in business. Grab a spare deep tupperware container and fill it with water. Cut a hole in the lid large enough for the plastic pump tube and the electric cord then drop in the pump and seal everything up. Place the watering tube around your plant and you are done.

STEP 5: SCRIPT AND SCHEDULE WATERINGS

Plants for the most only need water when their moisture level is too low. In this case the plant watering script is going to run on an hourly schedule to see if the moisture reading is getting too high. Based on my experience with these sensors, that is around 600. So the script below will check to see if the measurements of the plant with the watering tube is lower than 600 in the database and if so water the plant for 10 seconds. Copy the below script into a text file named ‘WateringProtocol.py’:

import time
import datetime
from time import sleep
import RPi.GPIO as GPIO
import MySQLdb

# Database credentials
db_config = {
    'host': 'localhost',
    'user': 'exampleuser',
    'password': 'password',
    'database': 'SensorDataDB'
}

# GPIO setup
GPIO.setmode(GPIO.BOARD)
GPIO.setup(31, GPIO.OUT)

# Threshold for moisture sensor reading
MOISTURE_THRESHOLD = 600

def check_moisture_and_activate_relay():
    try:
        # Connect to the database
        conn = MySQLdb.connect(**db_config)
        cursor = conn.cursor()
        
        # Get the most recent tomato moisture reading
        cursor.execute("""
            SELECT sensorRead 
            FROM sensorMeasurements 
            WHERE sensorOI = 1  -- Assuming sensorOI 1 is for Roma Tomato
            ORDER BY timestamp DESC 
            LIMIT 1
        """)
        result = cursor.fetchone()
        if result:
            moisture_reading = result[0]
            print(f"Moisture reading: {moisture_reading}")
            
            if moisture_reading > MOISTURE_THRESHOLD:
                print(str(datetime.datetime.now()) + ' - Moisture above threshold, activating relay.')
                GPIO.output(31, GPIO.HIGH)
                sleep(10)
                GPIO.output(31, GPIO.LOW)
                print('Relay deactivated after 10 seconds.')
            else:
                print(str(datetime.datetime.now()) + ' - Moisture below threshold, relay not activated.')
        else:
            print(str(datetime.datetime.now()) + ' - No moisture reading found.')

    except MySQLdb.Error as e:
        print(f"Error connecting to MySQL: {e}")
    finally:
        cursor.close()
        conn.close()
        GPIO.cleanup()

if __name__ == "__main__":
    check_moisture_and_activate_relay()

Connect to the device via WinSCP and drop the file into the folder where you are keeping scripts. As with the previous step, you will want to be careful when setting up the cron job. In PuTTY Terminal for the device enter the following command to enter the cron file:

crontab -e

In Terminal a file will pop up in Nano and you will want to carefully move the cursor to the bottom and add the following line:

0 * * * * /usr/bin/python3 /Path/To/Scripts/WateringProtocol.py >> /Path/To/Scripts/WateringProtocol.log 2>&1

Adjust the above line to reflect the path on device where the script is located then add it to the bottom of the crontab file by right clicking. Then hit Ctrl-O to save, then Ctrl-X to leave Nano. You should return to normal Terminal command line and everything will be complete. Your system should now automatically water your plant when it gets above a certain moisture threshold.

By setting up this system, you can achieve consistent and reliable plant watering. The moisture sensor ensures that plants receive water only when needed, preventing both under- and over-watering. This automation not only saves time but also optimizes plant health and growth. Also if you have made it this far successfully, you have accomplished a fairly impressive amount. You have worked cross functionally across hardware, backend software, front end visualizations, and data engineering. Congratulations! Enjoy the (hopefully literal) fruits of your labor where your only work is making sure there is enough water.

Previous
Previous

Exploratory Data Analysis: Using R and Python

Next
Next

Exploratory Data Analysis: Visualizing Sensor Insights